commit d6bf8e19434b93efbf73548967c78359791a7120 Author: Rinjae Date: Thu Oct 23 13:21:43 2025 +0900 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..da26d0a --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*.war +.apt_src +.settings +dist +build +.classpath +.project +*.log +*.tmp +bin +tmp \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb893fe --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# BAPWeb + +## 빌드 방법 +### Windows - git bash 예시 +```bash +export PATH=${PATH}:/c/eactive/apps/apache-ant-1.10.15/bin + +ant clean build +``` \ No newline at end of file diff --git a/WebContent/HolidayBasis.jsp b/WebContent/HolidayBasis.jsp new file mode 100644 index 0000000..cbafde5 --- /dev/null +++ b/WebContent/HolidayBasis.jsp @@ -0,0 +1,69 @@ +<%@ page import="java.util.ArrayList"%> +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="com.eactive.eai.batch.scheduler.ScheduleBasisManager"%> +<%@ page import="com.eactive.eai.batch.common.StringUtil"%> + +<% + + String day = StringUtil.nvlTrim(request.getParameter("day" ), ""); + + ArrayList holicodes = null; + + if (day != null && day.length() >0){ + holicodes = ScheduleBasisManager.getInstance().getIntervalTypes( day ); + } + +%> + + + + + Informations + + + + +

+ Informations

+

+ +
+ + + + +
+ + + + + + +
¥ :  
+

+ + <% + if (holicodes !=null && holicodes.size() > 0) { + for (int j=0; j + + + + + + + +
  CODE :   

+ <% + } + } + %> + + + \ No newline at end of file diff --git a/WebContent/META-INF/MANIFEST.MF b/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/WebContent/META-INF/context.xml b/WebContent/META-INF/context.xml new file mode 100644 index 0000000..cf7e5d6 --- /dev/null +++ b/WebContent/META-INF/context.xml @@ -0,0 +1,33 @@ + + + + + WEB-INF/web.xml + WEB-INF/tomcat-web.xml + ${catalina.base}/conf/web.xml + . + + + + + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/applicationContext.xml b/WebContent/WEB-INF/applicationContext.xml new file mode 100644 index 0000000..f51b87e --- /dev/null +++ b/WebContent/WEB-INF/applicationContext.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WebContent/WEB-INF/jms/applicationContext-jms.xml b/WebContent/WEB-INF/jms/applicationContext-jms.xml new file mode 100644 index 0000000..9e4f4c1 --- /dev/null +++ b/WebContent/WEB-INF/jms/applicationContext-jms.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + diff --git a/WebContent/WEB-INF/jms/applicationContext-jms.xml.P b/WebContent/WEB-INF/jms/applicationContext-jms.xml.P new file mode 100644 index 0000000..40580b8 --- /dev/null +++ b/WebContent/WEB-INF/jms/applicationContext-jms.xml.P @@ -0,0 +1,34 @@ +applicationContext-jms.xml + + + + + + + + + + + + + + + diff --git a/WebContent/WEB-INF/jms/applicationContext-jms.xml.Q b/WebContent/WEB-INF/jms/applicationContext-jms.xml.Q new file mode 100644 index 0000000..2385e05 --- /dev/null +++ b/WebContent/WEB-INF/jms/applicationContext-jms.xml.Q @@ -0,0 +1,34 @@ +applicationContext-jms.xml + + + + + + + + + + + + + + + diff --git a/WebContent/WEB-INF/lib/INICrypto_v4.2.9.jar b/WebContent/WEB-INF/lib/INICrypto_v4.2.9.jar new file mode 100644 index 0000000..6d00e9f Binary files /dev/null and b/WebContent/WEB-INF/lib/INICrypto_v4.2.9.jar differ diff --git a/WebContent/WEB-INF/lib/INISAFECore_v2.2.49.jar b/WebContent/WEB-INF/lib/INISAFECore_v2.2.49.jar new file mode 100644 index 0000000..24633ed Binary files /dev/null and b/WebContent/WEB-INF/lib/INISAFECore_v2.2.49.jar differ diff --git a/WebContent/WEB-INF/lib/INISAFENet_v7.2.65_NS.jar b/WebContent/WEB-INF/lib/INISAFENet_v7.2.65_NS.jar new file mode 100644 index 0000000..d4e6a63 Binary files /dev/null and b/WebContent/WEB-INF/lib/INISAFENet_v7.2.65_NS.jar differ diff --git a/WebContent/WEB-INF/lib/INISAFEPKI_v1.1.49.jar b/WebContent/WEB-INF/lib/INISAFEPKI_v1.1.49.jar new file mode 100644 index 0000000..45c5a37 Binary files /dev/null and b/WebContent/WEB-INF/lib/INISAFEPKI_v1.1.49.jar differ diff --git a/WebContent/WEB-INF/lib/activemq-broker-5.15.13.jar b/WebContent/WEB-INF/lib/activemq-broker-5.15.13.jar new file mode 100644 index 0000000..08b1660 Binary files /dev/null and b/WebContent/WEB-INF/lib/activemq-broker-5.15.13.jar differ diff --git a/WebContent/WEB-INF/lib/activemq-client-5.15.13.jar b/WebContent/WEB-INF/lib/activemq-client-5.15.13.jar new file mode 100644 index 0000000..a5296a4 Binary files /dev/null and b/WebContent/WEB-INF/lib/activemq-client-5.15.13.jar differ diff --git a/WebContent/WEB-INF/lib/activemq-console-5.15.13.jar b/WebContent/WEB-INF/lib/activemq-console-5.15.13.jar new file mode 100644 index 0000000..124b405 Binary files /dev/null and b/WebContent/WEB-INF/lib/activemq-console-5.15.13.jar differ diff --git a/WebContent/WEB-INF/lib/activemq-spring-5.15.13.jar b/WebContent/WEB-INF/lib/activemq-spring-5.15.13.jar new file mode 100644 index 0000000..a738525 Binary files /dev/null and b/WebContent/WEB-INF/lib/activemq-spring-5.15.13.jar differ diff --git a/WebContent/WEB-INF/lib/bcpkix-jdk15on-1.70.jar b/WebContent/WEB-INF/lib/bcpkix-jdk15on-1.70.jar new file mode 100644 index 0000000..07223f6 Binary files /dev/null and b/WebContent/WEB-INF/lib/bcpkix-jdk15on-1.70.jar differ diff --git a/WebContent/WEB-INF/lib/bcprov-jdk15on-1.70.jar b/WebContent/WEB-INF/lib/bcprov-jdk15on-1.70.jar new file mode 100644 index 0000000..0e4198e Binary files /dev/null and b/WebContent/WEB-INF/lib/bcprov-jdk15on-1.70.jar differ diff --git a/WebContent/WEB-INF/lib/commons-codec-1.6.jar b/WebContent/WEB-INF/lib/commons-codec-1.6.jar new file mode 100644 index 0000000..ee1bc49 Binary files /dev/null and b/WebContent/WEB-INF/lib/commons-codec-1.6.jar differ diff --git a/WebContent/WEB-INF/lib/commons-dbcp-1.4.jar b/WebContent/WEB-INF/lib/commons-dbcp-1.4.jar new file mode 100644 index 0000000..c4c1c4f Binary files /dev/null and b/WebContent/WEB-INF/lib/commons-dbcp-1.4.jar differ diff --git a/WebContent/WEB-INF/lib/commons-lang3-3.14.0.jar b/WebContent/WEB-INF/lib/commons-lang3-3.14.0.jar new file mode 100644 index 0000000..da9302f Binary files /dev/null and b/WebContent/WEB-INF/lib/commons-lang3-3.14.0.jar differ diff --git a/WebContent/WEB-INF/lib/commons-net-3.12.0.jar b/WebContent/WEB-INF/lib/commons-net-3.12.0.jar new file mode 100644 index 0000000..c12378e Binary files /dev/null and b/WebContent/WEB-INF/lib/commons-net-3.12.0.jar differ diff --git a/WebContent/WEB-INF/lib/commons-pool2-2.12.1.jar b/WebContent/WEB-INF/lib/commons-pool2-2.12.1.jar new file mode 100644 index 0000000..a8d1f10 Binary files /dev/null and b/WebContent/WEB-INF/lib/commons-pool2-2.12.1.jar differ diff --git a/WebContent/WEB-INF/lib/eddsa-0.3.0.jar b/WebContent/WEB-INF/lib/eddsa-0.3.0.jar new file mode 100644 index 0000000..31a271d Binary files /dev/null and b/WebContent/WEB-INF/lib/eddsa-0.3.0.jar differ diff --git a/WebContent/WEB-INF/lib/ezgatorconsoleclient.jar b/WebContent/WEB-INF/lib/ezgatorconsoleclient.jar new file mode 100644 index 0000000..8731414 Binary files /dev/null and b/WebContent/WEB-INF/lib/ezgatorconsoleclient.jar differ diff --git a/WebContent/WEB-INF/lib/ezgatormodule.jar b/WebContent/WEB-INF/lib/ezgatormodule.jar new file mode 100644 index 0000000..e54c5ca Binary files /dev/null and b/WebContent/WEB-INF/lib/ezgatormodule.jar differ diff --git a/WebContent/WEB-INF/lib/geronimo-j2ee-management_1.1_spec-1.0.1.jar b/WebContent/WEB-INF/lib/geronimo-j2ee-management_1.1_spec-1.0.1.jar new file mode 100644 index 0000000..0701ae0 Binary files /dev/null and b/WebContent/WEB-INF/lib/geronimo-j2ee-management_1.1_spec-1.0.1.jar differ diff --git a/WebContent/WEB-INF/lib/geronimo-jms_1.1_spec-1.1.1.jar b/WebContent/WEB-INF/lib/geronimo-jms_1.1_spec-1.1.1.jar new file mode 100644 index 0000000..4f5e646 Binary files /dev/null and b/WebContent/WEB-INF/lib/geronimo-jms_1.1_spec-1.1.1.jar differ diff --git a/WebContent/WEB-INF/lib/geronimo-jta_1.0.1B_spec-1.1.1.jar b/WebContent/WEB-INF/lib/geronimo-jta_1.0.1B_spec-1.1.1.jar new file mode 100644 index 0000000..b41550e Binary files /dev/null and b/WebContent/WEB-INF/lib/geronimo-jta_1.0.1B_spec-1.1.1.jar differ diff --git a/WebContent/WEB-INF/lib/hawtbuf-1.11.jar b/WebContent/WEB-INF/lib/hawtbuf-1.11.jar new file mode 100644 index 0000000..c7042a6 Binary files /dev/null and b/WebContent/WEB-INF/lib/hawtbuf-1.11.jar differ diff --git a/WebContent/WEB-INF/lib/httpclient5-5.2.1.jar b/WebContent/WEB-INF/lib/httpclient5-5.2.1.jar new file mode 100644 index 0000000..b9cdadc Binary files /dev/null and b/WebContent/WEB-INF/lib/httpclient5-5.2.1.jar differ diff --git a/WebContent/WEB-INF/lib/httpclient5-fluent-5.2.1.jar b/WebContent/WEB-INF/lib/httpclient5-fluent-5.2.1.jar new file mode 100644 index 0000000..8972e81 Binary files /dev/null and b/WebContent/WEB-INF/lib/httpclient5-fluent-5.2.1.jar differ diff --git a/WebContent/WEB-INF/lib/httpcore5-5.2.1.jar b/WebContent/WEB-INF/lib/httpcore5-5.2.1.jar new file mode 100644 index 0000000..5e779f3 Binary files /dev/null and b/WebContent/WEB-INF/lib/httpcore5-5.2.1.jar differ diff --git a/WebContent/WEB-INF/lib/i2p-2.8.0.jar b/WebContent/WEB-INF/lib/i2p-2.8.0.jar new file mode 100644 index 0000000..88974ef Binary files /dev/null and b/WebContent/WEB-INF/lib/i2p-2.8.0.jar differ diff --git a/WebContent/WEB-INF/lib/icu4j-77.1.jar b/WebContent/WEB-INF/lib/icu4j-77.1.jar new file mode 100644 index 0000000..65f5973 Binary files /dev/null and b/WebContent/WEB-INF/lib/icu4j-77.1.jar differ diff --git a/WebContent/WEB-INF/lib/jcl-over-slf4j-2.0.9.jar b/WebContent/WEB-INF/lib/jcl-over-slf4j-2.0.9.jar new file mode 100644 index 0000000..2cd05fc Binary files /dev/null and b/WebContent/WEB-INF/lib/jcl-over-slf4j-2.0.9.jar differ diff --git a/WebContent/WEB-INF/lib/jep-2.3.0.jar b/WebContent/WEB-INF/lib/jep-2.3.0.jar new file mode 100644 index 0000000..108ba20 Binary files /dev/null and b/WebContent/WEB-INF/lib/jep-2.3.0.jar differ diff --git a/WebContent/WEB-INF/lib/jsch-0.1.55.jar b/WebContent/WEB-INF/lib/jsch-0.1.55.jar new file mode 100644 index 0000000..c6fd21d Binary files /dev/null and b/WebContent/WEB-INF/lib/jsch-0.1.55.jar differ diff --git a/WebContent/WEB-INF/lib/jul-to-slf4j-2.0.17.jar b/WebContent/WEB-INF/lib/jul-to-slf4j-2.0.17.jar new file mode 100644 index 0000000..66c0a7b Binary files /dev/null and b/WebContent/WEB-INF/lib/jul-to-slf4j-2.0.17.jar differ diff --git a/WebContent/WEB-INF/lib/logback-access-1.2.13.jar b/WebContent/WEB-INF/lib/logback-access-1.2.13.jar new file mode 100644 index 0000000..e997f15 Binary files /dev/null and b/WebContent/WEB-INF/lib/logback-access-1.2.13.jar differ diff --git a/WebContent/WEB-INF/lib/logback-classic-1.2.13.jar b/WebContent/WEB-INF/lib/logback-classic-1.2.13.jar new file mode 100644 index 0000000..105b2f2 Binary files /dev/null and b/WebContent/WEB-INF/lib/logback-classic-1.2.13.jar differ diff --git a/WebContent/WEB-INF/lib/logback-core-1.2.13.jar b/WebContent/WEB-INF/lib/logback-core-1.2.13.jar new file mode 100644 index 0000000..36b0805 Binary files /dev/null and b/WebContent/WEB-INF/lib/logback-core-1.2.13.jar differ diff --git a/WebContent/WEB-INF/lib/ojdbc8-19.28.0.0.jar b/WebContent/WEB-INF/lib/ojdbc8-19.28.0.0.jar new file mode 100644 index 0000000..fab342f Binary files /dev/null and b/WebContent/WEB-INF/lib/ojdbc8-19.28.0.0.jar differ diff --git a/WebContent/WEB-INF/lib/orai18n-19.8.0.0.jar b/WebContent/WEB-INF/lib/orai18n-19.8.0.0.jar new file mode 100644 index 0000000..cc1cbd2 Binary files /dev/null and b/WebContent/WEB-INF/lib/orai18n-19.8.0.0.jar differ diff --git a/WebContent/WEB-INF/lib/quartz-2.2.1.jar b/WebContent/WEB-INF/lib/quartz-2.2.1.jar new file mode 100644 index 0000000..7cf3ca4 Binary files /dev/null and b/WebContent/WEB-INF/lib/quartz-2.2.1.jar differ diff --git a/WebContent/WEB-INF/lib/quartz-2.3.2.jar b/WebContent/WEB-INF/lib/quartz-2.3.2.jar new file mode 100644 index 0000000..8b73882 Binary files /dev/null and b/WebContent/WEB-INF/lib/quartz-2.3.2.jar differ diff --git a/WebContent/WEB-INF/lib/rms-client-vo.jar b/WebContent/WEB-INF/lib/rms-client-vo.jar new file mode 100644 index 0000000..8724f02 Binary files /dev/null and b/WebContent/WEB-INF/lib/rms-client-vo.jar differ diff --git a/WebContent/WEB-INF/lib/rms-concurrent.jar b/WebContent/WEB-INF/lib/rms-concurrent.jar new file mode 100644 index 0000000..32d1407 Binary files /dev/null and b/WebContent/WEB-INF/lib/rms-concurrent.jar differ diff --git a/WebContent/WEB-INF/lib/rms-log4j.jar b/WebContent/WEB-INF/lib/rms-log4j.jar new file mode 100644 index 0000000..46f1f8f Binary files /dev/null and b/WebContent/WEB-INF/lib/rms-log4j.jar differ diff --git a/WebContent/WEB-INF/lib/rms-mina.jar b/WebContent/WEB-INF/lib/rms-mina.jar new file mode 100644 index 0000000..0e695d8 Binary files /dev/null and b/WebContent/WEB-INF/lib/rms-mina.jar differ diff --git a/WebContent/WEB-INF/lib/slf4j-api-1.7.36.jar b/WebContent/WEB-INF/lib/slf4j-api-1.7.36.jar new file mode 100644 index 0000000..a42ee10 Binary files /dev/null and b/WebContent/WEB-INF/lib/slf4j-api-1.7.36.jar differ diff --git a/WebContent/WEB-INF/lib/spring-aop-5.3.17.jar b/WebContent/WEB-INF/lib/spring-aop-5.3.17.jar new file mode 100644 index 0000000..f1136a6 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-aop-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-aop-5.3.27.jar b/WebContent/WEB-INF/lib/spring-aop-5.3.27.jar new file mode 100644 index 0000000..9fcd3e1 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-aop-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-aspects-5.3.17.jar b/WebContent/WEB-INF/lib/spring-aspects-5.3.17.jar new file mode 100644 index 0000000..310bdee Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-aspects-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-aspects-5.3.27.jar b/WebContent/WEB-INF/lib/spring-aspects-5.3.27.jar new file mode 100644 index 0000000..1cbf456 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-aspects-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-beans-5.3.17.jar b/WebContent/WEB-INF/lib/spring-beans-5.3.17.jar new file mode 100644 index 0000000..a1975e8 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-beans-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-beans-5.3.27.jar b/WebContent/WEB-INF/lib/spring-beans-5.3.27.jar new file mode 100644 index 0000000..52b02cb Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-beans-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-context-5.3.17.jar b/WebContent/WEB-INF/lib/spring-context-5.3.17.jar new file mode 100644 index 0000000..632e987 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-context-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-context-5.3.27.jar b/WebContent/WEB-INF/lib/spring-context-5.3.27.jar new file mode 100644 index 0000000..af9d1ad Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-context-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-context-support-5.3.17.jar b/WebContent/WEB-INF/lib/spring-context-support-5.3.17.jar new file mode 100644 index 0000000..4a3cf87 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-context-support-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-context-support-5.3.27.jar b/WebContent/WEB-INF/lib/spring-context-support-5.3.27.jar new file mode 100644 index 0000000..c8723d0 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-context-support-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-core-5.3.17.jar b/WebContent/WEB-INF/lib/spring-core-5.3.17.jar new file mode 100644 index 0000000..64f1e85 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-core-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-core-5.3.27.jar b/WebContent/WEB-INF/lib/spring-core-5.3.27.jar new file mode 100644 index 0000000..3af41f5 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-core-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-expression-5.3.17.jar b/WebContent/WEB-INF/lib/spring-expression-5.3.17.jar new file mode 100644 index 0000000..d94ed4f Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-expression-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-expression-5.3.27.jar b/WebContent/WEB-INF/lib/spring-expression-5.3.27.jar new file mode 100644 index 0000000..8f203fa Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-expression-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-instrument-5.3.17.jar b/WebContent/WEB-INF/lib/spring-instrument-5.3.17.jar new file mode 100644 index 0000000..a4c7b9f Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-instrument-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-instrument-5.3.27.jar b/WebContent/WEB-INF/lib/spring-instrument-5.3.27.jar new file mode 100644 index 0000000..0949247 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-instrument-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-jdbc-5.3.17.jar b/WebContent/WEB-INF/lib/spring-jdbc-5.3.17.jar new file mode 100644 index 0000000..8f2ea61 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-jdbc-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-jdbc-5.3.27.jar b/WebContent/WEB-INF/lib/spring-jdbc-5.3.27.jar new file mode 100644 index 0000000..6cf0517 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-jdbc-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-jms-5.3.17.jar b/WebContent/WEB-INF/lib/spring-jms-5.3.17.jar new file mode 100644 index 0000000..bfeae8e Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-jms-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-jms-5.3.27.jar b/WebContent/WEB-INF/lib/spring-jms-5.3.27.jar new file mode 100644 index 0000000..f618967 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-jms-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-orm-5.3.17.jar b/WebContent/WEB-INF/lib/spring-orm-5.3.17.jar new file mode 100644 index 0000000..5a0fdcc Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-orm-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-orm-5.3.27.jar b/WebContent/WEB-INF/lib/spring-orm-5.3.27.jar new file mode 100644 index 0000000..35b22de Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-orm-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-oxm-5.3.17.jar b/WebContent/WEB-INF/lib/spring-oxm-5.3.17.jar new file mode 100644 index 0000000..6551972 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-oxm-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-oxm-5.3.27.jar b/WebContent/WEB-INF/lib/spring-oxm-5.3.27.jar new file mode 100644 index 0000000..89d676c Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-oxm-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-test-5.3.17.jar b/WebContent/WEB-INF/lib/spring-test-5.3.17.jar new file mode 100644 index 0000000..38755a6 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-test-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-test-5.3.27.jar b/WebContent/WEB-INF/lib/spring-test-5.3.27.jar new file mode 100644 index 0000000..4e33bc0 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-test-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-tx-5.3.17.jar b/WebContent/WEB-INF/lib/spring-tx-5.3.17.jar new file mode 100644 index 0000000..fc3eddb Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-tx-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-tx-5.3.27.jar b/WebContent/WEB-INF/lib/spring-tx-5.3.27.jar new file mode 100644 index 0000000..b3e446c Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-tx-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-web-5.3.17.jar b/WebContent/WEB-INF/lib/spring-web-5.3.17.jar new file mode 100644 index 0000000..a6d941c Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-web-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-web-5.3.27.jar b/WebContent/WEB-INF/lib/spring-web-5.3.27.jar new file mode 100644 index 0000000..554d3e6 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-web-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/spring-webmvc-5.3.17.jar b/WebContent/WEB-INF/lib/spring-webmvc-5.3.17.jar new file mode 100644 index 0000000..3c0d778 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-webmvc-5.3.17.jar differ diff --git a/WebContent/WEB-INF/lib/spring-webmvc-5.3.27.jar b/WebContent/WEB-INF/lib/spring-webmvc-5.3.27.jar new file mode 100644 index 0000000..b65d353 Binary files /dev/null and b/WebContent/WEB-INF/lib/spring-webmvc-5.3.27.jar differ diff --git a/WebContent/WEB-INF/lib/sshj-0.40.0.jar b/WebContent/WEB-INF/lib/sshj-0.40.0.jar new file mode 100644 index 0000000..39cec93 Binary files /dev/null and b/WebContent/WEB-INF/lib/sshj-0.40.0.jar differ diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000..1c7a925 --- /dev/null +++ b/WebContent/WEB-INF/web.xml @@ -0,0 +1,88 @@ + + + BAPAppWeb + + FrontFilter + com.eactive.eai.agent.web.FrontFilter + + + FrontFilter + /* + + + + org.springframework.web.context.ContextLoaderListener + + + + contextConfigLocation + /WEB-INF/applicationContext.xml + + + + + WebAgent + com.eactive.eai.agent.web.WebAgent + + + + DBRefreshAgent + com.eactive.eai.agent.web.DBRefreshAgent + + + + FepSendFile + com.eactive.eai.agent.web.FepSendFile + + + + FepReqRecvFile + com.eactive.eai.agent.web.FepReqRecvFile + + + + CheckFileSysHealth + com.eactive.eai.agent.web.CheckFileSysHealth + + + + FepFileSend + com.eactive.eai.agent.web.FepFileSend + + + + FepFileReceive + com.eactive.eai.agent.web.FepFileReceive + + + + + WebAgent + /WebAgent + + + DBRefreshAgent + /DBRefreshAgent + + + FepSendFile + /FepSendFile + + + FepReqRecvFile + /FepReqRecvFile + + + CheckFileSysHealth + /CheckFileSysHealth + + + FepFileSend + /FepFileSend + + + FepFileReceive + /FepFileReceive + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/weblogic.xml b/WebContent/WEB-INF/weblogic.xml new file mode 100644 index 0000000..eaec68e --- /dev/null +++ b/WebContent/WEB-INF/weblogic.xml @@ -0,0 +1,5 @@ + + + 12.1.3 + BAPWeb + \ No newline at end of file diff --git a/WebContent/adapter.jsp b/WebContent/adapter.jsp new file mode 100644 index 0000000..ee0afe4 --- /dev/null +++ b/WebContent/adapter.jsp @@ -0,0 +1,161 @@ +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="java.util.List"%> +<%@ page import="java.util.Iterator"%> +<%@ page import="com.eactive.eai.adapter.AdapterGroupVO"%> +<%@ page import="com.eactive.eai.adapter.AdapterManager"%> +<%@ page import="com.eactive.eai.adapter.AdapterVO"%> + +<% + + AdapterManager manager = AdapterManager.getInstance(); + + List grpList = manager.getAllAdapterGroupNames(); + + String selectedName = request.getParameter("groupName"); + if (selectedName == null && grpList.size() > 1) + selectedName = grpList.get(0); + + AdapterGroupVO grpVO = null; + AdapterVO aVO = null; + + if (selectedName != null) { + grpVO = manager.getAdapterGroupVO(selectedName); + } + +%> + + + + + Adpater Informations + + + + +

+ Adpater Informations

+

+ +
+ + + + +
+ + + + + +
Adapter Group :    +
+

+ + <% + if (selectedName != null) { + %> + + + + + + + + + + + + + + + + + + + + + + + + + +
  ڵ :   
  ͻ뿩 :   
  BATCH۾ڵ :   
  BATCHڵ :   
  ͱ׷ :   
  AdapterGroupVO.toString() :  <%=grpVO.toString()%>

+ <% + } + %> + + + + <%----%> + + + + + + + + + + + + + + + + + + <% + if (selectedName != null) { + Iterator adtIt = grpVO.getAdapters(); + while(adtIt.hasNext()) { + AdapterVO adtVO = adtIt.next(); + %> + + + + + + + + + + + + + + + + + + + + <% + } + } + %> +
 ;׷s ; ̸ ͼ Ƽ ׷ BATCHýۿڵ BATCH۾ڵ BATCH۾и BATCHܱڵ BATCHܱ BATCHIP BATCHƮ BATCH޼ŸӾƿ BATCHóĢڵ BATCH̵ BATCHн BATCHŶũ BATCH䱸ۼŸ
                
+
+ + \ No newline at end of file diff --git a/WebContent/batchjobpriority.jsp b/WebContent/batchjobpriority.jsp new file mode 100644 index 0000000..6a35ab5 --- /dev/null +++ b/WebContent/batchjobpriority.jsp @@ -0,0 +1,155 @@ +<%@ page import="java.util.ArrayList"%> +<%@ page import="java.util.HashMap"%> +<%@ page import="com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityManager"%> +<%@ page import="com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityVO"%> +<%@ page language="java" contentType="text/html;charset=euc-kr"%> + +<% + + BatchJobPriorityManager jobpmanager = BatchJobPriorityManager.getInstance(); + + HashMap> jobmap = jobpmanager.getPriorityDatas(); + String[] keys = jobpmanager.getPriorityKeys(); + +%> + + + + + 켱 ۾ + + + + +

+ 켱 ۾

+

+ +
+ + + +
+ + <% + int count = -1; + boolean tableIndex = false; + String mapkey = ""; + if (keys !=null && keys.length > 0) { + + for (int keyindex =0; keyindex < keys.length; keyindex++){ + mapkey = keys[keyindex]; + ArrayList alist = jobmap.get(mapkey); + for (int j=0; j 0){ + delay = (int)((System.currentTimeMillis() - hvo.getFirstCallForDelayTime())/1000.0); + } + count++; + if(j == 0) { + tableIndex = true; + + %> + + + + + + + + + + + + + + + + + + + + + + + + + + +<% + } + else { +%> + + + + + + + + + + + +<% + } + } + if(tableIndex){ + %> +
<%= hvo.getProcessName() %>ֿ켱 ۾(Key)Batch۾ŷ
ڵ
UUIDϸDelayð()
<%= mapkey %>  +
+ +
<%= hvo.getBizCode() %> <%= hvo.getUUID() %> <%= hvo.getOsdName() %> <%= hvo.getFileName() %> <%=delay%> <%=hvo.getDataCountInfo()%>   
<%= hvo.getBizCode() %> <%= hvo.getUUID() %> <%= hvo.getOsdName() %> <%= hvo.getFileName() %> <%=delay%> <%=hvo.getDataCountInfo()%>   
+
+<%} + } + }else { + %> + 켱 ۾ ϴ. + <% + } + if(count == 0 && tableIndex==true){ + %> + 켱 ۾ ϴ. + <% + } + %> + + + \ No newline at end of file diff --git a/WebContent/codeMessage.jsp b/WebContent/codeMessage.jsp new file mode 100644 index 0000000..6b384b0 --- /dev/null +++ b/WebContent/codeMessage.jsp @@ -0,0 +1,65 @@ +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="com.eactive.eai.batch.code.CodeMessageManager"%> +<%@ page import="com.eactive.eai.batch.code.CodeMessageVO"%> + +<% + + CodeMessageManager manager = CodeMessageManager.getInstance(); + + String[] al = manager.getAllCodes(); + +%> + + + + + ڵ ޽ Informations + + + + +

+ ڵ ޽ Informations

+

+ +
+ + <% + if (al != null && al.length > 0) { + CodeMessageVO vo = null; + %> + + + + + + + + + <% + for (int j=0; j < al.length; j++) { + vo = manager.getMessageVO(al[j]); + %> + + + + + + + + + + + <% + } + %>
  code id    code txt    ġ    SMS߼    ɰ  
 <%=vo.getMsgKey()%> <%=vo.getMsgTxt()%> <%=vo.getMsgEtc()%> <%=vo.getSmsSendType()%> <%=vo.getItsmObstclGrdDstcd()%>

<% + } + %> +
+ + \ No newline at end of file diff --git a/WebContent/dump.jsp b/WebContent/dump.jsp new file mode 100644 index 0000000..bb98e93 --- /dev/null +++ b/WebContent/dump.jsp @@ -0,0 +1,87 @@ +<%@ page language="java" contentType="text/html; charset=EUC-KR"%> +<%@ page import="java.io.* +,java.util.* +"%> +<%! +static private String getStackTrace(Thread thread) { + StringBuffer sb = new StringBuffer(); + sb.append(" " + thread.getName() + " "); + sb.append("prio=" + thread.getPriority() + " "); + sb.append(thread.isDaemon() ? "daemon " : " "); + + StackTraceElement stack[] = thread.getStackTrace(); + + if (stack==null || stack.length<1) + return sb.toString(); + + if (stack[0].getMethodName().equals("wait")) + sb.append("wait \n"); + else if (stack[0].getMethodName().equals("sleep")) + sb.append("sleep \n"); + else + sb.append(stack[0].getMethodName() + " \n"); + + for (int i=0; i at "); + else + sb.append(" at "); + sb.append(className + "." + methodName); + sb.append("(" + filename + ":" + (isNativeMethod ? "native" : String.valueOf(line)) + ")"); + if (!className.startsWith("java") && !className.startsWith("org.") && !className.startsWith("sun.") && !className.startsWith("com.sun.")) + sb.append("-"); + sb.append("\n"); + } + + + return sb.toString(); +} + +static public String dump() { + Hashtable hash = new Hashtable(); + + StringBuffer sb = new StringBuffer(); + ThreadGroup it = Thread.currentThread().getThreadGroup(); + Thread[] threads = new Thread[it.activeCount()] ; + sb.append("active thread count : " + it.activeCount() + "\n"); + it.enumerate(threads); + + String[] threadNames = new String[threads.length]; + for (int i=0; i +<% + response.setHeader("Pragma", "No-cache"); + response.setHeader("Cache-Control", "no-cache"); + response.setHeader("Expires", "0"); +%> + + +
<%=dump()%>
+ + + diff --git a/WebContent/holiday.jsp b/WebContent/holiday.jsp new file mode 100644 index 0000000..bb2daaa --- /dev/null +++ b/WebContent/holiday.jsp @@ -0,0 +1,93 @@ +<%@ page import="java.io.*, java.util.*"%> +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="com.eactive.eai.batch.eventscheduler.holiday.HolidayManager"%> +<%@ page import="com.eactive.eai.batch.eventscheduler.holiday.HolidayVO"%> +<%@ page import="com.eactive.eai.batch.common.StringUtil"%> + +<% + + String day = StringUtil.nvlTrim(request.getParameter("day" ), ""); + HolidayManager manager = HolidayManager.getInstance(); + + ArrayList holiday = manager.getAllHoliday(); + + boolean isHoly = false; + boolean isAllHoly = false; + if (day != null && day.length() >0){ + isHoly = manager.isHoliday(day); + isAllHoly = manager.isAllHoliday(day); + } + +%> + + + + + Informations + + + + +

+ Informations

+

+ +
+ + + + +
+ + + + + + + + + + + + + + + + +
¥ : 
IS : 
IS ALL : 
+

+ + <% + if (holiday !=null && holiday.size() > 0) { + HolidayVO hvo = null; + for (int j=0; j + + + + + + + + + + + + + + + +
  :   
  :   
  :   

+ <% + } + } + %> + + + \ No newline at end of file diff --git a/WebContent/kikwanInfo.jsp b/WebContent/kikwanInfo.jsp new file mode 100644 index 0000000..d156c2a --- /dev/null +++ b/WebContent/kikwanInfo.jsp @@ -0,0 +1,64 @@ +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="java.util.HashMap"%> +<%@ page import="com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoManager"%> +<%@ page import="com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoVO"%> + +<% + + KikwanInfoManager manager = KikwanInfoManager.getInstance(); + + String[] al = manager.getAllKikwanCodes(); + +%> + + + + + FTManager + + + + +

+ FTManager

+

+ +
+ + <% + if (al != null && al.length > 0) { + KikwanInfoVO vo = null; + %> + + + + + + + + <% + for (int j=0; j < al.length; j++) { + vo = manager.getKikwanInfo(al[j]); + %> + + + + + + + + + + <% + } + %>
  ڵ       ý IP    ȣȭ IP  
 <%=vo.getKikwanCd()%> <%=vo.getKikwanName()%> <%=vo.getSysIp()%> <%=vo.getEncIp()%>

<% + } + %> +
+ + \ No newline at end of file diff --git a/WebContent/loglevel.jsp b/WebContent/loglevel.jsp new file mode 100644 index 0000000..222c91e --- /dev/null +++ b/WebContent/loglevel.jsp @@ -0,0 +1,83 @@ +<%@ page contentType="text/html;charset=EUC-KR"%> +<%@page import="ch.qos.logback.core.*"%> +<%@page import="ch.qos.logback.classic.*"%> +<%@page import="org.slf4j.*"%> +<%@page import="java.util.*"%> +<% + + String loggerName = request.getParameter("loggerName"); + String slevel = request.getParameter("level"); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + if (loggerName != null && !"".equals(loggerName) && slevel != null && !"".equals(slevel)){ + Level level = Level.ERROR; + if ("DEBUG".equals(slevel)){ + level = Level.DEBUG; + }else if ("INFO".equals(slevel)){ + level = Level.INFO; + }else if ("WARN".equals(slevel)){ + level = Level.WARN; + }else if ("ERROR".equals(slevel)){ + level = Level.ERROR; + }else if ("TRACE".equals(slevel)){ + level = Level.TRACE; + } + + lc.getLogger(loggerName).setLevel(level); +%> + <%=loggerName %> α level <%=slevel %> Ǿϴ. +<% + } + + List logs = lc.getLoggerList();; + +%> + +
+ + + +
+ +<% + ArrayList al = new ArrayList(); + for(ch.qos.logback.classic.Logger log : logs){ + if (log.getLevel() != null){ + al.add(log.getName()); + } + } + al.sort(null); + for(String name : al){ + ch.qos.logback.classic.Logger l = lc.getLogger(name); +%> + + + +<% + } +%> +
<%=l.getName() %> +
diff --git a/WebContent/outside.jsp b/WebContent/outside.jsp new file mode 100644 index 0000000..c2b21ec --- /dev/null +++ b/WebContent/outside.jsp @@ -0,0 +1,193 @@ +<%@ page import="java.util.List"%> +<%@ page import="java.util.ArrayList"%> +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="com.eactive.eai.batch.osd.OutsideVO"%> +<%@ page import="com.eactive.eai.batch.osd.OutsideManager"%> +<%@ page import="com.eactive.eai.batch.osd.OutsideLinkVO"%> + +<% + + OutsideManager manager = OutsideManager.getInstance(); + + List outside = new ArrayList(); + List outsideLink = new ArrayList(); + Object[] batchCodes = manager.getBatchCodeArray(); + + String selectedName = request.getParameter("groupName"); + if (selectedName == null && batchCodes.length > 1) + selectedName = (String)batchCodes[0]; + + OutsideVO outVO = null; + OutsideLinkVO linkVO = null; + + if (selectedName != null) { + outside = manager.getOutsideInfo(selectedName); + } + +%> + + + + + Outside Informations + + + + +

+ Adpater Informations

+

+ +
+ + + + +
+ + + + + +
ġ۾ڵ :   +
+

+ + <% + if (selectedName !=null && outside != null) { + for (int j=0; j + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  ġ۾ڵ :   
  ġ۾ :   
  ܱڵ :   
  ܱ :   
  ͱ׷ :   
  ۽óĢ :   
  óĢ :   
  ܼ۽ :   
  ܼ :   
  :   
  :   
  ŷε :   
  ŷε :   
  Ŷ :   
  OutsideVO.toString() :  <%=outVO.toString()%>

+ <% + + outsideLink = manager.getOutsideLinkInfo(outVO.getOsdCode()); + if ( outsideLink != null ){ + for (int n=0; n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <% + } + } + } + } + } + %> +
 ýۿᱸ ۼűڵ IP  Port ID PW ŸӾƿ ȸڵ ͱ׷̸ ͸
          
+ + + \ No newline at end of file diff --git a/WebContent/phaseInfo.jsp b/WebContent/phaseInfo.jsp new file mode 100644 index 0000000..e0e8e0e --- /dev/null +++ b/WebContent/phaseInfo.jsp @@ -0,0 +1,112 @@ +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="java.util.HashMap"%> +<%@ page import="java.util.Arrays"%> +<%@ page import="java.util.ArrayList"%> +<%@ page import="java.util.Iterator"%> + +<%@ page import="com.eactive.eai.batch.rule.phaseinfo.PhaseInfoManager"%> +<%@ page import="com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO"%> + + +<% + + PhaseInfoManager manager = PhaseInfoManager.getInstance(); + + + HashMap> all = manager.getAllData(); + + Iterator it = all.keySet().iterator(); + String[] phaseinfoList = new String[all.size()]; + for(int i=0;it.hasNext();i++) { + phaseinfoList[i] = (String)it.next(); + } + Arrays.sort(phaseinfoList); + + String selectedName = request.getParameter("phaseinfoName"); + if (selectedName == null && phaseinfoList.length > 1) + selectedName = (String)phaseinfoList[0]; + + ArrayList al = all.get(selectedName); + + +%> + + + + + Phase Informations + + + + +

+ Phase Informations

+

+ +
+ + + + +
+ + + + + +
帧Ģڵ :    +
+

+ + <% + if (selectedName != null) { + %> + + <% + } + %> + + + + + + <% + if (al != null) { + for ( int inx=0; inx < al.size(); inx++){ + PhaseInfoVO vo = al.get(inx); + %> + + + + + + <% + } + } + %> +
 List
<%=vo.toString()%>
+
+ + \ No newline at end of file diff --git a/WebContent/properties.jsp b/WebContent/properties.jsp new file mode 100644 index 0000000..ea4c9c0 --- /dev/null +++ b/WebContent/properties.jsp @@ -0,0 +1,113 @@ +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="com.eactive.eai.common.property.PropManager"%> +<%@ page import="com.eactive.eai.common.property.PropGroupVO"%> + +<% + + PropManager manager = PropManager.getInstance(); + + String[] grpList = manager.getAllPropGroupNames(); + + String selectedName = request.getParameter("groupName"); + if (selectedName == null && grpList.length > 1) + selectedName = (String)grpList[0]; + + PropGroupVO grpVO = null; + + if (selectedName != null) { + grpVO = manager.getPropGroupVO(selectedName); + } + +%> + + + + + Properties Informations + + + + +

+ Properties Informations

+

+ +
+ + + + +
+ + + + + +
Adapter Group :    +
+

+ + <% + if (selectedName != null) { + %> + + + + + + + + + +
  Ƽ ׷ :  <%=grpVO.getName()%>
  Ƽ ׷켳 :  <%=grpVO.getDescription()%>

+ <% + } + %> + + + + + + + <% + if (selectedName != null) { + String[] keys = grpVO.keys(); + for ( int inx=0; inx < keys.length; inx++){ + String value = grpVO.getProperty(keys[inx]); + %> + + + + + + + <% + } + } + %> +
 Key Value
<%=keys[inx]%><%=value%>
+
+ + \ No newline at end of file diff --git a/WebContent/sms.jsp b/WebContent/sms.jsp new file mode 100644 index 0000000..7f58176 --- /dev/null +++ b/WebContent/sms.jsp @@ -0,0 +1,56 @@ +<%@ page contentType="text/html;charset=euc-kr" pageEncoding="euc-kr"%> +<%@ page import="com.eactive.eai.batch.common.SMSManager"%> +<%@ page import="com.eactive.eai.batch.common.StringUtil"%> +<% request.setCharacterEncoding("euc-kr"); %> +<% + + String telno = StringUtil.nvlTrim(request.getParameter("telno" ), ""); + String text = StringUtil.nvlTrim(request.getParameter("text" ), ""); + SMSManager manager = SMSManager.getInstance(); + + + boolean result = false; + + if (telno != null && telno.length() >0 && text != null && text.length() > 0){ + result = manager.sendSMS( telno, text ) ; + } + +%> + + + + + ޽ ׽Ʈ + + + + +

+ ޽ ׽Ʈ

+

+ +
+ + + + +
+ + + + + + + + +
ȭȣ : ޽ : 
+
+
+
+ + \ No newline at end of file diff --git a/WebContent/sysInfo.jsp b/WebContent/sysInfo.jsp new file mode 100644 index 0000000..674c23c --- /dev/null +++ b/WebContent/sysInfo.jsp @@ -0,0 +1,73 @@ +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="java.util.HashMap"%> +<%@ page import="com.eactive.eai.batch.rule.sysInfo.SysInfoManager"%> +<%@ page import="com.eactive.eai.batch.rule.sysInfo.SysInfoVO"%> + +<% + + SysInfoManager manager = SysInfoManager.getInstance(); + + String[] al = manager.getAllSysCodes(); + +%> + + + + + FTManager + + + + +

+ FTManager

+

+ +
+ + <% + if (al != null && al.length > 0) { + SysInfoVO vo = null; + %> + + + + + + + + + + + + + <% + for (int j=0; j < al.length; j++) { + vo = manager.getSysInfo(al[j]); + %> + + + + + + + + + + + + + + <% + } + %>
  ýڵ    ý۸    ý IP    Ʈ    ID    йȣ    ۽ŵ丮    ŵ丮    SFTP  
 <%=vo.getSysCd()%> <%=vo.getSysName()%> <%=vo.getSysIp()%> <%=vo.getSysPort ()%> <%=vo.getUserId ()%> <%=vo.getUserPassword()%> <%=vo.getSendDir ()%> <%=vo.getRecvDir ()%> <%=vo.getSftpYn ()%>

<% + } + %> +
+ + \ No newline at end of file diff --git a/WebContent/telegrams.jsp b/WebContent/telegrams.jsp new file mode 100644 index 0000000..812fcfc --- /dev/null +++ b/WebContent/telegrams.jsp @@ -0,0 +1,108 @@ +<%@ page language="java" contentType="text/html;charset=euc-kr"%> +<%@ page import="java.util.HashMap"%> +<%@ page import="com.eactive.eai.batch.telegram.TelegramManager"%> +<%@ page import="com.eactive.eai.batch.telegram.TelegramVO"%> + +<% + + TelegramManager manager = TelegramManager.getInstance(); + + HashMapmap = manager.getAllTelegrams(); + String[] keyNames = (String[])map.keySet().toArray(); + + String selectedName = request.getParameter("groupName"); + if (selectedName == null && map.size() > 1) + selectedName = (String)keyNames[0]; + + TelegramVO vo = null; + + if (selectedName != null) { + vo = map.get(selectedName); + } + +%> + + + + Properties Informations + + + + +

+ Properties Informations

+

+ +
+ + + + +
+ + + + + +
Adapter Group :    +
+

+ + <% + if (selectedName != null) { + } + %> + + + + + + + <% + if (selectedName != null) { +// String[] keys = grpVO.keys(); +// for ( int inx=0; inx < keys.length; inx++){ +// String value = grpVO.getProperty(keys[inx]); + %> + + + + <% + } +// } + %> +
 Key Value
+
+ + \ No newline at end of file diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..47a3807 --- /dev/null +++ b/build.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + finished to make distribute files ${EndTime} + + diff --git a/src/com/eactive/eai/adapter/AdapterDAO.java b/src/com/eactive/eai/adapter/AdapterDAO.java new file mode 100644 index 0000000..4a73318 --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterDAO.java @@ -0,0 +1,223 @@ +package com.eactive.eai.adapter; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Vector; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.NullControl; + +/** +* 1. 기능 : 업무데이터로 부터 아래와 같은 특정 필드를 추출하기 위한 어댑터 정보 테이블에 +* 대한 Data Access Object 이다. +* 2. 처리 개요 : 어댑터 정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다. +* +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : AdapterQuery.java +* @since : +*/ +public class AdapterDAO extends BaseDAO implements AdapterQuery +{ + + /** + * Default Logger + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + /** + * 1. 기능 : 어댑터 그룹 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서 + * AdapterGroupVO 객체 리스트로 생성 반환하는 메서드. + * 2. 처리 개요 : 어댑터 그룹 정보 전체를 SELECT해서 한 레코드를 AdapterGroupVO로 생성 ArrayList에 + * 저장하여 반환한다. + * 3. 주의사항 + * + * @return ArrayList 어댑터 그룹 정보 전체데이터로 AdapterGroupVO Collection + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 그룹 정보를 가져오다 발생되는 모든 에러 + **/ + public ArrayList getAllAdapterGroups() throws DAOException { + ArrayList al = new ArrayList(); + ResultSet rs = null; + AdapterGroupVO vo = null; + try { + this.connect(SELECT_ALL_GROUPS); + //logger.debug("SELECT_ALL_GROUPS: "+ SELECT_ALL_GROUPS); + + rs = this.executeQuery(); + while(rs.next()) { + vo = new AdapterGroupVO(); + vo.setName (rs.getString(1)); + vo.setType (rs.getString(2)); + vo.setUsedFlag ("1".equals(rs.getString(3))); + vo.setDescription (NullControl.trimSpace(rs.getString(4))); + vo.setBatchProcessCode (rs.getString(5)); //TSEAIBJ06테이블 PK 값 + vo.setBatchInstitutionCode(rs.getString(6)); //TSEAIBJ06테이블 PK 값 + al.add(vo); + } + + return al; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD001")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : 어댑터 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서 + * AdapterGroupVO 객체 리스트로 생성 반환하는 메서드. + * 2. 처리 개요 : 어댑터 정보 전체를 SELECT해서 한 레코드를 AdapterGroupVO로 생성 ArrayList에 + * 저장하여 반환한다. + * 3. 주의사항 + * + * @param adapterGroupName 어댑터 그룹 이름 + * @return ArrayList 어댑터 정보 전체데이터로 AdapterGroupVO Collection + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 정보를 가져오다 발생되는 모든 에러 + **/ + public ArrayList getAllAdapters(String adapterGroupName) throws DAOException { + ArrayList al = new ArrayList(); + ResultSet rs = null; + AdapterVO vo = null; + try { + this.connect(SELECT_ADAPTERS_BY_GROUP); + //logger.debug("[AdapterDAO:getAllAdapters]SELECT_ADAPTERS_BY_GROUP: "+ SELECT_ADAPTERS_BY_GROUP); + + this.preparedStatement.setString(1, adapterGroupName); + logger.debug("바인드[1]: "+ adapterGroupName); + + + + rs = this.executeQuery(); + while(rs.next()) { + vo = new AdapterVO(); + vo.setAdapterGroupName (rs.getString("AdptrBzwkGroupName")); + vo.setName (rs.getString("AdptrBzwkName")); + vo.setListenerClass (NullControl.trimSpace(rs.getString("LstnerClsName"))); + vo.setPropGroupName (NullControl.trimSpace(rs.getString("PrptyGroupName"))); + vo.setDescription (NullControl.trimSpace(rs.getString("AdptrDesc"))); + vo.setBatchSystemConnCode (rs.getString("SysLnkgDstcd")); + vo.setBatchProcessCode (rs.getString("BjobBzwkDstcd")); + vo.setBatchInstitutionCode(rs.getString("OsidInstiDstcd")); + vo.setBatchServerIP (rs.getString("LnkgIPInfoName")); + vo.setBatchServerPortNo (rs.getString("LnkgPortInfoName")); + vo.setBatchInterMsgTimeout(rs.getInt ("ToutVal")); + vo.setBatchRcvFlowRuleCode(rs.getString("RecvPrcssRuleCd")); + vo.setBatchInstitutionName(rs.getString("OsidInstiName")); + vo.setLnkID(rs.getString ("LnkgID")); + vo.setLnkPwd(rs.getString ("LnkgPwd")); + vo.setPacketSize (rs.getInt("TelgmPcketSize")); + vo.setRqstRspnsDstcd (rs.getString("RqstRspnsDstcd")); + vo.setBatchProcessName (rs.getString("BjobBzwkName")); + al.add(vo); + } + + return al; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD002")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : 어댑터 그룹 및 그룹에 속한 어댑터 정보 리스트에 대한 상세 조회를 하는 + * 메서드. by 전홍성 + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @param adapterGroupName 어댑터 그룹 이름 + * @param serverName 서버 이름 + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 그룹 정보를 가져오다 발생되는 모든 에러 + **/ + public AdapterGroupVO getAdapterGroup(String adapterGroupName) throws DAOException { + + ResultSet rs = null; + try { + this.connect(GET_ADAPTER_GROUP); + this.preparedStatement.setString(1, adapterGroupName); + rs = this.executeQuery(); + + if(!rs.next()) { + String code = "BECEAIMAD008"; + String[] msgArgs = new String[1]; + msgArgs[0] = adapterGroupName; + String errText = ExceptionUtil.make(code, msgArgs); + if (logger.isError()) logger.error(errText); + throw new DAOException(errText); + } + + AdapterGroupVO gvo = new AdapterGroupVO(); + gvo.setName(adapterGroupName); + gvo.setType(rs.getString("AdptrCd")); + try { + gvo.setUsedFlag(rs.getString("AdptrUseYn").equals("1")); + } catch(NullPointerException e) {} + gvo.setDescription(NullControl.trimSpace(rs.getString("AdptrBzwkGroupDesc"))); + gvo.setBatchProcessCode(rs.getString("BjobBzwkDstcd")); + gvo.setBatchInstitutionCode(rs.getString("OsidInstiDstcd")); + + rs.close(); + + this.prepareStatement(GET_ADAPTERS); + this.preparedStatement.setString(1,adapterGroupName); + rs = this.executeQuery(); + + while(rs.next()) { + AdapterVO vo = new AdapterVO(); + vo.setAdapterGroupName(adapterGroupName); + vo.setName(rs.getString("AdptrBzwkName")); + vo.setListenerClass(NullControl.trimSpace(rs.getString("LstnerClsName"))); + vo.setPropGroupName(NullControl.trimSpace(rs.getString("PrptyGroupName"))); + vo.setDescription(NullControl.trimSpace(rs.getString("AdptrDesc"))); + vo.setPropGroupDesc(NullControl.trimSpace(rs.getString("PrptyGroupDesc"))); + gvo.addAdapterVO(vo); + } + + + return gvo; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD009")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : 어댑터 그룹 정보 테이블 전체 내용을 SELECT해서 + * AdapterGroupVO 객체 Vector로 생성 반환하는 메서드. + * 2. 처리 개요 : 어댑터 그룹 정보 전체를 SELECT해서 한 레코드를 AdapterGroupVO로 생성 Vector에 + * 저장하여 반환한다. + * 3. 주의사항 + * + * @return Vector 어댑터 그룹 정보 전체데이터로 AdapterGroupVO Collection + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 그룹 정보를 가져오다 발생되는 모든 에러 + **/ + public Vector getAdptGroupNM() throws DAOException { + Vector all = new Vector(); + ResultSet rs = null; + try { + this.connect(SELECT_ADPT_GROUP_NAMES); + rs = executeQuery(); + AdapterGroupVO vo = null; + + while(rs.next()) { + vo = new AdapterGroupVO(); + vo.setName(rs.getString(1)); + all.addElement(vo); + } + + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD014")); + } finally { + this.disconnect(); + } + + return all; + } +} diff --git a/src/com/eactive/eai/adapter/AdapterGroupVO.java b/src/com/eactive/eai/adapter/AdapterGroupVO.java new file mode 100644 index 0000000..d27a2ba --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterGroupVO.java @@ -0,0 +1,465 @@ +package com.eactive.eai.adapter; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Vector; + +import org.slf4j.LoggerFactory; + +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +/** +* 1. 기능 : 어댑터 그룹 정보를 표현하는 Java Value Object 클래스. +* 2. 처리 개요 : 어댑터 그룹 정보를 정의한다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class AdapterGroupVO implements Serializable, Lifecycle +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default Logger + */ + static Logger logger = (Logger) Logger.getLogger(Logger.LOGGER_ADAPTER); + + private String name; //어뎁터업무그룹명[TSEAIAD01.AdptrBzwkGroupName] + private String type; //어댑터코드[TSEAIAD01.AdptrCd] + private boolean usedFlag; //어댑터사용여부[TSEAIAD01.AdptrUseYn] + private String description; //어댑터업무그룹설명[TSEAIAD01.AdptrBzwkGroupDesc] + private String batchProcessCode; //BATCH작업업무구분코드[TSEAIBJ06.BjobBzwkDstcd] + private String batchInstitutionCode; //BATCH작업업무구분코드[TSEAIBJ06.OsidInstiDstCd] + + /** + * 어댑터 collection + */ + private HashMap adapters; + + private Vector actives; +// private Vector disables; + + /** + * 어댑터 이름 리스트 + */ + private ArrayList adapterNames; + + /** + * index + */ + private int idx; + + /** + * 기동 여부 + */ + private boolean started; + /** + * LifecycleSupport instance + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * current transaction + */ + private int currentTx; + + /** + * 1. 기능 : Defualt Constructor + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + **/ + public AdapterGroupVO() { + this(""); + } + + /** + * 1. 기능 : 어댑터 그룹명을 초기화하는 생성자 함수 + * 2. 처리 개요 : 어댑터 그룹명을 초기화한다. + * 3. 주의사항 + * + * @param name 어댑터 그룹명 + **/ + public AdapterGroupVO(String name) { + this.name = name; + this.adapters = new HashMap(); + this.actives = new Vector(); +// this.disables = new Vector(); + this.adapterNames = new ArrayList(); + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public void setType(String type) { + this.type = type; + } + + public String getType() { + return this.type; + } + + public void setUsedFlag(boolean usedFlag) { + this.usedFlag = usedFlag; + } + + public boolean isUsedFlag() { + return this.usedFlag; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDescription() { + return this.description; + } + + + /** + * 1. 기능 : 어댑터 정보를 추가하는 메서드 + * 2. 처리 개요 : 어댑터 정보를 추가 한다. + * 3. 주의사항 + * + * @param avo AdapterVO 객체 + * + **/ + public void addAdapterVO(AdapterVO avo) { + this.adapters.put(avo.getName(),avo); + this.adapterNames.add(avo.getName()); + } + + /** + * 1. 기능 : 어댑터 정보를 반환하는 메서드 + * 2. 처리 개요 : 어댑터 정보를 반환 한다. + * 3. 주의사항 + * + * @return AdapterVO AdapterVO 객체 + * + **/ + public AdapterVO getAdapterVO(String adapterName) { + return (AdapterVO)adapters.get(adapterName); + } + + /** + * 1. 기능 : currentTx를 증가시키는 메서드 + * 2. 처리 개요 : currentTx를 증가시킨다. + * 3. 주의사항 + * + **/ + public synchronized void increase() { + ++currentTx; + } + + /** + * 1. 기능 : currentTx를 감소시키는 메서드 + * 2. 처리 개요 : currentTx를 감소 시킨다. + * 3. 주의사항 + * + **/ + public synchronized void decrease() { + --currentTx; + } + + /** + * 1. 기능 : currentTx getter 메서드 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @return int currentTx + **/ + public int currentTx() { + return this.currentTx; + } + + /** + * 1. 기능 : Lifecycle의 start 메서드로 AdapterGroupVO 초기화하는 메서드 + * 2. 처리 개요 : AdapterVO를 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, AdapterVO를 통해 Rule 정보를 가져오다 DAOExcepiton이 발생될 경우 + * + **/ + public void start() throws LifecycleException { + + if (started) + throw new LifecycleException("BECEAIMAD030"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + if(!this.usedFlag){ + String code = "BECEAIMAD040"; + String[] msgArgs = new String[1]; + msgArgs[0] = name; + String errText = ExceptionUtil.make(code, msgArgs); + if (logger.isError()) logger.error(errText); + throw new LifecycleException(errText); + } + + AdapterVO avo = null; + Iterator it = adapters.values().iterator(); + while(it.hasNext()) { + avo = it.next(); + if(avo instanceof Lifecycle) { + try { + LifecycleListener []listeners = this.lifecycle.findLifecycleListeners(); + if(listeners != null) { + for(int j=0;j it = adapters.values().iterator(); + while(it.hasNext()) { + avo = it.next(); + if(!avo.isStarted()) continue; + if(avo instanceof Lifecycle) { + try { + avo.stop(); + } catch(Exception e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD033")); + } + } + } + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + + /** + * 1. 기능 : 해당 어댑터를 active 그룹으로 변경한다. + * 2. 처리 개요 : 해당 어댑터를 disble 그룹에서 삭제하고, active 그룹에 추가한다. + * 3. 주의사항 + * + * @param vo 상태변경할 어댑터 + */ + public void active(AdapterVO vo) { +// this.disables.remove(vo); + if (!actives.contains(vo) && vo.isStatus()) { + this.actives.add(vo); + } + } + + /** + * 1. 기능 : 해당 어댑터를 disble 그룹으로 변경한다. + * 2. 처리 개요 : 해당 어댑터를 active 그룹에서 삭제하고, disble 그룹에 추가한다. + * 3. 주의사항 + * + * @param vo 상태변경할 어댑터 + */ + public void disable(AdapterVO vo) { + this.actives.remove(vo); +// this.disables.add(vo); + } + + /** + * 1. 기능 : 어댑터 그룹에 속한 가용한 어댑터가 있는지 여부를 반환하는 메서드 + * 2. 처리 개요 : Active 그룹에 속한 어댑터가 있으면 true, 그렇지 않으면 false를 반환한다. + * 3. 주의사항 + * + * @return 어댑터 그룹에 속한 가용한 어댑터가 있는지 여부 + */ + public boolean isAlive() { + if(this.actives.size()>0) return true; + else return false; + } + + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : 어댑터 정보 Iteration 객체를 반환 + * 2. 처리 개요 : 어댑터 정보 Iteration 객체를 반환 한다. + * 3. 주의사항 + * + * @return Iterator 어댑터 정보 Iteration 객체 + **/ + public Iterator getAdapters() { + return this.adapters.values().iterator(); + } + + public HashMap getAllAdapters() { + return this.adapters; + } + + /** + * 1. 기능 : 어댑터명 array를 반환 + * 2. 처리 개요 : 어댑터명 array를 반환한다. + * 3. 주의사항 + * + * @return String[] 어댑터명 array + **/ + public String[] getAdapterNames() { + String[] names = new String[this.adapterNames.size()]; + for(int i=0;i=this.actives.size()) idx=0; + AdapterVO vo = this.actives.get(idx++); + return vo; + } catch(Exception e) { + if(this.actives.size()==0) return null; + idx = 0; + return this.actives.get(idx++); + } + } + + /** + * 1. 기능 : 어댑터 정보를 삭제하는 메서드 + * 2. 처리 개요 : 어댑터 정보를 삭제 한다. + * 3. 주의사항 + * + * @param name 어댑터그룹명 + **/ + public void removeAdapterVO(String name){ + adapters.remove(name); + } + + /** + * 1. 기능 : 어댑터 정보를 String 형태로 반환하는 메서드 + * 2. 처리 개요 : String 형태로 어댑터 정보를 반환한다. + * 3. 주의사항 + * + * @return String 어댑터 정보 + **/ + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("\nAdapterGroupVO [ name=").append(name); + sb.append(", type=").append(type); + sb.append(", usedFlag=").append(usedFlag); + sb.append(", description=").append(description); + sb.append(", batchProcessCode=").append(batchProcessCode); + sb.append(", batchInstitutionCode=").append(batchInstitutionCode); + sb.append(", AdapterList=").append(adapters); + sb.append(" ]"); + + return sb.toString(); + } + + public void setBatchProcessCode(String batchProcessCode) { + this.batchProcessCode = batchProcessCode; + } + + public String getBatchProcessCode() { + return this.batchProcessCode; + } + + public void setBatchInstitutionCode(String batchInstitutionCode) { + this.batchInstitutionCode = batchInstitutionCode; + } + + public String getBatchInstitutionCode() { + return this.batchInstitutionCode; + } + +} diff --git a/src/com/eactive/eai/adapter/AdapterManager.java b/src/com/eactive/eai/adapter/AdapterManager.java new file mode 100644 index 0000000..d76f36d --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterManager.java @@ -0,0 +1,352 @@ +package com.eactive.eai.adapter; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +/** +* 1. 기능 : 어댑터 정보를 DB로 부터 로딩해 메모리에 관리하는 Manager 클래스 +* 2. 처리 개요 : 어댑터 정보에 저장된 정보를 메모리에 로딩 관리한다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : Lifecycle +* @since : +*/ +public class AdapterManager implements Lifecycle +{ + /** + * Default Logger + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + /** + * AdapterManager Single Instance + */ + private static AdapterManager instance = new AdapterManager(); + /** + * 기동 여부 + */ + private boolean started; + /** + * 어댑터 정보를 저장하는 collection + */ + private HashMap adapterGroups = new HashMap(); + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : + * 3. 주의사항 + * + **/ + private AdapterManager() { + } + + /** + * 1. 기능 : AdapterManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : AdapterManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return AdapterManager Singleton object + **/ + public static AdapterManager getInstance() { + return instance; + } + + /** + * 1. 기능 : Lifecycle의 start 메서드로 AdapterManager를 초기화하는 메서드 + * 2. 처리 개요 : AdapterDAO를 이용해 추출 Rule 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, AdapterDAO를 통해 Rule 정보를 가져오다 DAOExcepiton이 발생될 경우 + * + **/ + public void start() throws LifecycleException { + if (started) + throw new LifecycleException("BECEAIMAD015"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + this.adapterGroups.clear(); + + ArrayList groups = null; + AdapterDAO dao = null; + try { + dao = (AdapterDAO)DAOFactory.newInstance().create(AdapterDAO.class); + groups = dao.getAllAdapterGroups(); + + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD016")); + } + + AdapterGroupVO gvo = null; + //AdapterVO avo = null; + for(int i=0;i all = null; + try { + all = dao.getAllAdapters(gvo.getName()); + for(int j=0;j> "+gvo); + continue; + } + gvo.start(); + } catch(Exception e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD019")); + } + } + } + started = true; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 AdapterManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱한 어댑터 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMAD020"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + for(Iterator it = this.adapterGroups.values().iterator();it.hasNext();) { + AdapterGroupVO vo = it.next(); + try { + if(!vo.isStarted()) continue; + if(vo instanceof Lifecycle) { + vo.stop(); + } + } catch(LifecycleException e) { + String msgArgs[] = new String[1]; + msgArgs[0] = vo.toString(); + String errText = ExceptionUtil.make("BECEAIMAD021", msgArgs); + if (logger.isError()) logger.error(errText); + throw new LifecycleException(ExceptionUtil.getErrorCode(e, errText)); + } + } + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : AdapterManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : AdapterManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : 어댑터 정보를 찾아 반환하는 메서드 + * 2. 처리 개요 : 어댑터 정보를 찾아 반환한다. + * 3. 주의사항 + * + * @param adapterGroupName 어댑터그룹명 + * @param adapterName 어댑터명 + * @return 어댑터 정보 VO 객체 + **/ + public AdapterVO getAdapterVO(String adapterGroupName, String adapterName) { + AdapterGroupVO gvo = (AdapterGroupVO)adapterGroups.get(adapterGroupName); + if(gvo==null) return null; + + return (AdapterVO)gvo.getAdapterVO(adapterName); + } + + /** + * 1. 기능 : 어댑터 그룹 정보를 찾아 반환하는 메서드 + * 2. 처리 개요 : 어댑터 그룹 정보를 찾아 반환한다. + * 3. 주의사항 + * + * @param adapterGroupName 어댑터그룹명 + * @return 어댑터 그룹 정보 VO 객체 + **/ + public AdapterGroupVO getAdapterGroupVO(String adapterGroupName) { + return (AdapterGroupVO)adapterGroups.get(adapterGroupName); + } + + public AdapterGroupVO getAdapterGroupInDB(String adapterGroupName) { + try { + AdapterDAO dao = (AdapterDAO)DAOFactory.newInstance().create(AdapterDAO.class); + AdapterGroupVO vo = dao.getAdapterGroup(adapterGroupName); + ArrayList all = null; + + all = dao.getAllAdapters(adapterGroupName); + for(int j=0;j getAllAdapterGroupVO() { + return adapterGroups; + } + + /** + * 1. 기능 : 모든 어댑터 그룹명을 찾아 반환하는 메서드 + * 2. 처리 개요 : 모든 어댑터 그룹명을 찾아 List 객체로 반환한다. + * 3. 주의사항 + * + * @return 어댑터 그룹명 리스트 + **/ + public List getAllAdapterGroupNames() { + ArrayList al = new ArrayList(); + Iterator it = this.adapterGroups.keySet().iterator(); + while(it.hasNext()) { + al.add(it.next()); + } + Collections.sort(al); + return al; + } + + /** + * 1. 기능 : 어댑터 그룹정보를 갱신하는 메서드 + * 2. 처리 개요 : 어댑터 그룹정보를 갱신한다. + * 3. 주의사항 + * + * @param vo 어댑터 그룹 VO 객체 + **/ + //db update code 필요!! + public void updateAdapterGroupVO(AdapterGroupVO vo) { + if(vo!=null) + adapterGroups.put(vo.getName(),vo); + //db update code 넣을것.. + } + + /** + * 1. 기능 : 어댑터 그룹정보를 삭제하는 메서드 + * 2. 처리 개요 : 어댑터 그룹정보를 삭제한다. + * 3. 주의사항 + * + * @param vo 어댑터 그룹명 + **/ + public void removeAdapterGroupVO(String name){ + adapterGroups.remove(name); + } + + /** + * 1. 기능 : debug String을 리턴하는 메서드 + * 2. 처리 개요 : + * 3. 주의사항 + * + **/ + public void print() { + if (logger.isDebugEnabled()) logger.debug("AdapterManager] All Adapter List>> "+this.adapterGroups); + } +} diff --git a/src/com/eactive/eai/adapter/AdapterPropDAO.java b/src/com/eactive/eai/adapter/AdapterPropDAO.java new file mode 100644 index 0000000..4fad46d --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterPropDAO.java @@ -0,0 +1,169 @@ +package com.eactive.eai.adapter; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.NullControl; + +import java.sql.ResultSet; +import java.util.HashMap; + +/** + * 1. 기능 : 어댑터 유형 별 프라퍼키 정보를 추출하기 위한 Data Access Object + * 2. 처리 개요 : 어댑터유형, 어댑터프라퍼티정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다. + * * - + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public class AdapterPropDAO extends BaseDAO implements AdapterPropQuery +{ + /** + * EAI FRAMEWORK DEFAULT FILE LOGGER + */ + //private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_ADAPTER); + + /** + * 1. 기능 : 어댑터 유형 별 모든 프라퍼티 정보 조회하여 AdapterTypeVO Collection으로 반환 + * 2. 처리 개요 : 어댑터 유형 별 모든 프라퍼티 정보를 SELECT해서 AdapterTypeVO로 생성 HashMap에 + * 저장하여 반환한다. + * 3. 주의사항 + * + * @return Returns AdapterTypeVO Collection + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 유형 별 모든 프라퍼티 정보를 가져오다 발생되는 모든 에러 + */ + public HashMap getAllAdapterPropInfo() throws DAOException { + + HashMap adptPropInfo = new HashMap(); + ResultSet rs = null; + + try { + + this.connect(GET_ALL_ADPT_PROP_INFO); + rs = executeQuery(); + + String current = null, previous = null; + AdapterTypeVO adptTp = null; + + while(rs.next()) { + current = rs.getString(1); + + if(!current.equals(previous)) { + adptTp = new AdapterTypeVO(current, rs.getString(2)); + adptPropInfo.put(current, adptTp); + previous = current; + } + + adptTp.addAdapterPropInfo(current, rs.getString(3), rs.getString(4), NullControl.trimSpace(rs.getString(5))); + } + + return adptPropInfo; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD041")); + } finally { + this.disconnect(); + } + + } + + /** + * 1. 기능 : 특정 어댑터 유형의 프라퍼티 정보 조회하여 AdapterTypeVO로 반환 + * 2. 처리 개요 : 특정 어댑터 유형의 프라퍼티 정보를 SELECT해서 AdapterTypeVO로 생성, 반환한다. + * 3. 주의사항 + * + * @return Returns AdapterTypeVO + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 프라퍼티 정보를 가져오다 발생되는 모든 에러 + */ + public AdapterTypeVO getAdapterPropInfo(String adptrCd) throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(GET_ADPT_PROP_INFO); + this.preparedStatement.setString(1, adptrCd); + rs = executeQuery(); + + String current = null, previous = null; + AdapterTypeVO adptTp = null; + + while(rs.next()) { + current = rs.getString(1); + + if(!current.equals(previous)) { + adptTp = new AdapterTypeVO(current, rs.getString(2)); + previous = current; + } + + adptTp.addAdapterPropInfo(current, rs.getString(3), rs.getString(4), NullControl.trimSpace(rs.getString(5))); + } + + return adptTp; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD042")); + } finally { + this.disconnect(); + } + + } + + /** + * 1. 기능 : 어댑터유형 정보를 등록하는 메서드 + * 2. 처리 개요 : 어댑터유형 정보를 DB 테이블에 INSERT한다. + * 3. 주의사항 + * + * @param adptrCd 어댑터코드 + * @param adptrName 어댑터명 + * @exception DAOException DB INSERT 시 발생하는 SQLException을 포함한 추출정보 저장시 발생되는 모든 에러 + */ + public void addAdapterType(String adptrCd, String adptrName) throws DAOException { + + try { + this.connect(ADD_ADPT_TP); + + this.preparedStatement.setString(1,adptrCd); + this.preparedStatement.setString(2,adptrName); + + executeUpdate(); + + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD043")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : 어댑터프라퍼티정보를 등록하는 메서드 + * 2. 처리 개요 : 어댑터프라퍼티정보를 DB 테이블에 INSERT한다. + * 3. 주의사항 + * + * @param adptrCd 어댑터코드 + * @param adptrIODstcd 어댑터입출력구분코드 + * @param adptrPrptyName 어댑터프라퍼티명 + * @param adptrPrptyDesc 어댑터프라퍼티설명 + * @exception DAOException DB INSERT 시 발생하는 SQLException을 포함한 추출정보 저장시 발생되는 모든 에러 + */ + public void addAdapterPropInfo(String adptrCd, String adptrIODstcd, String adptrPrptyName, String adptrPrptyDesc) + throws DAOException { + + try { + this.connect(ADD_ADPT_PROP_INFO); + + this.preparedStatement.setString(1,adptrCd); + this.preparedStatement.setString(2,adptrIODstcd); + this.preparedStatement.setString(3,adptrPrptyName); + this.preparedStatement.setString(4,NullControl.addSpace(adptrPrptyDesc)); + + executeUpdate(); + + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD044")); + } finally { + this.disconnect(); + } + } +} diff --git a/src/com/eactive/eai/adapter/AdapterPropInfoVO.java b/src/com/eactive/eai/adapter/AdapterPropInfoVO.java new file mode 100644 index 0000000..8aea24f --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterPropInfoVO.java @@ -0,0 +1,93 @@ +package com.eactive.eai.adapter; + +import java.io.Serializable; + +/** + * 1. 기능 : 어댑터 프라퍼티 정보를 정의한 Java Value Object 클래스 + * 2. 처리 개요 : 어댑터 프라퍼티 정보를 정의한다. + * * - + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public class AdapterPropInfoVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String adptrCd; //어댑터코드[TSEAIAD04.AdptrCd] + private String adptrIODstcd; //어댑터입출력구분코드[TSEAIAD04.AdptrIODstcd] + private String adptrPrptyName; //어댑터프라퍼티명[TSEAIAD04.AdptrPrptyName] + private String adptrPrptyDesc; //어댑터프라퍼티설명[TSEAIAD04.AdptrPrptyDesc] + + /** + * Constructor + */ + public AdapterPropInfoVO(String adptrCd, String adptrIODstcd, String adptrPrptyName, String adptrPrptyDesc) { + this.adptrCd = adptrCd; + this.adptrIODstcd = adptrIODstcd; + this.adptrPrptyName = adptrPrptyName; + this.adptrPrptyDesc = adptrPrptyDesc; + } + + /** + * @return Returns the adptrCd. + */ + public String getAdptrCd() { + return adptrCd; + } + + /** + * @param adptrCd The adptrCd to set. + */ + public void setAdptrCd(String adptrCd) { + this.adptrCd = adptrCd; + } + + /** + * @return Returns the adptrIODstcd. + */ + public String getAdptrIODstcd() { + return adptrIODstcd; + } + + /** + * @param adptrIODstcd The adptrIODstcd to set. + */ + public void setAdptrIODstcd(String adptrIODstcd) { + this.adptrIODstcd = adptrIODstcd; + } + + /** + * @return Returns the adptrPrptyDesc. + */ + public String getAdptrPrptyDesc() { + return adptrPrptyDesc; + } + + /** + * @param adptrPrptyDesc The adptrPrptyDesc to set. + */ + public void setAdptrPrptyDesc(String adptrPrptyDesc) { + this.adptrPrptyDesc = adptrPrptyDesc; + } + + /** + * @return Returns the adptrPrptyName. + */ + public String getAdptrPrptyName() { + return adptrPrptyName; + } + + /** + * @param adptrPrptyName The adptrPrptyName to set. + */ + public void setAdptrPrptyName(String adptrPrptyName) { + this.adptrPrptyName = adptrPrptyName; + } + +} diff --git a/src/com/eactive/eai/adapter/AdapterPropQuery.java b/src/com/eactive/eai/adapter/AdapterPropQuery.java new file mode 100644 index 0000000..b8a4cda --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterPropQuery.java @@ -0,0 +1,63 @@ +package com.eactive.eai.adapter; + +import com.eactive.eai.common.dao.Keys; +/** + * 1. 기능 : AdapterPropDAO에서 사용하는 SQL Query문을 정의한 상수 인터페이스 + * 2. 처리 개요 : AdapterPropDAO에서 사용하는 SQL Query문을 상수로 정의한다. + * * - + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public interface AdapterPropQuery +{ + /** + * 어댑터 유형 별 모든 프라퍼티 정보 조회 + */ + public static final String GET_ALL_ADPT_PROP_INFO = + //AdptrCd, AdptrName + //AdptrPrptyName, AdptrPrptyDesc, AdptrCd, AdptrIODstcd + " SELECT a.AdptrCd, a.AdptrName, b.AdptrIODstcd, b.AdptrPrptyName, b.AdptrPrptyDesc \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIAD03 a, " + Keys.TABLE_OWNER + "TSEAIAD04 b \n" + + " WHERE a.AdptrCd = b.AdptrCd \n" + + " ORDER BY a.AdptrCd "; + + /** + * 특정 어댑터 유형에 해당하는 프라퍼티 정보 조회 + */ + public static final String GET_ADPT_PROP_INFO = + " SELECT a.AdptrCd, a.AdptrName, b.AdptrIODstcd, b.AdptrPrptyName, b.AdptrPrptyDesc \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIAD03 a, " + Keys.TABLE_OWNER + "TSEAIAD04 b \n" + + " WHERE a.AdptrCd = b.AdptrCd \n" + + " AND a.AdptrCd = ? "; + + /** + * 어댑터 유형 추가 + */ + public static final String ADD_ADPT_TP = + " INSERT INTO " + Keys.TABLE_OWNER + "TSEAIAD03 ( AdptrCd, AdptrName ) VALUES ( ?, ? ) "; + + /** + * 어댑터 프라퍼티 정보 추가 + */ + public static final String ADD_ADPT_PROP_INFO = + " INSERT INTO " + Keys.TABLE_OWNER + "TSEAIAD04 ( AdptrCd, AdptrIODstcd, AdptrPrptyName, AdptrPrptyDesc ) \n" + + " VALUES ( ?, ?, ?, ? ) "; + + /** + * 어댑터 유형 수정 + * 어댑터명만 수정 가능 + */ + public static final String UPDATE_ADPT_TP = + " UPDATE " + Keys.TABLE_OWNER + "TSEAIAD03 SET AdptrName = ? WHERE AdptrCd = ? "; + + /** + * 어댑터 프라퍼티 정보 수정 + */ + public static final String UPDATE_ADPT_PROP_INFO = + " UPDATE " + Keys.TABLE_OWNER + "TSEAIAD04 SET AdptrPrptyDesc = ? \n" + + " WHERE AdptrCd = ? AND AdptrIODstcd = ? AND AdptrPrptyName = ? "; +} diff --git a/src/com/eactive/eai/adapter/AdapterQuery.java b/src/com/eactive/eai/adapter/AdapterQuery.java new file mode 100644 index 0000000..9fef814 --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterQuery.java @@ -0,0 +1,110 @@ +package com.eactive.eai.adapter; + +import com.eactive.eai.common.dao.Keys; +/** +* 1. 기능 : AdapterDAO에서 사용하는 SQL Query문을 정의한 상수 인터페이스 +* 2. 처리 개요 : AdapterDAO에서 사용하는 SQL Query문을 상수로 정의한다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public interface AdapterQuery +{ + + /** + * 모든 어댑터그룹 정보를 SELECT하는 QUERY + * 어댑터 사용여부 = '1' + */ + public static final String SELECT_ALL_GROUPS = + "SELECT A.AdptrBzwkGroupName ,\n" + + " A.AdptrCd ,\n" + + " A.AdptrUseYn ,\n" + + " A.AdptrBzwkGroupDesc ,\n" + + " B.BjobBzwkDstcd ,\n" + + " LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBA01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" + + "WHERE A.AdptrBzwkGroupName = B.AdptrBzwkGroupName \n" + + "AND A.AdptrUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' "; + + + /** + * 어댑터그룹에 해당되는 어댑터 정보를 SELECT하는 QUERY + */ + public static final String SELECT_ADAPTERS_BY_GROUP = + "SELECT A.AdptrBzwkGroupName ,\n" + + " A.AdptrBzwkName ,\n" + + " A.LstnerClsName ,\n" + + " A.PrptyGroupName ,\n" + + " A.AdptrDesc ,\n" + + " B.SysLnkgDstcd ,\n" + + " B.BjobBzwkDstcd ,\n" + + " LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd,\n" + + " B.LnkgIPInfoName ,\n" + + " B.LnkgPortInfoName ,\n" + + " B.ToutVal ,\n" + + " C.RecvPrcssRuleCd ,\n" + + " C.OsidInstiName ,\n" + + " B.LnkgID ,\n" + + " B.LnkgPwd ,\n" + + " C.TelgmPcketSize ,\n" + + " B.RqstRspnsDstcd ,\n" + + " D.BjobBzwkName \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBA02 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ05 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 C \n" + + " LEFT OUTER JOIN " + Keys.TABLE_OWNER + "TSEAIBJ02 D \n" + + " on C.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "WHERE A.AdptrBzwkGroupName = B.AdptrBzwkGroupName \n" + + "AND A.AdptrBzwkName = B.AdptrBzwkName \n" + + "AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(B.OsidInstiDstcd)) = LTRIM(RTRIM( C.OsidInstiDstcd))\n" + + "AND A.AdptrBzwkGroupName = ? \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "AND B.RqstRspnsDstcd in ('A', 'C') \n" + + "AND C.ThisMsgUseYn = '1' "; + + /** + * 어댑터 그룹 정보 상세조회 + */ + public static final String GET_ADAPTER_GROUP = + "SELECT A.AdptrBzwkGroupName ,\n" + + " A.AdptrCd ,\n" + + " A.AdptrUseYn ,\n" + + " A.AdptrBzwkGroupDesc ,\n" + + " B.BjobBzwkDstcd ,\n" + + " LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBA01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" + + "WHERE A.AdptrBzwkGroupName = B.AdptrBzwkGroupName \n" + + "AND A.AdptrBzwkGroupName = ? "; + + + /** + * 어댑터 정보 상세조회 + */ + public static final String GET_ADAPTERS = + "SELECT a.AdptrBzwkGroupName,\n" + + " a.AdptrBzwkName ,\n" + + " a.LstnerClsName ,\n" + + " a.PrptyGroupName ,\n" + + " a.AdptrDesc ,\n" + + " b.PrptyGroupDesc \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBA02 a LEFT OUTER JOIN\n" + + Keys.TABLE_OWNER + "TSEAIBP01 b \n" + + " ON a.PrptyGroupName = b.PrptyGroupName \n" + + "WHERE a.AdptrBzwkGroupName = ? "; + + /** + * 어댑터 그룹명 조회 + */ + public static final String SELECT_ADPT_GROUP_NAMES = + "SELECT AdptrBzwkGroupName \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBA01\n" + + "ORDER BY AdptrBzwkGroupName "; + +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/AdapterTypeVO.java b/src/com/eactive/eai/adapter/AdapterTypeVO.java new file mode 100644 index 0000000..ea36dc9 --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterTypeVO.java @@ -0,0 +1,63 @@ +package com.eactive.eai.adapter; + +import java.io.Serializable; +import java.util.ArrayList; + +/** + * 1. 기능 : 어댑터유형을 정의한 Java Value Object 클래스 + * 2. 처리 개요 : 어댑터유형을 정의한다. + * * - + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public class AdapterTypeVO implements Serializable +{ + private static final long serialVersionUID = 1L; + private String adptrCd; + private String adptrName; + + private ArrayList propInfo; + + public AdapterTypeVO() { + this("", ""); + } + + public AdapterTypeVO(String adptrCd, String adptrName) { + this.adptrCd = adptrCd; + this.adptrName = adptrName; + this.propInfo = new ArrayList(); + } + + public String getAdptrCd() { + return adptrCd; + } + + public void setAdptrCd(String adptrCd) { + this.adptrCd = adptrCd; + } + + public String getAdptrName() { + return adptrName; + } + + public void setAdptrName(String adptrName) { + this.adptrName = adptrName; + } + + public ArrayList getPropInfo() { + return propInfo; + } + + public void setPropInfo(ArrayList propInfo) { + this.propInfo = propInfo; + } + + public void addAdapterPropInfo(String adptrCd, String adptrIODstcd, String adptrPrptyName, String adptrPrptyDesc) { + AdapterPropInfoVO vo = new AdapterPropInfoVO(adptrCd, adptrIODstcd, adptrPrptyName, adptrPrptyDesc); + this.propInfo.add(vo); + } +} diff --git a/src/com/eactive/eai/adapter/AdapterVO.java b/src/com/eactive/eai/adapter/AdapterVO.java new file mode 100644 index 0000000..04a7c87 --- /dev/null +++ b/src/com/eactive/eai/adapter/AdapterVO.java @@ -0,0 +1,475 @@ +package com.eactive.eai.adapter; + +import java.io.Serializable; + +import com.eactive.eai.adapter.listener.AdapterException; +import com.eactive.eai.adapter.listener.AdapterListener; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +/** +* 1. 기능 : 어댑터 정보를 표현하는 Java Value Object 클래스. +* 2. 처리 개요 : 어댑터 정보를 정의한다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : Serializable, Lifecycle +* @since : +*/ +public class AdapterVO implements Serializable, Lifecycle +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default Logger + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + private AdapterGroupVO adapterGroupVO; //어댑터 그룹 + + private String adapterGroupName; //어뎁터업무그룹명[TSEAIAD02.AdptrBzwkGroupName] + private String name; //어뎁터업무명[TSEAIAD02.AdptrBzwkName] +// private String eaiSevrInstncName; //서버인스탄스명[TSEAIAD02.EAISevrInstncName] - migration added. + private String listenerClass; //리스너클래스명[TSEAIAD02.LstnerClsName] +// private String testCallClass; //테스터클래스명[TSEAIAD02.TestClsName] + private String propGroupName; //프라퍼티그룹명[TSEAIAD02.PrptyGroupName] + private String description; //어댑터설명[TSEAIAD02.AdptrDesc] + private String propGroupDesc; //프라퍼티그룹설명 + + private String batchSystemConnCode; //BATCH작업업무구분코드[TSEAIBJ05.SysLnkgDstCd] [JUNGFUX] 추가 2006/02/20 + private String batchProcessCode; //BATCH작업업무구분코드[TSEAIBJ05.BjobBzwkDstcd] [JUNGFUX] 추가 2006/02/20 + private String batchProcessName; //BATCH작업업무구분코드[TSEAIBJ05.BjobBzwkName] [JUNGFUX] 추가 2006/11/17 + private String batchInstitutionCode; //BATCH작업업무구분코드[TSEAIBJ05.OsidInstiDstCd] [JUNGFUX] 추가 2006/02/20 + private String batchServerIP; //BATCH작업업무구분코드[TSEAIBJ05.LnkgIPInfoName] [JUNGFUX] 추가 2006/02/20 + private String batchServerPortNo; //BATCH작업업무구분코드[TSEAIBJ05.LnkgPortInfoName] [JUNGFUX] 추가 2006/02/20 + private int batchInterMsgTimeout; //BATCH소켓서버전문간Timeout[TSEAIBJ05.ToutVal] [JUNGFUX] 추가 2006/02/20 + private String batchRcvFlowRuleCode; //BATCH수신처리규칙코드[TSEAIBJ02.SysLnkgPortNo] [JUNGFUX] 추가 2006/02/20 + //20060328 add by khs + private String batchInstitutionName; // 대외기관 이름 + //20060329 add by khs + private String lnkID; + private String lnkPwd; + //20060331 add by khs +// private String batchInstitutionType; // 퇴직연금 전문조립에 사용되는 대외기관 구분 : 1, 2,3,4,5 등 가능 + //20060411 add by khs + private int batchPacketSize; + //20060425 add by khs + private String rqstRspnsDstcd; // 응답수신('A'), 응답송신('C'), 요구('R') 구분 + + private ConfigurationContext context; + + /** + * 어댑터 상태 + */ + private boolean status; + + /** + * AdapterListener instance + */ + transient private AdapterListener adapterListener; + //private AdapterListener adapterListener; + + + /** + * 기동여부 + */ + private boolean started; + /** + * LifecycleSupport instance + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 1. 기능 : Defualt Constructor + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + **/ + public AdapterVO() { + } + + /** + * 1. 기능 : 어댑터를 초기화하는 생성자 함수 + * 2. 처리 개요 : 어댑터를 초기화한다. + * 3. 주의사항 + * + * @param name 어뎁터업무 이름 + **/ + public AdapterVO(String name) { + this.name = name; + } + + /** + * 1. 기능 : 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + + public void setAdapterGroupName(String adapterGroupName) { + this.adapterGroupName = adapterGroupName; + } + + public String getAdapterGroupName() { + return this.adapterGroupName; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public void setListenerClass(String listenerClass) { + this.listenerClass = listenerClass; + } + + public String getListenerClass() { + return this.listenerClass; + } + +// public void setTestCallClass(String testCallClass) { +// this.testCallClass = testCallClass; +// } +// +// public String getTestCallClass() { +// return this.testCallClass; +// } + + public void setPropGroupName(String propGroupName) { + this.propGroupName = propGroupName; + } + + public String getPropGroupName() { + return this.propGroupName; + } + + public void setAdapterGroupVO(AdapterGroupVO group) { + this.adapterGroupVO = group; + } + + public AdapterGroupVO getAdapterGroupVO() { + return this.adapterGroupVO; + } + + /** + * 1. 기능 : TestCallManager에 어댑터 정보를 설정하는 메서드 + * 2. 처리 개요 : 어댑터 상태 설정 + * 3. 주의사항 + * + * @param status 어댑터 상태 + * + **/ + public synchronized void setStatus(boolean status) { + this.status = status; + +// if (this.status==false && this.testCallClass!=null && !this.testCallClass.equals("")) { +// TestCallManager tmanager = TestCallManager.getInstance(); +// try { +// tmanager.addTester(this); +// logger.info(ExceptionUtil.make("BICEAIMAD034", new String[] {this.toString()})); +// +// } catch(Exception e) { +// throw new RuntimeException(ExceptionUtil.getErrorCode(e, "BICEAIMAD035")); +// } +// } + + if(this.status) { + this.adapterGroupVO.active(this); + } else { + this.adapterGroupVO.disable(this); + } + } + + public boolean isStatus() { + return this.status; + } + + /** + * 1. 기능 : Lifecycle의 start 메서드로 AdapterVO 초기화하는 메서드 + * 2. 처리 개요 : AdapterVO를 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었을 경우 + * + **/ + public void start() throws LifecycleException { + if (started) + throw new LifecycleException("BECEAIMAD036"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + if(listenerClass!=null && !"".equals(listenerClass)) { + try { + adapterListener = (AdapterListener)Class.forName(listenerClass).newInstance(); + adapterListener.setAdapterInfo(this); + adapterListener.start(); + } catch(Exception e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD037")); + } + } + + started = true; + status = true; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 어댑터 정보를 clear 하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱한 어댑터 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMAD038"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + try { + if(adapterListener!=null) adapterListener.stop(); + } catch(AdapterException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD039")); + } + + started = false; + status = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDescription() { + return this.description; + } + +// public void setEaiSevrInstncName(String eaiSevrInstncName) { +// this.eaiSevrInstncName = eaiSevrInstncName; +// } +// +// public String getEaiSevrInstncName() { +// return this.eaiSevrInstncName; +// } + + public void setPropGroupDesc(String propGroupDesc) { + this.propGroupDesc = propGroupDesc; + } + + public String getPropGroupDesc() { + return this.propGroupDesc; + } + + public void setContext(ConfigurationContext context) { + this.context = context; + } + + public ConfigurationContext getContext() { + return this.context; + } + + /** + * 1. 기능 : 어댑터 정보를 String 형태로 반환하는 메서드 + * 2. 처리 개요 : String 형태로 어댑터 정보를 반환한다. + * 3. 주의사항 + * + * @return String 어댑터 정보 + **/ + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("\n AdapterVO [ name=").append(name); + sb.append(", adapterGroupName=").append(adapterGroupName); +// sb.append(", eaiSevrInstncName=").append(eaiSevrInstncName); + sb.append(", listenerClass=").append(listenerClass); +// sb.append(", testCallClass=").append(testCallClass); + sb.append(", propGroupName=").append(propGroupName); + sb.append(", description=").append(description); + sb.append(", status=").append(status); + sb.append(", context=").append(context); + sb.append(", batchSystemConnCode=").append(batchSystemConnCode); + sb.append(", batchProcessCode=").append(batchProcessCode); + sb.append(", batchProcessName=").append(batchProcessName); + sb.append(", batchInstitutionCode=").append(batchInstitutionCode); + sb.append(", batchServerIP=").append(batchServerIP); + sb.append(", batchServerPortNo=").append(batchServerPortNo); + sb.append(", batchInterMsgTimeout=").append(batchInterMsgTimeout); + sb.append(", batchRcvFlowRuleCode=").append(batchRcvFlowRuleCode); + sb.append(", batchInstitutionCode=").append(this.batchInstitutionName); +// sb.append(", batchInstitutionType=").append(this.batchInstitutionType); + sb.append(" ]"); + + return sb.toString(); + } + + public void setBatchSystemConnCode(String batchSystemConnCode) { + this.batchSystemConnCode = batchSystemConnCode; + } + + public String getBatchSystemConnCode() { + return this.batchSystemConnCode; + } + + public void setBatchProcessCode(String batchProcessCode) { + this.batchProcessCode = batchProcessCode; + } + + public String getBatchProcessCode() { + return this.batchProcessCode; + } + + public void setBatchProcessName(String batchProcessName) { + this.batchProcessName = batchProcessName; + } + + public String getBatchProcessName() { + return this.batchProcessName; + } + + public void setBatchInstitutionCode(String batchInstitutionCode) { + this.batchInstitutionCode = batchInstitutionCode; + } + + public String getBatchInstitutionCode() { + return this.batchInstitutionCode; + } + + public void setBatchInstitutionName(String batchInstitutionName) { + this.batchInstitutionName = batchInstitutionName; + } + + public String getBatchInstitutionName() { + return this.batchInstitutionName; + } +// public void setBatchInsitutionType(String batchInstitutionType) { +// this.batchInstitutionType = batchInstitutionType; +// } +// public String getBatchInstitutionType() { +// return this.batchInstitutionType; +// } + + + public void setBatchServerIP(String batchServerIP) { + this.batchServerIP = batchServerIP; + } + + public String getBatchServerIP() { + return this.batchServerIP; + } + + public void setBatchServerPortNo(String batchServerPortNo) { + this.batchServerPortNo = batchServerPortNo; + } + + public String getBatchServerPortNo() { + return this.batchServerPortNo; + } + + public void setBatchInterMsgTimeout(int batchInterMsgTimeout) { + this.batchInterMsgTimeout = batchInterMsgTimeout; + } + + public int getBatchInterMsgTimeout() { + return this.batchInterMsgTimeout; + } + + public void setBatchRcvFlowRuleCode(String batchRcvFlowRuleCode) { + this.batchRcvFlowRuleCode = batchRcvFlowRuleCode; + } + + public String getBatchRcvFlowRuleCode() { + return this.batchRcvFlowRuleCode; + } + + public void setLnkID(String lnkID) { + this.lnkID = lnkID; + } + + public String getLnkID() { + return this.lnkID; + } + + public void setLnkPwd(String lnkPwd) { + this.lnkPwd = lnkPwd; + } + + public String getLnkPwd() { + return this.lnkPwd; + } + + public int getPacketSize() { + return this.batchPacketSize; + } + + public void setPacketSize(int packetSize) { + this.batchPacketSize = packetSize; + } + + //20060425 add by khs for 응답송신 + public String getRqstRspnsDstcd() { + return this.rqstRspnsDstcd; + } + //20060425 add by khs for 응답송신 + public void setRqstRspnsDstcd(String rqstRspnsDstcd) { + this.rqstRspnsDstcd = rqstRspnsDstcd; + } +} diff --git a/src/com/eactive/eai/adapter/Keys.java b/src/com/eactive/eai/adapter/Keys.java new file mode 100644 index 0000000..b29b968 --- /dev/null +++ b/src/com/eactive/eai/adapter/Keys.java @@ -0,0 +1,22 @@ +package com.eactive.eai.adapter; + +/** +* 1. 기능 : adapter 패키지에서 사용하는 상수를 정의한 Interface +* 2. 처리 개요 : +* - adapter 패키지에서 사용하는 상수를 정의한 Interface +* 3. 주의사항 +*/ +public interface Keys +{ + + /** + * 어댑터 타입 - NET(Socket) + */ + public static final String TYPE_NET = "SOC"; + + /** + * 어댑터 타입 - X25 + */ + public static final String TYPE_X25 = "X25"; + +} diff --git a/src/com/eactive/eai/adapter/RequestDispatcher.java b/src/com/eactive/eai/adapter/RequestDispatcher.java new file mode 100644 index 0000000..0c81339 --- /dev/null +++ b/src/com/eactive/eai/adapter/RequestDispatcher.java @@ -0,0 +1,151 @@ +package com.eactive.eai.adapter; + +import java.util.HashMap; + +import com.eactive.eai.adapter.socket.service.InboundControl; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.inbound.ResponseHandler; + +/** +* 1. 기능 : AdapterGroupVO와 AdapterVO 생성 +* 2. 처리 개요 : +* - AdapterGroupVO와 AdapterVO 생성 +* - Adapter.isStatus()를 통해 어뎁터 상태 확인 +* - property에 어뎁터 그룹명, 어뎁터 명, 표준메시지여부, REQUESTACTION class 등록 +* - Processor 클래스의 execute(Object message, Properties prop) 호출 +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : AdapterGroupVO, AdapterVO +* @since : +*/ +public class RequestDispatcher +{ + /** + * Default Logger + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + /** + * RequestDispatcher HashMap + */ + private static HashMap dispatchers = new HashMap(); + + /** + * 1. 기능 : RequestDispatcher HashMap 객체로 부터 + * 요청한 어탭터 그룹의 RequestDispatcher instance 획득 + * 2. 처리 개요 : + * - RequestDispatcher HashMap 객체로 부터 요청한 어탭터 그룹의 RequestDispatcher instance 획득 + * - RequestDispatcher instance가 없으면 생성 한다. + * 3. 주의사항 + * + * @param adapterGroupName 어댑터 그룹명 + * @return RequestDispatcher instance + **/ + public static RequestDispatcher getRequestDispatcher(String adapterGroupName) { + RequestDispatcher dispatcher = dispatchers.get(adapterGroupName); + if(dispatcher==null) { + dispatcher = new RequestDispatcher(adapterGroupName); + dispatchers.put(adapterGroupName, dispatcher); + } + + return dispatcher; + } + + /** + * 어댑터 그룹명 + */ + private String adapterGroupName; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : + * - 어댑터 그룹명 초기화 + * - ProcessorFactory instance 생성 + * 3. 주의사항 + * + * @param adapterGroupName 어댑터 그룹명 + **/ + private RequestDispatcher(String adapterGroupName) { + this.adapterGroupName = adapterGroupName; + } + + + /** + * 1. 기능 : Processor 클래스의 execute(Object message, Properties prop) 호출 + * 2. 처리 개요 : + * - 어댑터 프라퍼티를 설정하고 Processor Class의 + * execute(Object message, Properties prop) method 호출 + * - 리턴된 메시지 객체를 반환 + * 3. 주의사항 + * + * @param adapterName 어댑터명 + * @param message 요청 메시지 + * @param prop 어댑터 프라퍼티 + * @return Object Processor로 부터 리턴된 message Object + * @exception Exception Adapter가 없거나 액티브 상태가 아닐때, 프라퍼티 설정 오류 시 발생 + **/ + //public BatchDoc handle(InboundControl control) throws Exception { + public void handle(InboundControl control) throws Exception { + + logger.debug("[ELINK]################ RequestDispatcher.handle() 호출됨."); + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + String adapterName = control.getAdapterName(); + AdapterManager manager = AdapterManager.getInstance(); + AdapterGroupVO group = manager.getAdapterGroupVO(this.adapterGroupName); + if(group == null) { + String code = "BECEAIMAD042"; + String[] msgArgs = new String[2]; + msgArgs[0] = adapterGroupName; + msgArgs[1] = adapterName; + String errText = ExceptionUtil.make(code, msgArgs); + if (logger.isError()) logger.error(errText); + throw new Exception(errText); + } + + AdapterVO adapter = group.getAdapterVO(adapterName); + if(adapter==null) { + String code = "BECEAIMAD022"; + String[] msgArgs = new String[3]; + msgArgs[0] = adapterGroupName; + msgArgs[1] = adapterName; + msgArgs[2] = group.toString(); + String errText = ExceptionUtil.make(code, msgArgs); + if (logger.isError()) logger.error(errText); + throw new Exception(errText); + } + + + if(!adapter.isStatus()) { + String code = "BECEAIMAD023"; + String[] msgArgs = new String[1]; + msgArgs[0] = adapter.toString(); + String errText = ExceptionUtil.make(code, msgArgs); + if (logger.isError()) logger.error(errText); + throw new Exception(errText); + } + + //BatchDoc batchMsgDoc = null; + try { + group.increase(); + ResponseHandler handler = new ResponseHandler(); + BatchDoc batchMsgDoc = handler.execute(control.getBatchMsgDoc()); + control.setBatchMsgDoc(batchMsgDoc); + ////batchMsgDoc = handler.execute(control.getBatchMsgDoc()); + + } catch(Exception e) { + throw new Exception(ExceptionUtil.getErrorCode(e, "BECEAIMAD025")); + } finally { + group.decrease(); + } + + logger.debug("[ELINK]################ RequestDispatcher.handle() 종료. (수행 시간: "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec)"); + //return batchMsgDoc; + } +} diff --git a/src/com/eactive/eai/adapter/WLIAdapter.java b/src/com/eactive/eai/adapter/WLIAdapter.java new file mode 100644 index 0000000..8e0a4cf --- /dev/null +++ b/src/com/eactive/eai/adapter/WLIAdapter.java @@ -0,0 +1,52 @@ +package com.eactive.eai.adapter; + +import java.util.Properties; + +/** + * 1. 기능 : EAI 엔진에서 어댑터을 common하게 접근하기 위한 Interface + * 2. 처리 개요 : + * - execute hookup method를 실행한다. + * - 실재 어댑터를 통해 통신 한다. + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public interface WLIAdapter +{ + /** + * 1. 기능 : execute hookup method를 실행한다. + * 2. 처리 개요 : + * - execute hookup method를 실행한다. + * 3. 주의사항 + * + * @param prop 어댑터 Property + * @param message 전문 메시지 + **/ + //public Object callService(Properties prop, Object message) throws Exception; + + /** + * 1. 기능 : execute hookup method를 실행한다. + * 2. 처리 개요 : + * - execute hookup method를 실행한다. + * 3. 주의사항 + * + * @param adapterGroupName 어댑터 그룹명 + * @param prop 어댑터 Property + * @param message 전문 메시지 + **/ + public Object callService(String adapterGroupName, Properties prop, Object message) throws Exception; + + /** + * 1. 기능 : 실재 어댑터를 통해 통신하는 로직을 구현한다. + * 2. 처리 개요 : + * - 실재 어댑터를 통해 통신하는 로직을 구현한다. + * 3. 주의사항 + * + * @param prop 어댑터 Property + * @param message 전문 메시지 + **/ + public Object execute(Properties prop, Object message) throws Exception; +} diff --git a/src/com/eactive/eai/adapter/WLIAdapterFactory.java b/src/com/eactive/eai/adapter/WLIAdapterFactory.java new file mode 100644 index 0000000..f1f584e --- /dev/null +++ b/src/com/eactive/eai/adapter/WLIAdapterFactory.java @@ -0,0 +1,95 @@ +//package com.eactive.eai.adapter; +// +//import java.util.HashMap; +//import com.eactive.eai.adapter.socket.SocketAdapter; +// +///** +//* 1. 기능 : 어댑터를 초기화 하기 위한 Factory Class +//* 2. 처리 개요 : +//* - 초기화 된 어댑터 인스턴스를 HashMap 객체에 담는다. +//* - 해당 어댑터의 WLIAdapter 인스턴스를 반환 한다. +//* 3. 주의사항 +//* +//*/ +//public class WLIAdapterFactory +//{ +// +// private static final WLIAdapterFactory factory = new WLIAdapterFactory(); +// +// private HashMap adapterMap; +// +// /** +// * 1. 기능 : Default Constructor +// * 2. 처리 개요 : +// * - 타입 별 어댑터 instance를 어댑터 HashMap에 담는다. +// * 3. 주의사항 +// * +// **/ +// private WLIAdapterFactory() { +// // 초기화 코드는 여기에 넣어 주세요. +// //try { +// adapterMap = new HashMap(); +// //adapterMap.put(Keys.TYPE_HTTP, new HttpClientAdapter()); +// //adapterMap.put(Keys.TYPE_SNA, new SNAAdapterClient()); +// //adapterMap.put(Keys.TYPE_NET, SocketAdapter.getInstance()); +// +// //adapterMap.put(Keys.TYPE_IMS, new IMSAdapter()); +// //adapterMap.put(Keys.TYPE_IMS, IMSAdapter.getInstance()); +// //} catch(Exception e) { +// // throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAIAAC026")); +// //} +// } +// +// /** +// * 1. 기능 : WLIAdapterFactory Object를 반환하는 getter method +// * 2. 처리 개요 : WLIAdapterFactory Object를 반환한다. +// * 3. 주의사항 +// * +// * @return WLIAdapterFactory object +// **/ +// public static WLIAdapterFactory newInstance() { +// return factory; +// } +// +// /** +// * 1. 기능 : 해당 어댑터의 WLIAdapter Object를 반환 +// * 2. 처리 개요 : +// * - WLIAdapter instance HashMap으로 부터 해당 어댑터의 WLIAdapter Object를 반환 한다. +// * 3. 주의사항 +// * +// * @param adapterName 어댑터명 +// * @return WLIAdapter object +// **/ +// public WLIAdapter getWLIAdapter(String adapterName) { +// WLIAdapter adapter = (WLIAdapter)adapterMap.get(adapterName); +// if(adapter==null) { +// adapter = createAdapter(adapterName); +// } +// if(adapter==null) { +// throw new RuntimeException("등록된 어댑터를 찾을 수 없습니다. - "+adapterName); +// } +// return adapter; +// } +// +// private synchronized WLIAdapter createAdapter(String adapterName) { +// if(adapterName==null) return null; +// +// WLIAdapter adapter = null; +// if(adapterName.equals(Keys.TYPE_HTTP)) { +// //adapter = new HttpClientAdapter(); +// //adapterMap.put(Keys.TYPE_HTTP, adapter); +// } else if(adapterName.equals(Keys.TYPE_SNA)) { +// //adapter = new SNAAdapterClient(); +// //adapterMap.put(Keys.TYPE_SNA, adapter); +// } else if(adapterName.equals(Keys.TYPE_NET)) { +// adapter = SocketAdapter.getInstance(); +// adapterMap.put(Keys.TYPE_NET, adapter); +// } else if(adapterName.equals(Keys.TYPE_IMS)) { +// //adapter = IMSAdapter.getInstance(); +// //adapterMap.put(Keys.TYPE_IMS, adapter); +// } +// +// return adapter; +// } +//} + diff --git a/src/com/eactive/eai/adapter/WLIDefaultAdapter.java b/src/com/eactive/eai/adapter/WLIDefaultAdapter.java new file mode 100644 index 0000000..ed5e351 --- /dev/null +++ b/src/com/eactive/eai/adapter/WLIDefaultAdapter.java @@ -0,0 +1,91 @@ +package com.eactive.eai.adapter; + +import java.util.Properties; + +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : WLIAdapter Interface를 implements 한 Default WLIAdapter +* 2. 처리 개요 : +* - execute hookup method를 실행한다. +* - 실재 어댑터를 통해 통신 한다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : WLIAdapter, AdapterManager +* @since : +*/ +public class WLIDefaultAdapter implements WLIAdapter +{ + /** + * Default Logger + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + /** + * AdapterManager instance + */ + private AdapterManager manager; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : + * - AdapterManager instance를 생성한다. + * 3. 주의사항 + * + **/ + public WLIDefaultAdapter() { + this.manager = AdapterManager.getInstance(); + } + /* + public Object callService(Properties prop, Object message) throws Exception { + return callService(null,prop,message); + } + */ + + /** + * 1. 기능 : execute hookup method를 실행한다. + * 2. 처리 개요 : + * - execute hookup method를 실행한다. + * 3. 주의사항 + * + * @param adapterGroupName 어댑터 그룹명 + * @param prop 어댑터 Property + * @param message 전문 메시지 + **/ + public Object callService(String adapterGroupName, Properties prop, Object message) throws Exception{ + AdapterGroupVO group = this.manager.getAdapterGroupVO(adapterGroupName); + if(group==null) { + String code = "BECEAIMAD027"; + String[] msgArgs = new String[1]; + msgArgs[0] = adapterGroupName; + String errText = ExceptionUtil.make(code, msgArgs); + if (logger.isError()) logger.error(errText); + throw new Exception(errText); + } + + if(group!=null) group.increase(); + try { + return execute(prop, message); + } catch(Throwable e) { + throw new Exception(ExceptionUtil.getErrorCode(e, "BECEAIMAD028")); + } finally { + if(group!=null) group.decrease(); + } + } + + /** + * 1. 기능 : 실재 어댑터를 통해 통신하는 로직을 구현한다. + * 2. 처리 개요 : + * - 실재 어댑터를 통해 통신하는 로직을 구현한다. + * 3. 주의사항 + * + * @param prop 어댑터 Property + * @param message 전문 메시지 + **/ + public Object execute(Properties prop, Object message) throws Exception { + throw new java.lang.UnsupportedOperationException("BECEAIMAD029"); + } +} diff --git a/src/com/eactive/eai/adapter/ftp/FTP00.java b/src/com/eactive/eai/adapter/ftp/FTP00.java new file mode 100644 index 0000000..a220c4b --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTP00.java @@ -0,0 +1,578 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPFileObject; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + + +/** + * 우체국 공융 ftp 전송을 위함 SFTP + * + * 파일명 : FTP00 + * + */ + +public class FTP00 extends Transfer implements SocketService { + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + + private static final String REMOTE_PATH = "remote.path";// 원격지 경로 #YYYYMMDD# + private static final String FILENAME_PATTERN = "filename.pattern";// 기준일자 [YYYYMMDD] 당일이전일 [YYYYMMDD-1][YYYYMMDD-2][YYYYMMDD+1] + private static final String EXT_NAME = "ext.name"; + private static final String FTP_FILE_TYPE = "ftp.file.type";// ftp ASCII 인 경우만 default BINARY + private static final String BASE_DATE_OVER_YN = "basedate.over.yn"; // 기준일 이후 파일전송여부 + + /** ftp 0 , 인증 방법 1 = id, 2 = key 방식 */ + private static final String AUTH_TYPE = "sftp.auth.type"; + + private static final String TRANS_LIB = "sftp.trans.lib"; + + @Override + public void sendFile(BatchDoc batchDoc) throws Exception { + // TODO Auto-generated method stub + if(logger.isInfoEnabled()) + logger.info("[FTP00] ■ 대외기관→FEP 파일 송신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH, ""); + + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String ftpgb = pmanager.getProperties(propName).getProperty(AUTH_TYPE, "1"); + + + //baseDate 추출 + String baseDate = DatetimeUtil.getCurrentDate(); + String reqFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (reqFileName != null && reqFileName.length() > 8) { + String extName = pmanager.getProperties(propName).getProperty(EXT_NAME); + if(extName != null && extName.trim().length() > 0){ + //String reqFileNameNoExt = reqFileName.replace(extName, ""); + String reqFileNameNoExt = reqFileName.substring(0, reqFileName.lastIndexOf(extName));// 20241230 + if (reqFileNameNoExt.length() >= 8 && DatetimeUtil.isRightDate(reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8))) { + baseDate = reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + } + +// remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate); + if(remotePath.indexOf("#YYYYMMDD#") > -1){ + remotePath = remotePath.replace("#YYYYMMDD#", baseDate); + }else if(remotePath.indexOf("#YYYYMMDD-1#") > -1) { + baseDate = DatetimeUtil.addDays(baseDate, -1); + remotePath = remotePath.replace("#YYYYMMDD-1#", baseDate); + }else if(remotePath.indexOf("#YYYYMMDD-2#") > -1) { + baseDate = DatetimeUtil.addDays(baseDate, -2); + remotePath = remotePath.replace("#YYYYMMDD-2#", baseDate); + }else if(remotePath.indexOf("#YYYYMMDD+1#") > -1) { + baseDate = DatetimeUtil.addDays(baseDate, 1); + remotePath = remotePath.replace("#YYYYMMDD+1#", baseDate);; + } + + if (!remotePath.endsWith("/")) + remotePath = remotePath + "/"; + + // 실제 파일이름 + //String orgFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + // FEP 에서 Rename(송신Real->송신Arch)한 파일이름 + String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName(); + + //logger.debug( "[FTP00]sendFileName:" + orgFileName); + + if(logger.isDebugEnabled()) + logger.debug( "[FTP00]remotePath:" + remotePath); + + //File 시작시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + //String sendFilePath = batchDoc.getBatchMsg().getHeader().getFilePath(); + + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + String transLib = pmanager.getProperties(propName).getProperty(TRANS_LIB, "JSCH"); + + try { + if("SSH".equals(transLib)) { + FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(), ftpgb); + }else { + FTPUtil.store(batchDoc, ipaddress, port, userid, + passwd, remotePath, batchDoc.getBatchMsg().getHeader().getFileName(), + sendFileName, + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), ftpgb); + } + } catch (Exception e) { + logger.error("[FTP00]파일송신에 실패하였습니다.", e); + throw e; + } + + //File 종료시간 설정 + setLastActivity(); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + // SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출. + this.disconnect(); + } + if(logger.isDebugEnabled()) + logger.info("[FTP00] ■ FEP → VAN사 파일 송신 완료."); + + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + if(logger.isInfoEnabled()) + logger.info("@@@@@@@FTP00] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, + batchDoc); + + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + if(logger.isDebugEnabled()) + logger.debug("@@@@FTP00]userid:" + userid); + //logger.debug("@@@@FTP00]passwd:" + passwd); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + batchDoc.getBatchMsg().getHeader().getProcessCode() + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + if (remotePath == null) { + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + + //SFTP방식 + String ftpgb = pmanager.getProperties(propName).getProperty(AUTH_TYPE, "1"); + + + // FTP_FILE_TYPE + String ftpFileType = pmanager.getProperties(propName).getProperty(FTP_FILE_TYPE, "BINARY"); + + if(logger.isDebugEnabled()) + logger.debug("[FTP00]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + //baseDate 추출 + String baseDate = DatetimeUtil.getCurrentDate(); + + String extName = ""; + String reqFileNameNoExt = reqFileName; + try { + extName = pmanager.getProperties(propName).getProperty(EXT_NAME); + if(extName != null && extName.trim().length() > 0) + reqFileNameNoExt = reqFileName.substring(0, reqFileName.lastIndexOf(extName));// 20241230 + }catch(Exception e) { + } + + if (reqFileNameNoExt != null && reqFileNameNoExt.length() > 8) { + if (reqFileNameNoExt.length() >= 8 && DatetimeUtil.isRightDate(reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8))) { + baseDate = reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + + //remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate); + if(remotePath.indexOf("#YYYYMMDD#") > -1){ + remotePath = remotePath.replace("#YYYYMMDD#", baseDate); + }else if(remotePath.indexOf("#YYYYMMDD-1#") > -1) { + baseDate = DatetimeUtil.addDays(baseDate, -1); + remotePath = remotePath.replace("#YYYYMMDD-1#", baseDate); + }else if(remotePath.indexOf("#YYYYMMDD-2#") > -1) { + baseDate = DatetimeUtil.addDays(baseDate, -2); + remotePath = remotePath.replace("#YYYYMMDD-2#", baseDate); + }else if(remotePath.indexOf("#YYYYMMDD+1#") > -1) { + baseDate = DatetimeUtil.addDays(baseDate, 1); + remotePath = remotePath.replace("#YYYYMMDD+1#", baseDate);; + } + if (!remotePath.endsWith("/")) + remotePath = remotePath + "/"; + + boolean isFileNameSet = false;// 파일이름이 설정되는지 여부 + try{// 파일 프로퍼티 + String propFileName = PROP_GROUP_NAME_PREFIX + "{" + batchDoc.getBatchMsg().getHeader().getProcessCode() + "_" + + batchDoc.getBatchMsg().getHeader().getBizCode() + "}"; + + String filenamePattern = pmanager.getProperties(propFileName).getProperty(FILENAME_PATTERN, ""); + if(filenamePattern != null && filenamePattern.length() > 0) { + isFileNameSet = true; + reqFileName = filenamePattern; + reqFileName = reqFileName.replace("[FILENAME]", batchDoc.getBatchMsg().getHeader().getBizCode()); + + if(reqFileName.indexOf("[YYYYMMDD]") > -1){ + reqFileName = reqFileName.replace("[YYYYMMDD]", baseDate); + }else if(reqFileName.indexOf("[YYYYMMDD-1]") > -1) { + String tmpbaseDate = DatetimeUtil.addDays(baseDate, -1); + reqFileName = reqFileName.replace("[YYYYMMDD-1]", tmpbaseDate); + }else if(reqFileName.indexOf("[YYYYMMDD-2]") > -1) { + String tmpbaseDate = DatetimeUtil.addDays(baseDate,-2); + reqFileName = reqFileName.replace("[YYYYMMDD-2]", tmpbaseDate); + }else if(reqFileName.indexOf("[YYYYMMDD+1]") > -1){ + String tmpbaseDate = DatetimeUtil.addDays(baseDate, 1); + reqFileName = reqFileName.replace("[YYYYMMDD+1]", tmpbaseDate); + } + + if(reqFileName.indexOf("[YYYYMM]") > -1){ + reqFileName = reqFileName.replace("[YYYYMM]", baseDate.substring(0,6)); + } + + + if(reqFileName.indexOf("[MMDD]") > -1) { + reqFileName = reqFileName.replace("[MMDD]", baseDate.substring(4)); + }else if(reqFileName.indexOf("[MMDD-1]") > -1) { + String tmpbaseDate = DatetimeUtil.addDays(baseDate,-1); + reqFileName = reqFileName.replace("[MMDD-1]", tmpbaseDate.substring(4)); + }if(reqFileName.indexOf("[MMDD-2]") > -1) { + String tmpbaseDate = DatetimeUtil.addDays(baseDate,-2); + reqFileName = reqFileName.replace("[MMDD-2]", tmpbaseDate.substring(4)); + }else if(reqFileName.indexOf("[MMDD+1]") > -1) { + String tmpbaseDate = DatetimeUtil.addDays(baseDate, 1); + reqFileName = reqFileName.replace("[MMDD+1]", tmpbaseDate.substring(4)); + } + if(logger.isDebugEnabled()) + logger.debug("trans reqFileName:"+reqFileName); + } + }catch(Exception ex) { + // 파일프로퍼티 설정 없음 + } + + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "30"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "30"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + boolean selectDate = true; + try { + if("Y".equals(pmanager.getProperties(propName).getProperty(BASE_DATE_OVER_YN, "N"))) { + selectDate = false; + } + }catch(Exception e) { + } + + FTPFileObject[] list = FTPUtil.listFilesJSCH(ipaddress, port, userid, passwd, remotePath, true, batchDoc.getLogger(),ftpgb); + + if(list == null) {// 파일 경로가 없는경우 20231025 + if(logger.isDebugEnabled()) + logger.debug("[FTP00]remotePath:"+remotePath +" path is none"); + return; + } + setLastActivity(); + + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + if(logger.isDebugEnabled()) + logger.debug("[FTP00] ■ baseDate[" + baseDate + "] bizCode[" + bizCode + "]"); + + for (int inx = 0; inx < list.length; inx++) { + FTPFileObject file = list[inx]; + + if(!file.isFile()) + continue; + + String fileName = file.getName().trim(); + long fileSize = file.getSize(); + + if(isFileNameSet && fileName.contains(reqFileName)){ + if(logger.isDebugEnabled()) + logger.debug("[FTP00]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] reqFileName[" + reqFileName +"]"); + fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType + , connTimeout, setTimeout, bandWidth); + }else if (!isFileNameSet && fileName.contains(bizCode)) { + if(logger.isDebugEnabled()) + logger.debug("[FTP00]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] bizCode[" + bizCode +"]"); + + Matcher matcher = Pattern.compile("(20[0-9]{6})").matcher(fileName.trim()); + if (matcher.find()) { + + String value = matcher.group(1).trim(); + int iday = Integer.parseInt(value); + int bday = Integer.parseInt(baseDate); + if (iday >= bday && !selectDate) { //스케줄러를 통한 파일 수신, 오늘 날짜 이상 + if(logger.isDebugEnabled()) + logger.debug("[FTP00]ALL OVER DATE OK-fileName[" + fileName + "]"); + fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType + , connTimeout, setTimeout, bandWidth); + + } else if (iday == bday && selectDate) { //파일날짜 선택하여 파일 수신, 해당 날짜만 수신 + if(logger.isDebugEnabled()) + logger.debug("[FTP00]SELECT_DATE-fileName[" + fileName + "]"); + fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType + , connTimeout, setTimeout, bandWidth); + } + }else{ + if(logger.isDebugEnabled()) + logger.debug("[FTP00]No SELECT_DATE-fileName[" + fileName + "]"); + + try { + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode() + , batchDoc.getBatchMsg().getHeader().getInstitutionCode()); + int bizCodeStartIndex = organInfo.getBizCdStartIdx(); + int bizCodeEndIndex = organInfo.getBizCdEndIdx(); + + if (fileName.length() > bizCodeEndIndex && bizCode.equals(fileName.substring(bizCodeStartIndex, bizCodeEndIndex))){ + fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType + , connTimeout, setTimeout, bandWidth); + } + }catch(Exception e) { + // + } + + } + } + } + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode(ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error(errMsg, ex); + throw ex; + } finally { + this.disconnect(); + } + if(logger.isInfoEnabled()) + logger.info("[FTP00] ■ VAN사 → FEP 파일 수신 완료."); + } + + private void fileDownProcess(BatchDoc batchDoc, String fileName, long fileSize, String ipaddress, int port, + String userid, String passwd, String remotePath, String sftpmode, String ftpFileType + , int connTimeout, int setTimeout, int bandWidth) throws Exception { + FileOutputStream fos = null; + + batchDoc.getBatchMsg().getHeader().setFileName(fileName); + batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + + if(logger.isDebugEnabled()) + logger.debug("@@@@@@@@@batchDoc.getBatchMsg().getHeader().getJobCode()[" + + batchDoc.getBatchMsg().getHeader().getJobCode() + "]"); + + String recvFile = ""; + File rcvRealFile = null; + File rcvChkFile = null; + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis()); + LogUtil.setLogFileStart(batchDoc); + try { + + if(logger.isDebugEnabled()) + logger.debug("@@@@@@@@" + this.getClass().getName() + ".fileName[" + fileName + "]"); + + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath , fileName, batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), sftpmode, ftpFileType); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + fileName; + rcvRealFile = new File(recvFile); + rcvChkFile = new File(StringUtil.realToRootDir(recvFile)); + } catch (Exception e) { + setLastActivity(); + logger.error(e.getMessage(), e); + throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage()); + } finally { + //fos.close(); + } + try { + File rcvArchFile = new File(StringUtil.realToArchDir(recvFile)); + + if(logger.isDebugEnabled()) + logger.debug("@@@@@@@@@rcvArchFile[" + rcvArchFile.getName() + "]"); + batchDoc.getBatchMsg().getHeader().getJobCode(); + + if (rcvRealFile.exists()) { + if(logger.isDebugEnabled()) + logger.debug("@@@@@@@@@rcvRealFile[" + rcvRealFile.getName() + "]"); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + } else { + throw new Exception("파일수신에 실패하였습니다."); + } + + } catch (Exception e) { + throw e; + + } + // File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis()); + LogUtil.setLogFileEnd(batchDoc); + } + + // 정상처리 20241025 + private void fileDownEndProcess(BatchDoc batchDoc, String fileName, String errMsg) throws Exception { + FileOutputStream fos = null; + + batchDoc.getBatchMsg().getHeader().setFileName(fileName); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + logger.debug("@@@@@@@@@fileDownEndProcess batchDoc.getBatchMsg().getHeader().getFileName()["+ fileName + "]"); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis()); + + LogUtil.setLogFileStart(batchDoc); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + batchDoc.getBatchMsg().getHeader().getJobCode(); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + // File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis()); + LogUtil.setLogFileEnd(batchDoc); + } + + @Override + public void shutdown() { + // TODO Auto-generated method stub + + } + + @Override + public Socket getCurrentSocket() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean connect() { + // TODO Auto-generated method stub + return false; + } + + @Override + public ConfigurationContext getContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setControl(Object control) { + // TODO Auto-generated method stub + + } + + @Override + public void notifyMessage() { + // TODO Auto-generated method stub + + } + + @Override + public boolean idle(long timeout) { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getCurrentState() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean isConnected() throws IOException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isActive() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void checkActivity() { + // TODO Auto-generated method stub + + } + + @Override + public String getRemoteIPAddress() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setLastActivity() { + // TODO Auto-generated method stub + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public long getLastActivity() { + // TODO Auto-generated method stub + return 0; + } +} diff --git a/src/com/eactive/eai/adapter/ftp/FTP01.java b/src/com/eactive/eai/adapter/ftp/FTP01.java new file mode 100644 index 0000000..6e67207 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTP01.java @@ -0,0 +1,274 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.Properties; + +import org.apache.commons.net.ftp.FTP; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; + +//KIS 제공 자료 정보계 ( FTP ) +//IP : 203.234.219.30 PORT : 21 +//ID : kjbank PWD: kjbank0409 +//파일명 kjb_YYYYMMDD[_HH].tar.gz + +/** + * 데이터 수신에 시간이 오래 걸리는 경우에 KeepAliveTimeout을 설정하여 NOOP 를 Control Connection으로 + * 전송하도록 TCP 연결을 유지하도록 수정 + * + */ +public class FTP01 extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String REQ_FILE_NAME = "req.file.name"; + private static final String POST_FIX = "post.fix"; + private static final String FLAG_FILE_NAME = "flag.file.name"; + + + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTP01] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + // 기관 프라퍼티에서 keepAliveTimeout 읽음 + // 설정이 없는 경우 0으로 설정하여 disable + String instPropName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + int keepAliveTimeout = 0; + int keepAliveReplyTimeout = 1; + try { + Properties instProperties = PropManager.getInstance().getProperties(instPropName); + keepAliveTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.timeout", "0")); + keepAliveReplyTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.reply.timeout", "1")); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + } + logger.info("keepAliveTimeout = {} seconds", keepAliveTimeout); + logger.info("keepAliveReplyTimeout = {} seconds", keepAliveReplyTimeout); + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + String port = batchDoc.getBatchMsg().getHeader().getPort(); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + if (ftpClient == null || !ftpClient.isConnected()) this.connect(ipaddress, Integer.parseInt(port) ); + ftpClient.login(userid, passwd); + ftpClient.enterLocalPassiveMode(); + ftpClient.setFileType(FTP.BINARY_FILE_TYPE); + setLastActivity(); + + logger.debug( "[FTP01]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + String postFix = ""; + String flagFileName = ""; + reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode(); + try{ + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getBizCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + postFix = pmanager.getProperties(propName).getProperty(POST_FIX); + if ( postFix == null ){ + postFix = ""; + } + flagFileName = pmanager.getProperties(propName).getProperty(FLAG_FILE_NAME); + reqFileName = pmanager.getProperties(propName).getProperty(REQ_FILE_NAME); + }catch ( Exception e){} + + reqFileName = reqFileName + "_" + baseDate + postFix.trim() + ".tar.gz"; + + ftpClient.setDataTimeout(600*1000); + ftpClient.setConnectTimeout(300); + // Keep Alive 설정 + ftpClient.setControlKeepAliveTimeout(keepAliveTimeout); + ftpClient.setControlKeepAliveReplyTimeout(keepAliveReplyTimeout * 1000); + + String remoteDir = "pub/" + baseDate + postFix.trim(); + logger.debug("[FTP01] ■ VAN사 remoteDir["+remoteDir+"]"); + if ( !ftpClient.changeWorkingDirectory(remoteDir)){ + logger.info("[FTP01] ■ VAN사 → FEP 수신 파일 없음.["+remoteDir+"]"); + return; + } + + FTPFile[] files = ftpClient.listFiles(); + setLastActivity(); + + if ( !flagFileName.equals("")){ + boolean find = false; + for (int inx = 0; inx < files.length; inx++) { + if ( files[inx].getName().equals(flagFileName) ){ + find = true; + break; + } + } + if ( !find ){ + logger.info("[FTP01] ■ VAN사 → FEP 수신 지표 파일이 없음.["+flagFileName+"]"); + return; + } + } + + for (int inx = 0; inx < files.length; inx++) { + + if ( !files[inx].isFile() || !files[inx].getName().equals(reqFileName) ) continue; + FileOutputStream fos = null; + + batchDoc.getBatchMsg().getHeader().setFileName(reqFileName); + batchDoc.getBatchMsg().getHeader().setFileSize(files[inx].getSize()); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName; + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + try { + fos = new FileOutputStream( rcvRealFile ); + ftpClient.retrieveFile(reqFileName, fos); + setLastActivity(); + } catch (Exception e) { + setLastActivity(); + logger.error(e.getMessage(), e); + throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage()); + } finally { + fos.close(); + } + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + + } catch (Exception e) { + throw e; + + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + break; + } + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPCC] ■ VAN사 → FEP 파일 수신 완료."); + } + + + @Override + public void shutdown() { + disconnect(); + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTP03.java b/src/com/eactive/eai/adapter/ftp/FTP03.java new file mode 100644 index 0000000..a3b8319 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTP03.java @@ -0,0 +1,243 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.Properties; + +import org.apache.commons.net.ftp.FTP; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; + +//KIS 제공 자료 정보계 ( FTP ) +//IP : 203.234.219.30 PORT : 21 +//ID : kjbank PWD: kjbank0409 +//파일명 kjfb_YYYYMMDD.tar.gz +//매월 첫주 화요일에 수신 + +/** + * 데이터 수신에 시간이 오래 걸리는 경우에 KeepAliveTimeout을 설정하여 NOOP 를 Control Connection으로 + * 전송하도록 TCP 연결을 유지하도록 수정 + * + */ + +public class FTP03 extends Transfer implements SocketService{ + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTP03] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + // 기관 프라퍼티에서 keepAliveTimeout 읽음 + // 설정이 없는 경우 0으로 설정하여 disable + String instPropName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + int keepAliveTimeout = 0; + int keepAliveReplyTimeout = 1; + try { + Properties instProperties = PropManager.getInstance().getProperties(instPropName); + keepAliveTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.timeout", "0")); + keepAliveReplyTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.reply.timeout", "1")); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + } + logger.info("keepAliveTimeout = {} seconds", keepAliveTimeout); + logger.info("keepAliveReplyTimeout = {} seconds", keepAliveReplyTimeout); + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + String port = batchDoc.getBatchMsg().getHeader().getPort(); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + if (ftpClient == null || !ftpClient.isConnected()) this.connect(ipaddress, Integer.parseInt(port) ); + ftpClient.login(userid, passwd); + ftpClient.enterLocalPassiveMode(); + ftpClient.setFileType(FTP.BINARY_FILE_TYPE); + setLastActivity(); + + logger.debug( "[FTPC3]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + + reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate + ".tar.gz"; + + ftpClient.setDataTimeout(600*1000); + ftpClient.setConnectTimeout(300); + // Keep Alive 설정 + ftpClient.setControlKeepAliveTimeout(keepAliveTimeout); + ftpClient.setControlKeepAliveReplyTimeout(keepAliveReplyTimeout * 1000); + + String remoteDir = "pub/" + baseDate; + logger.debug( "[FTPC3]remoteDir:" + remoteDir); + logger.debug( "[FTPC3]reqFileName:" + reqFileName); + + if ( !ftpClient.changeWorkingDirectory(remoteDir)){ + logger.info("[FTP03] ■ VAN사 → FEP 수신 파일 없음.["+remoteDir+"]"); + return; + } + + FTPFile[] files = ftpClient.listFiles(); + setLastActivity(); + + for (int inx = 0; inx < files.length; inx++) { + + if ( !files[inx].isFile() || !files[inx].getName().equals(reqFileName) ) continue; + FileOutputStream fos = null; + + batchDoc.getBatchMsg().getHeader().setFileName(reqFileName); + batchDoc.getBatchMsg().getHeader().setFileSize(files[inx].getSize()); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName; + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + try { + fos = new FileOutputStream( rcvRealFile ); + ftpClient.retrieveFile(reqFileName, fos); + setLastActivity(); + } catch (Exception e) { + setLastActivity(); + logger.error(e.getMessage(), e); + throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage()); + } finally { + fos.close(); + } + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + + } catch (Exception e) { + throw e; + + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + break; + } + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPCC] ■ VAN사 → FEP 파일 수신 완료."); + } + + + @Override + public void shutdown() { + disconnect(); + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPBG.java b/src/com/eactive/eai/adapter/ftp/FTPBG.java new file mode 100644 index 0000000..0d58a6c --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPBG.java @@ -0,0 +1,213 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; + +public class FTPBG extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String SEND_SHELL = "send.shell"; + private static final String RECV_SHELL = "recv.shell"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPSH] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //Shell 명령어를 Runtime 으로 실행 + try { + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + + PropManager pmanager = PropManager.getInstance(); + + String shellCommand = pmanager.getProperties(propName).getProperty(SEND_SHELL); + if ( shellCommand == null ){ + throw new Exception("해당 기관에 송신 스크립트가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_SHELL); + } + String[] command = new String[4]; + command[0] = shellCommand; + command[1] = batchDoc.getBatchMsg().getHeader().getFilePath(); + command[2] = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + command[3] = batchDoc.getBatchMsg().getHeader().getFileName(); + + setFileHeaderAndTrailer(batchDoc, new File(batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName())); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + runSystemScript( command ); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + this.disconnect(); + } + logger.info("[FTPSH] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPSH] ■ 대외기관→FEP 파일 수신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + String fileName = batchDoc.getBatchMsg().getHeader().getBizCode(); + //Shell 명령어를 Runtime 으로 실행 + try { + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + + PropManager pmanager = PropManager.getInstance(); + + String shellCommand = pmanager.getProperties(propName).getProperty(RECV_SHELL); + if ( shellCommand == null ){ + throw new Exception("해당 기관에 수신 스크립트가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_SHELL); + } + + String[] command = new String[3]; + command[0] = shellCommand; + command[1] = batchDoc.getBatchMsg().getHeader().getFilePath(); + command[2] = fileName; + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + runSystemScript( command ); + File recvDir = new File(batchDoc.getBatchMsg().getHeader().getFilePath()); + File[] recvFiles = recvDir.listFiles(); + for( int inx = 0; inx < recvFiles.length; inx++){ + File recvFile = recvFiles[inx]; + if ( recvFile.getName().startsWith(fileName)){ + File rcvRootFile = new File( StringUtil.realToRootDir(batchDoc.getBatchMsg().getHeader().getFilePath()) + "/" + recvFile.getName() ); + File rcvArchFile = new File( StringUtil.realToArchDir(batchDoc.getBatchMsg().getHeader().getFilePath()) + "/" + recvFile.getName()); + batchDoc.getBatchMsg().getHeader().setFileName(recvFile.getName()); + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getHeader().setFileSize(recvFile.length()); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + setFileHeaderAndTrailer(batchDoc, recvFile); + recvFile.renameTo(rcvArchFile); + rcvRootFile.createNewFile(); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } + } + + } catch(Exception ex) { + String noFileMessage = fileName + " NOT EXIST"; + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + if ( ex.getMessage().indexOf(noFileMessage) < 0 ){ + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + this.disconnect(); + } + logger.info("[FTPSH] ■ 대외기관→FEP 파일 수신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPCC.java b/src/com/eactive/eai/adapter/ftp/FTPCC.java new file mode 100644 index 0000000..a213d61 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPCC.java @@ -0,0 +1,203 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.net.ftp.FTP; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; + +// 신용회복 위원회 파일 수신 ( FTP ) +// IP : 114.108.166.14 PORT : 21 PASSIVE 방식 +// ID : kjbk_ccrs PWD: ccrskjbk!@# +// 파일명: SNTFTP.${YYYYMMDD}.tar.gz + +public class FTPCC extends Transfer implements SocketService{ + + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPCC] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + String port = batchDoc.getBatchMsg().getHeader().getPort(); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + if (ftpClient == null || !ftpClient.isConnected()) this.connect(ipaddress, Integer.parseInt(port) ); + ftpClient.login(userid, passwd); + ftpClient.enterLocalPassiveMode(); + ftpClient.setFileType(FTP.BINARY_FILE_TYPE); + setLastActivity(); + + logger.debug( "[FTPCC]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + + reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "." + baseDate + ".tar.gz"; + + ftpClient.setDataTimeout(600*1000); + ftpClient.setConnectTimeout(300); + + FTPFile[] files = ftpClient.listFiles(); + setLastActivity(); + + for (int inx = 0; inx < files.length; inx++) { + + if ( !files[inx].isFile() || !files[inx].getName().equals(reqFileName) ) continue; + FileOutputStream fos = null; + + batchDoc.getBatchMsg().getHeader().setFileName(reqFileName); + batchDoc.getBatchMsg().getHeader().setFileSize(files[inx].getSize()); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName; + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + try { + fos = new FileOutputStream( rcvRealFile ); + ftpClient.retrieveFile(reqFileName, fos); + setLastActivity(); + } catch (Exception e) { + setLastActivity(); + logger.error(e.getMessage(), e); + throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage()); + } finally { + fos.close(); + } + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + + } catch (Exception e) { + throw e; + + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + break; + } + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPCC] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + disconnect(); + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPCH.java b/src/com/eactive/eai/adapter/ftp/FTPCH.java new file mode 100644 index 0000000..cd8da1e --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPCH.java @@ -0,0 +1,357 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; +import java.nio.file.Files; + +import org.apache.commons.lang3.StringUtils; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + + +/** + * chk 파일(check.file.suffix)이 있는 파일 송수신 + * + */ +public class FTPCH extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + /** 송신 폴더 */ + private static final String SEND_REMOTE_PATH = "send.remote.path"; + /** 수신 폴더 */ + private static final String RECV_REMOTE_PATH = "recv.remote.path"; + /** 체크 파일 확장자 */ + private static final String CHECK_FILE_SUFFIX = "check.file.suffix"; + /** 큐에서 가져오는 최대 갯수 */ + private static final String MAX_ITERATION = "max.iteration"; + + public final static String PHASECODE_NORMAL_END = "END"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + internalSendFile(batchDoc); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + int iteration = 100; + + String maxIteration = pmanager.getProperties(propName).getProperty(MAX_ITERATION); + if (maxIteration != null) { + try { + iteration = Integer.parseInt(maxIteration); + } catch(Exception e) { + logger.error(maxIteration, e); + } + } + + // 만일의 경우 대비해서 100번만 돈다. + for (int i = 0; i < iteration; i++) { + // Queue에 있는 지 확인한다. + BatchDoc newDoc = checkMoreFile(batchDoc); + if (newDoc == null) { + break; + } + String uuid = newDoc.getBatchMsg().getHeader().getUUID(); + String subUuid = newDoc.getBatchMsg().getBody().getSubUUID(); + try { + internalSendFile(newDoc); + + newDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + setDefaultEndStage(newDoc); + // FlowController Log + LogUtil.setLog(newDoc); + // master 정보 + LogUtil.updateLogMaster(newDoc); + // master 작업상태 정보: 정상 종료 + LogUtil.setEndLog(newDoc); + } finally { + // 진행중에서 삭제. 반드시 삭제되어야 함 + SchedulerMessageManager.getInstance().deleteJobFromProcessing(uuid, subUuid); + } + } + } + + /** + * 실제로 파일을 전송한다. + * @param batchDoc 전송할 배치 작업 + */ + private void internalSendFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPCH] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + String checkFileName = null; + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + String checkFileSuffix = pmanager.getProperties(propName).getProperty(CHECK_FILE_SUFFIX); + if ( checkFileSuffix == null ){ + throw new Exception("체크 파일 접미어가 지정되어 있지 않습니다. -propName:" + propName + "," + CHECK_FILE_SUFFIX); + } + + String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName(); + setFileHeaderAndTrailer(batchDoc, new File(sendFileName)); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + // check 파일 이름 + checkFileName = sendFileName + checkFileSuffix; + + // 체크 파일을 지우기 이전에 생성한 체크 파일 삭제 + Files.deleteIfExists(new File(checkFileName).toPath()); + + // check 파일 생성 + if (new File(checkFileName).createNewFile() == false) { + throw new Exception("체크 파일을 생성하지 못했습니다. checkFileName = " + checkFileName); + }; + String remoteCheckfileName = remoteFileName + checkFileSuffix; + FTPUtil.store(ipaddress, port, userid, passwd, remoteCheckfileName, checkFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + this.disconnect(); + // 체크 파일 삭제 + // 재전송할 때 오류 발생 방지 + if (checkFileName != null) { + Files.deleteIfExists(new File(checkFileName).toPath()); + } + } + logger.info("[FTPCHK] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + } + + /** + * 같은 업무, 기관 코드의 작업이 큐에 있는지 확인한다. + * + * @param batchDoc + * @return 큐에서 가져온 배치 잡 + */ + private BatchDoc checkMoreFile(BatchDoc batchDoc) { + BatchDoc newDoc = null; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return null; + } + newDoc = EAIBatchMsgManager.createBatchMsg(true); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandle(info); + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(newDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER); + + //BatchMsgDoc 값 설정 + newDoc.getBatchMsg().getHeader().setUUID(info.getUUID()); + newDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID()); + newDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode()); + newDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName()); + newDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType()); + newDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode()); + newDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName()); + newDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + newDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + newDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + newDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + newDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + newDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + newDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + newDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + newDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + newDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + newDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + newDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + newDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + newDoc.getBatchMsg().getHeader().setUserID(batchDoc.getBatchMsg().getHeader().getUserID()); + newDoc.getBatchMsg().getHeader().setUserPassword(batchDoc.getBatchMsg().getHeader().getUserPassword()); + newDoc.getBatchMsg().getHeader().setPort(batchDoc.getBatchMsg().getHeader().getPort()); + newDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode()); + newDoc.getBatchMsg().getHeader().setRequestResponse(info.getRqstRspnsDstcd()); + newDoc.getBatchMsg().getHeader().setRemoteIP(batchDoc.getBatchMsg().getHeader().getRemoteIP()); + + // 다음 파일의 체크 파일 가져오기 + if (info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) + || info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND)) { + String hdrInfoName = info.getHdrInfoName(); + newDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + newDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + newDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + + String dirPath = newDoc.getBatchMsg().getHeader().getFilePath(); + String renamedFileName = newDoc.getBatchMsg().getHeader().getRenamedFileName(); + File file = new File(dirPath + File.separatorChar + renamedFileName); + if (!file.exists()) { + throw new Exception(); + } + long fileLen = file.length(); + + newDoc.getBatchMsg().getHeader().setFileSize(fileLen); + } + } catch ( Exception e){ + logger.error(newDoc == null ? "null" : newDoc.toString(), e); + return null; + } + + return newDoc; + } + + /** + * FlowController END를 위한 값으로 설정한다. + * @param batchDoc 설정 값을 변경할 배치 작업 + */ + private void setDefaultEndStage(BatchDoc batchDoc) { + batchDoc.getBatchMsg().getBody().setFlowPhaseCode(PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getBody().setPhaseType(PHASECODE_NORMAL_END); + //Phase 쪽 단계정보 설정 + batchDoc.getBatchMsg().getPhaseinfo().setRuleCode ("FTPCH"); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseCode (PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseType (PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getPhaseinfo().setFlowClassName ("com.eactive.eai.batch.job.jobModule.Component.END"); + batchDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (0); + batchDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (""); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq ("1"); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue (""); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPET.java b/src/com/eactive/eai/adapter/ftp/FTPET.java new file mode 100644 index 0000000..6842f1a --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPET.java @@ -0,0 +1,319 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +// 이제너두 +// 파일명 +// 송신: +// KJ13_YYYYMMDD.in +// KJ15_YYYYMMDD.in +// 수신: +// KJ12_YYYYMMDD.out +// KJ14_YYYYMMDD.out +public class FTPET extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + /** 원격지 경로 */ + private static final String REMOTE_PATH = "remote.path"; + /** 파일 수신시 접미어 */ + private static final String POSTFIX = "post.fix"; + /** sftp 사용 여부 */ + private static final String SFTP_YN = "sftp"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPET] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + String sftpYn = pmanager.getProperties(propName).getProperty(SFTP_YN); + boolean isSftp = "Y".equalsIgnoreCase(sftpYn); + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + //String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName(); + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + setFileHeaderAndTrailer(batchDoc, new File(sendFileName)); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + //FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, isSftp, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName, + connTimeout, setTimeout, isSftp, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + logger.error( errMsg, ex ); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + throw ex; + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + this.disconnect(); + } + logger.info("[FTPET] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPET] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + String jobName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getBizCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + String sftpYn = pmanager.getProperties(propName).getProperty(SFTP_YN); + boolean isSftp = "Y".equalsIgnoreCase(sftpYn); + String postfix = null; + try{ + postfix = pmanager.getProperties(jobName).getProperty(POSTFIX); + logger.debug( "[FTPET]postfix: {}", postfix); + }catch( Exception e ){} + + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + logger.debug( "[FTPET]FileName: {}", batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + + reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate; + + if ( postfix != null && !postfix.equals("")){ + reqFileName = reqFileName + postfix; + } + logger.debug( "[FTPET]reqFileName:" + reqFileName ); + + + try { + FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, isSftp, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + for ( int inx = 0 ; inx < list.length; inx++){ + FTPFile file = list[inx]; + if ( file.getName().equals(reqFileName) ){ + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(file.getName()); + LogUtil.setLogFileStart(batchDoc); + //FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), isSftp, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, isSftp, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + //batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName(); + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + //setFileHeaderAndTrailer(batchDoc, rcvRealFile); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + } + } + } + }catch ( Exception e ){ + if ( !e.getMessage().contains("No such file")) + throw e; + } + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( errMsg, ex ); + String errorMessage = ex.getMessage(); + if (StringUtils.isEmpty(errorMessage)) { + errorMessage = "No Exception ErrorMessage"; + } + LogUtil.setErrorLog(batchDoc, errorMessage); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPET] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPFA.java b/src/com/eactive/eai/adapter/ftp/FTPFA.java new file mode 100644 index 0000000..37f7502 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPFA.java @@ -0,0 +1,270 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +/** + * 금용결제원 SFTP + * 빅데이터 기반의 금융의심거래정보 분석 공유 서비스[FAS] + * + * 이름은 KS(Kftc Sftp)가 사용 중이라 FAS에 따옴 + * + * 거래일자 확인: 전일자 YYYYMMDD 파일 + * 파일명 : FS0001 + * + * 오류 + * 1. 거래일자 파일이 없는 경우에 오류 발생 + */ +public class FTPFA extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + /** 원격지 경로 */ + private static final String REMOTE_PATH = "remote.path"; + /** 파일 수신시 접미어 */ + private static final String POSTFIX = "post.fix"; + /** sftp 사용 여부 */ + private static final String SFTP_YN = "sftp"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPFA] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + String jobName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getBizCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + String sftpYn = pmanager.getProperties(propName).getProperty(SFTP_YN); + boolean isSftp = "Y".equalsIgnoreCase(sftpYn); + String postfix = null; + try{ + postfix = pmanager.getProperties(jobName).getProperty(POSTFIX); + if (logger.isDebugEnabled()) { + logger.debug( "[FTPFA]postfix:" + postfix); + } + }catch( Exception e ){} + + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + + if (logger.isDebugEnabled()) { + logger.debug( "[FTPFA]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + } + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + } + } + + // 전일자 + baseDate = DatetimeUtil.getDayAddedDate(baseDate, -1); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + + reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode(); + + if ( postfix != null && !postfix.equals("")) { + reqFileName = reqFileName + postfix; + } + logger.debug( "[FTPFA]reqFileName:" + reqFileName ); + + try { + FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, isSftp, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + // 전일자 파일 확인 + boolean dateFileExist = false; + FTPFile remoteFile = null; + for (FTPFile file : list){ + if (file.getName().equals(baseDate)) { + dateFileExist = true; + } + if (file.getName().equals(reqFileName)) { + remoteFile = file; + } + } + + if (dateFileExist == false) { + throw new Exception("거래일자 파일(" + baseDate + ")이 없습니다."); + } + + if (remoteFile != null) { + batchDoc.getBatchMsg().getHeader().setFileSize(remoteFile.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(remoteFile.getName()); + LogUtil.setLogFileStart(batchDoc); + //FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + remoteFile.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), isSftp, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFile.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, isSftp, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + //batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + remoteFile.getName(); + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + //setFileHeaderAndTrailer(batchDoc, rcvRealFile); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + } + } + }catch ( Exception e ){ + if ( !e.getMessage().contains("No such file")) + throw e; + } + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPFA] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPFS.java b/src/com/eactive/eai/adapter/ftp/FTPFS.java new file mode 100644 index 0000000..ce82a52 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPFS.java @@ -0,0 +1,535 @@ +package com.eactive.eai.adapter.ftp; + +import static com.eactive.eai.adapter.ftp.SFTPConstants.RECV_REMOTE_PATH; +import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_REMOTE_PATH; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; +import java.util.ArrayList; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.logger.LogManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + + +/** + * 금용결제원 SFTP + * 빅데이터 기반의 금융의심거래정보 분석 공유 서비스[FAS] + * + * 이름은 KS(Kftc Sftp)가 사용 중이라 FAS에 따옴 + * + * 파일명 : FS0001 + * + */ + +public class FTPFS extends Transfer implements SocketService { + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + + // 파일경로 관련 프로퍼티 + private static final String REMOTE_PATH = "remote.path"; + private static final String REMOTE_PATH_BASEDATE_YN = "remote.path.basedate.yn"; + + /** 임시 파일 확장자 .FILEPART. 해당 파일 무시 */ + private static final String REMOTE_FILE_WORKING_POSTFIX = "remote.file.working.postfix"; + // 파일관련 프로퍼티 + private static final String REMOTE_FILE_BASEDATE_DELIM = "remote.file.basedate.delim"; + /** 현재일 기준 일자 변경: -1 인경우 전일자 */ + private static final String REMOTE_FILE_BASEDATE_ADDDAYS = "remote.file.basedate.adddays"; + private static final String REMOTE_FILE_BASEDATE_YN = "remote.file.basedate.yn"; + private static final String REMOTE_FILE_BASETIME_DELIM = "remote.file.basetime.delim"; + private static final String REMOTE_FILE_BASETIME_YN = "remote.file.basetime.yn"; + private static final String REMOTE_FILE_BASETIME = "remote.file.basetime"; + + /** 인증 방법 1 = id, 2 = key 방식 */ + private static final String AUTH_TYPE = "sftp.auth.type"; + + @Override + public void sendFile(BatchDoc batchDoc) throws Exception { + // TODO Auto-generated method stub + logger.info("[FTPFS] ■ 대외기관→FEP 파일 송신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + if ( remotePath == null ) { + remotePath = ""; + } + String sendRemotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH); + if ( sendRemotePath != null && sendRemotePath.trim().length() > 0) { + remotePath = sendRemotePath; + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = "1"; // id + } + + // 업로드 서버가 일자별 경로 생성 시, 경로에 일자정보 추가. + String remotePathBasedateYn = pmanager.getProperties(propName).getProperty(REMOTE_PATH_BASEDATE_YN); + if ( remotePathBasedateYn == null || !remotePathBasedateYn.equalsIgnoreCase("y") ) { + remotePathBasedateYn = "n"; + } + else { + remotePathBasedateYn = "y"; + } + + String baseDate = DatetimeUtil.getCurrentDate(); + if ( remotePathBasedateYn == "y" ) + remotePath = remotePath + baseDate + "/"; + + // 실제 파일이름 + String orgFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + // FEP 에서 Rename(송신Real->송신Arch)한 파일이름 + String sendFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + logger.debug( "[FTPFS]sendFileName:" + orgFileName); + logger.debug( "[FTPFS]remotePath:" + remotePath); + + //File 시작시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + String sendFilePath = batchDoc.getBatchMsg().getHeader().getFilePath(); + + try { + FTPUtil.store(ipaddress, port, userid, passwd, remotePath + orgFileName, sendFilePath + File.separator + sendFileName, true, batchDoc.getLogger(), authType); + + } catch (Exception e) { + logger.error("[FTPFS]파일송신에 실패하였습니다.", e); + throw e; + } + + //File 종료시간 설정 + setLastActivity(); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + // SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출. + this.disconnect(); + } + + logger.info("[FTPFS] ■ FEP → VAN사 파일 송신 완료."); + + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPFS] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + + try { + + int bizCodeStartIndex = 0; // 거래시작인덱스 + int bizCodeEndIndex = 0; // 거래종료인덱스 + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i 0) { + remotePath = recvRemotePath; + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + // 1. 파일 경로에 일자 디렉토리 포함 여부 확인 + String remotePathBasedateYn = pmanager.getProperties(propName).getProperty(REMOTE_PATH_BASEDATE_YN); + if ( remotePathBasedateYn == null || !remotePathBasedateYn.equalsIgnoreCase("y") ) { + remotePathBasedateYn = "n"; + } + else { + remotePathBasedateYn = "y"; + } + + // 2. 파일 이름에 일자 포함 여부 확인 + String remoteFileBasedateYn = pmanager.getProperties(propName).getProperty(REMOTE_FILE_BASEDATE_YN); + if ( remoteFileBasedateYn == null || !remoteFileBasedateYn.equalsIgnoreCase("y") ) { + remoteFileBasedateYn = "n"; + } + else { + remoteFileBasedateYn = "y"; + } + + // 2-1. 2 에 해당 시 구분자 + String remoteFileBasedateDelim = pmanager.getProperties(propName).getProperty(REMOTE_FILE_BASEDATE_DELIM); + if ( remoteFileBasedateDelim == null ) + remoteFileBasedateDelim = ""; + + // 3. 임시파일 확장자 + String remoteFileWorkingPostfix = pmanager.getProperties(propName).getProperty(REMOTE_FILE_WORKING_POSTFIX); + if ( remoteFileWorkingPostfix == null ) + remoteFileWorkingPostfix = ""; + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + // 특정일자 파일을 수기로 수신요청 시, 해당 일자의 경로 설정 + logger.debug( "[FTPFS]recvFileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + boolean isManualRcv = false; + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + isManualRcv = true; + }else{ + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + }else{ + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + + // 다운로드 서버가 일자별 경로 생성 시, 경로에 일자정보 추가. + if ("y".equalsIgnoreCase(remotePathBasedateYn)) + remotePath = remotePath + baseDate; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + FTPFile[] list = new FTPFile[0]; + try { + list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(), authType); + } catch ( Exception e ){ + if ( !e.getMessage().contains("No such file") ) + throw e; + } + for ( int inx = 0 ; inx < list.length; inx++ ){ + FTPFile file = list[inx]; + String remoteFileName = file.getName(); + try { + + if (remoteFileWorkingPostfix.length() > 0 && remoteFileName.endsWith(remoteFileWorkingPostfix)) { + logger.debug( "[FTPFS]임시파일은 무시 " + remoteFileName + ", 임시파일 확장자 = " + remoteFileWorkingPostfix); + continue; + } + + // 파일이름으로부터 등록된 파일명을 구함 + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= remoteFileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > remoteFileName.length()) bizCodeEndIndex = remoteFileName.length(); + String bizCode = remoteFileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + + // 수기요청 파일명은 아래 로직에서 기관 프로퍼티값에 따라 재설정. + if ( reqFileName != null && reqFileName.length() > 8 ) { + reqFileName = reqFileName.substring(bizCodeStartIndex, bizCodeEndIndex); + } + + // 파일 프로퍼티그룹 명 + String propJobName = PROP_GROUP_NAME_PREFIX + "{" + + processCode + + "_" + + bizCode + "}"; + + // 3. 시간대별 수신이 필요한 파일여부 확인 + String remoteFileBasetimeYn = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASETIME_YN); + if ( remoteFileBasetimeYn == null || !remoteFileBasetimeYn.equalsIgnoreCase("y") ) { + remoteFileBasetimeYn = "n"; + } + else { + remoteFileBasetimeYn = "y"; + } + + // 3-1. 3 에 해당 시 구분자 + String remoteFileBasetimeDelim = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASETIME_DELIM); + if ( remoteFileBasetimeDelim == null ) + remoteFileBasetimeDelim = ""; + + // 3-2. 3 에 해당 시 기준시 추출 + String baseTime = ""; + if ("y".equalsIgnoreCase(remoteFileBasetimeYn)) { + baseTime = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASETIME); + + // 기준시 설정이 DEFAULT(99)일 경우 현재 시간(24HH)으로 설정 + if ( baseTime.equals("99") ) { + baseTime = DatetimeUtil.getTimeString().substring(0,2); + } + } + + // 파일이름에 날짜를 포함하는 경우, 특정일자 파일을 수신요청 시 요청일자의 파일명 설정 + if ("y".equalsIgnoreCase(remoteFileBasedateYn)) { + // 전일자 등 날짜 추가 + String addDays = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASEDATE_ADDDAYS, "0"); + String tempBaseDate = baseDate; + if (!StringUtils.equals(addDays, "0")) { + try { + int days = Integer.parseInt(addDays); + tempBaseDate = DatetimeUtil.addDays(tempBaseDate, days); + } catch (Exception e) { + // ignore + logger.error(e.getMessage()); + } + } + reqFileName = reqFileName + remoteFileBasedateDelim + tempBaseDate; + } + + logger.debug( "[FTPFS]reqFileName: {}", reqFileName ); + logger.debug( "[FTPFS]remotePath: {}", remotePath); + logger.debug( "[FTPFS]remoteFileName: {}", remoteFileName); + + boolean balreadyRcv = false; + // 수기요청이 아닐때, + if ( isManualRcv == false ) { + String compareFileName = bizCode + reqFileName; + // 특정시점(24HH)수신 파일인 경우, 자동요청시점과의 일치여부 검증 + if ( "y".equalsIgnoreCase(remoteFileBasetimeYn) ) { + // 시간만 비교하면 이전 일짜도 가져올 수 있기 때문에 년월일시까지 비교함 + compareFileName = bizCode + reqFileName + remoteFileBasetimeDelim + baseTime; + } + if (!remoteFileName.startsWith(compareFileName)) { + logger.debug( "[FTPFS]basetime not equal.. receive skipped : "+remoteFileName+" / "+compareFileName); + continue; + } + // 기수신여부 확인 + balreadyRcv = LogManager.getInstance().getFileLogSuccessCheck(processCode, institutionCode, bizCode, remoteFileName); + } + // 수기 요청 시, + else { + if ( remoteFileName.startsWith(reqFileName) ) { + String compareFileName = reqFileName; + // 특정시점(24HH)수신 파일인 경우, 수기요청시점과의 일치여부 검증 + if ( "y".equalsIgnoreCase(remoteFileBasetimeYn) ) { + // 시각을 붙여서 같은 시각인지 확인 + compareFileName = reqFileName + remoteFileBasetimeDelim + baseTime; + } + if (!remoteFileName.startsWith(compareFileName)) { + logger.debug( "[FTPFS]basetime not equal.. receive skipped : " + remoteFileName + "/" + compareFileName); + continue; + } + } + else { + continue; + } + } + + if ( balreadyRcv == false ) { + + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + // 반복 실행을 위해서 FileName을 원복 + String restoreFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + batchDoc.getBatchMsg().getHeader().setFileName(remoteFileName); + LogUtil.setLogFileStart(batchDoc); +// FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + remoteFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(), authType); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + remoteFileName; + File rcvRealFile = new File( recvFile ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + File rcvRootFile = new File( StringUtil.realToRootDir(recvFile) ); + rcvRootFile.createNewFile(); + } else { + throw new Exception("[FTPFS]파일수신에 실패하였습니다."); + } + //File 종료시간 설정 +// setLastActivity(); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + LogUtil.setErrorLog(batchDoc, e.getMessage()); + throw e; + } finally { + batchDoc.getBatchMsg().getHeader().setFileName(restoreFileName); + } + } + else { + logger.info( "[FTPFS] " + remoteFileName + " 은 기수신되었으므로 수신하지 않습니다."); + } + } catch (Exception e) { + logger.error(remoteFileName + " 파일 처리 중 오류, 다음 파일 처리는 계속 진행함", e); + } + } + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + // SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출. + this.disconnect(); + } + + logger.info("[FTPFS] ■ VAN사 → FEP 파일 수신 완료."); + + } + + @Override + public void shutdown() { + // TODO Auto-generated method stub + + } + + @Override + public Socket getCurrentSocket() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean connect() { + // TODO Auto-generated method stub + return false; + } + + @Override + public ConfigurationContext getContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setControl(Object control) { + // TODO Auto-generated method stub + + } + + @Override + public void notifyMessage() { + // TODO Auto-generated method stub + + } + + @Override + public boolean idle(long timeout) { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getCurrentState() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean isConnected() throws IOException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isActive() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void checkActivity() { + // TODO Auto-generated method stub + + } + + @Override + public String getRemoteIPAddress() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setLastActivity() { + // TODO Auto-generated method stub + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public long getLastActivity() { + // TODO Auto-generated method stub + return 0; + } +} diff --git a/src/com/eactive/eai/adapter/ftp/FTPKB.java b/src/com/eactive/eai/adapter/ftp/FTPKB.java new file mode 100644 index 0000000..077d19c --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPKB.java @@ -0,0 +1,555 @@ +package com.eactive.eai.adapter.ftp; + +import static com.eactive.eai.adapter.ftp.SFTPConstants.DATE_PATTERN; +import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_DAY; +import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_MONTH; +import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_PATH; +import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_YEAR; +import static com.eactive.eai.adapter.ftp.SFTPConstants.PHASECODE_NORMAL_END; +import static com.eactive.eai.adapter.ftp.SFTPConstants.RECV_REMOTE_PATH; +import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_COMPLETE_CREATE_YN; +import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_COMPLETE_FILE_EXT; +import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_MAX_ITERATION; +import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_REMOTE_PATH; +import static com.eactive.eai.adapter.ftp.SFTPConstants.SFTP_AUTH_TYPE; +import static com.eactive.eai.adapter.ftp.SFTPConstants.SFTP_AUTH_TYPE_ID; +import static com.eactive.eai.adapter.ftp.SFTPConstants.YES; +import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_AUTO_FILENAME; +import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_MANUAL_FILENAME; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; +import java.nio.file.Files; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.SFTPAdaptor; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.Session; + +/** + * 은행 연합회 SFTP 파일 송수신 + * + * 자동 수신시 해당 폴더에 있는 모든 파일을 받아온다. + * 수동 수신시 정해진 파일 이름의 파일을 받아온다. + * + */ +public class FTPKB extends Transfer implements SocketService { + String moduleName = this.getClass().getSimpleName(); + + /** 경로에 있는 날짜 패턴를 찾는 패턴 */ + static Pattern PATH_DATE_PATTERN = Pattern.compile(DATE_PATTERN); + + @Override + public void sendFile(BatchDoc batchDoc) throws Exception { + ChannelSftp channelSftp = null; + Session session = null; + try { + logger = batchDoc.getLogger(); + Properties instProperties = FtpSupport.getInstProperties(batchDoc); + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String authType = instProperties.getProperty(AUTH_TYPE, AUTH_TYPE_ID); + // 설정이 없으면 기존 처럼 한 번만 돈다. + int iteration = FtpSupport.getIntProperty(instProperties, SEND_MAX_ITERATION, 1, logger); + int connTimeout = FtpSupport.getIntProperty(instProperties, CONNECTION_TIMEOUT, 10, logger); + int setTimeout = FtpSupport.getIntProperty(instProperties, READ_TIMEOUT, 10, logger); + String bandWidthLimit = instProperties.getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + session = SFTPAdaptor.getSessionJSCH(ipaddress, port, userid, passwd, authType, connTimeout, setTimeout, logger); + + internalSendFile(session, batchDoc, bandWidth, logger); + + for (int i = 1; i < iteration; i++) { + // Queue에 있는 지 확인한다. + BatchDoc newDoc = checkMoreFile(batchDoc); + if (newDoc == null) { + break; + } + String uuid = newDoc.getBatchMsg().getHeader().getUUID(); + String subUuid = newDoc.getBatchMsg().getBody().getSubUUID(); + try { + internalSendFile(session, newDoc, bandWidth, logger); + + newDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + setDefaultEndStage(newDoc); + // FlowController Log + LogUtil.setLog(newDoc); + // master 정보 + LogUtil.updateLogMaster(newDoc); + // master 작업상태 정보: 정상 종료 + LogUtil.setEndLog(newDoc); + } finally { + // 진행중에서 삭제. 반드시 삭제되어야 함 + SchedulerMessageManager.getInstance().deleteJobFromProcessing(uuid, subUuid); + } + } + } finally { + closeJsch(logger, session, channelSftp); + } + } + /** + * 파일 하나를 전송한다. + */ + protected void internalSendFile(Session session, BatchDoc batchDoc, int bandWidthLimit, Logger logger) throws Exception { + logger.info("[{}] ■ 대외기관→FEP 파일 송신 시작...... ", moduleName); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, + batchDoc); + + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + try { + Properties instProperties = FtpSupport.getInstProperties(batchDoc); + + String remotePath = instProperties.getProperty(SEND_REMOTE_PATH); + if (remotePath == null) { + String propName = FtpSupport.getInstitutionPropertyName(batchDoc); + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH); + } + + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String sendCompleteCreateYn = instProperties.getProperty(SEND_COMPLETE_CREATE_YN, "n"); + String sendCompleteFileExt = ""; + if (sendCompleteCreateYn.equalsIgnoreCase(YES) ) { + sendCompleteFileExt = instProperties.getProperty(SEND_COMPLETE_FILE_EXT, "done"); + } + + // 실제 파일이름 + String sendFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + logger.debug("["+moduleName+"]sendFileName:{"+remoteFileName+"}"); + logger.debug("["+moduleName+"]remotePath:{"+remotePath+"}"); + + // File 시작시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + String sendFilePath = batchDoc.getBatchMsg().getHeader().getFilePath(); + + ChannelSftp channelSftp = null; + try { + channelSftp = (ChannelSftp) session.openChannel("sftp"); + channelSftp.connect(); + SFTPAdaptor.storeJSCH(batchDoc, channelSftp, remotePath, remoteFileName, sendFilePath + "/" + sendFileName, bandWidthLimit, logger); + + // 송신완료파일 생성 및 업로드 + if ( sendCompleteCreateYn.equalsIgnoreCase(YES) ) { + String completeFileName = remoteFileName + "." + sendCompleteFileExt; + File completeFile = new File(sendFilePath + "/" + completeFileName); + completeFile.createNewFile(); + + SFTPAdaptor.storeJSCH(batchDoc, channelSftp, remotePath, completeFileName, sendFilePath + "/" + completeFileName, bandWidthLimit, logger); + Files.delete(completeFile.toPath()); + } + } catch (Exception e) { + logger.error("[{}]파일송신에 실패하였습니다.", moduleName, e); + throw e; + } finally { + if (channelSftp != null) { + channelSftp.disconnect(); + } + } + + // File 종료시간 설정 + setLastActivity(); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode(ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error(errMsg, ex); + throw ex; + } finally { + // SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출. + this.disconnect(); + } + + logger.info("[{}] ■ FEP → VAN사 파일 송신 완료.", moduleName); + + } + + /** + * 자동 스케줄은 해당 폴더의 파일을 모두 수신하고, 수동 스케줄은 해당 일자(파일 프라터티)의 파일만 수신한다. + */ + public void recvFile(BatchDoc batchDoc) throws Exception { + logger = batchDoc.getLogger(); + logger.info("[{}] ■ 대외기관→FEP 파일 수신 시작...... ", moduleName); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, + batchDoc); + ChannelSftp channelSftp = null; + Session session = null; + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + Properties instProperties = FtpSupport.getInstProperties(batchDoc); + Properties fileProperties = FtpSupport.getFileProperties(batchDoc); + + String remotePath = instProperties.getProperty(RECV_REMOTE_PATH); + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + + if (remotePath == null) { + String propName = FtpSupport.getInstitutionPropertyName(batchDoc); + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH); + } + + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + int connTimeout = FtpSupport.getIntProperty(instProperties, CONNECTION_TIMEOUT, 10, logger); + int setTimeout = FtpSupport.getIntProperty(instProperties, READ_TIMEOUT, 10, logger); + String bandWidthLimit = instProperties.getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + logger.debug("["+moduleName+"]recvFileName:{"+remoteFileName+"}"); + + // 특정일자 파일을 수신요청 시, 해당 일자의 경로 설정 + String reqFileName = remoteFileName; + boolean isManualReceive = FtpSupport.isManaulRecive(batchDoc); + // isManualReceive에서 변경한 기준일자 + String baseDate = batchDoc.getBatchMsg().getHeader().getBaseDate(); + + // 경로에 있는 접수 일자 조정. + int addYear = FtpSupport.getIntProperty(fileProperties, FILE_RECV_ADD_YEAR, 0, logger); + int addMonth = FtpSupport.getIntProperty(fileProperties, FILE_RECV_ADD_MONTH, 0, logger); + int addDay = FtpSupport.getIntProperty(fileProperties, FILE_RECV_ADD_DAY, 0, logger); + if (addYear != 0 || addMonth != 0 || addDay != 0) { + baseDate = DatetimeUtil.getDateAddedDate(baseDate, addYear, addMonth, addDay); + } + + // 경로에 있는 TAX//01/send 날짜를 패턴에 따라 변경 + String fileRecvAddPath = fileProperties.getProperty(FILE_RECV_ADD_PATH, ""); + + // 파일별 추가 경로 + remotePath += fileRecvAddPath; + if (!remotePath.endsWith("/")) + remotePath = remotePath + "/"; + + Matcher matcher = PATH_DATE_PATTERN.matcher(remotePath); + + if (matcher.find()) { + String datePattern = matcher.group(1); + DateFormat dateFormatter = new SimpleDateFormat(datePattern); + Date replaceDate = new SimpleDateFormat("yyyyMMdd").parse(baseDate); + remotePath = remotePath.replaceFirst(DATE_PATTERN, dateFormatter.format(replaceDate)); + } + + String authType = instProperties.getProperty(SFTP_AUTH_TYPE, SFTP_AUTH_TYPE_ID); + + try { + if (isManualReceive == false) { + // 자동 스케줄 *.gz 모든 파일 수신. + reqFileName = fileProperties.getProperty(FILE_RECV_AUTO_FILENAME, "*.gz"); + } else { + // 수동 스케줄: 정해진 파일 수신 + reqFileName = fileProperties.getProperty(FILE_RECV_MANUAL_FILENAME, "*.gz"); + } + logger.debug("["+moduleName+"]remotePath:{"+remotePath+"}"); + logger.debug("["+moduleName+"]reqFileName:{"+reqFileName+"}"); + + // SFTP 연결을 하나 만들어서 ls, get 을 실행한다. + session = SFTPAdaptor.getSessionJSCH(ipaddress, port, userid, passwd, authType, connTimeout, setTimeout, logger); + channelSftp = (ChannelSftp) session.openChannel("sftp"); + channelSftp.connect(); + + FTPFile[] list = SFTPAdaptor.lsJSCH(channelSftp, remotePath, reqFileName, logger); + for (FTPFile file : list) { + receiveOneFile(channelSftp, batchDoc, file, remotePath, bandWidth); + } + } catch (Exception e) { + if (!e.getMessage().contains("No such file")) + throw e; + } finally { + closeJsch(logger, session, channelSftp); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode(ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error(errMsg, ex); + throw ex; + } finally { + // SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출. + this.disconnect(); + } + + logger.info("[{}] ■ VAN사 → FEP 파일 수신 완료.", moduleName); + } + + /** + * 파일 하나를 수신한다. + * + * @param sftpClient SFTP 연결 + * @param file 수신할 파일 + * @param remotePath 원격 디렉토리 + */ + protected void receiveOneFile(ChannelSftp channelSftp, BatchDoc batchDoc, FTPFile file, String remotePath, int bandWidth) + throws Exception { + // 파일만 처리 + if (!file.isFile()) { + return; + } + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(file.getName()); + LogUtil.setLogFileStart(batchDoc); + + SFTPAdaptor.cdJSCH(channelSftp, remotePath); + SFTPAdaptor.retrieveJSCH(batchDoc, channelSftp, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), bandWidth, logger); + + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + file.getName(); + File rcvRealFile = new File( recvFile ); + + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + File rcvRootFile = new File( StringUtil.realToRootDir(recvFile) ); + rcvRootFile.createNewFile(); + } else { + throw new Exception("[" + moduleName + "]파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } + + @Override + public void shutdown() { + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return 0; + } + + @Override + public long getLastActivity() { + return 0; + } + + /** + * FlowController END를 위한 값으로 설정한다. + * @param batchDoc 설정 값을 변경할 배치 작업 + */ + private void setDefaultEndStage(BatchDoc batchDoc) { + batchDoc.getBatchMsg().getBody().setFlowPhaseCode(PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getBody().setPhaseType(PHASECODE_NORMAL_END); + //Phase 쪽 단계정보 설정 + batchDoc.getBatchMsg().getPhaseinfo().setRuleCode (this.getClass().getSimpleName()); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseCode (PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseType (PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getPhaseinfo().setFlowClassName ("com.eactive.eai.batch.job.jobModule.Component.END"); + batchDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (0); + batchDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (""); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq ("1"); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue (""); + } + + /** + * 같은 업무, 기관 코드의 작업이 큐에 있는지 확인한다. + * + * @param batchDoc + * @return 큐에서 가져온 배치 잡 + */ + private BatchDoc checkMoreFile(BatchDoc batchDoc) { + logger = batchDoc.getLogger(); + + BatchDoc newDoc = null; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return null; + } + newDoc = EAIBatchMsgManager.createBatchMsg(true); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandle(info); + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(newDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER); + + //BatchMsgDoc 값 설정 + newDoc.getBatchMsg().getHeader().setUUID(info.getUUID()); + newDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID()); + newDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode()); + newDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName()); + newDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType()); + newDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode()); + newDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName()); + newDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + newDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + newDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + newDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + newDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + newDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + newDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + newDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + newDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + newDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + newDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + newDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + newDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + newDoc.getBatchMsg().getHeader().setUserID(batchDoc.getBatchMsg().getHeader().getUserID()); + newDoc.getBatchMsg().getHeader().setUserPassword(batchDoc.getBatchMsg().getHeader().getUserPassword()); + newDoc.getBatchMsg().getHeader().setPort(batchDoc.getBatchMsg().getHeader().getPort()); + newDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode()); + newDoc.getBatchMsg().getHeader().setRequestResponse(info.getRqstRspnsDstcd()); + newDoc.getBatchMsg().getHeader().setRemoteIP(batchDoc.getBatchMsg().getHeader().getRemoteIP()); + + // 다음 파일의 체크 파일 가져오기 + if (info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) + || info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND)) { + String hdrInfoName = info.getHdrInfoName(); + newDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + newDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + newDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + + String dirPath = newDoc.getBatchMsg().getHeader().getFilePath(); + String renamedFileName = newDoc.getBatchMsg().getHeader().getRenamedFileName(); + File file = new File(dirPath + File.separatorChar + renamedFileName); + if (!file.exists()) { + throw new Exception(); + } + long fileLen = file.length(); + + newDoc.getBatchMsg().getHeader().setFileSize(fileLen); + } + } catch ( Exception e){ + logger.error(newDoc == null ? "batchDoc is null" : newDoc.toString(), e); + return null; + } + + return newDoc; + } + + private void closeJsch(Logger logger, Session session, ChannelSftp channelSftp) { + if (channelSftp != null && channelSftp.isConnected()) { + try { + channelSftp.disconnect(); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } + if (session != null) { + try { + session.disconnect(); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + + } + } +} diff --git a/src/com/eactive/eai/adapter/ftp/FTPKF.java b/src/com/eactive/eai/adapter/ftp/FTPKF.java new file mode 100644 index 0000000..9aa7cf0 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPKF.java @@ -0,0 +1,284 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +// KED Findsystem 파일수신 ( SFTP ) +// IP : 10.0.249.35 PORT : 22 +// ID : kjbank PWD: kjbank2015 +// 수신디렉터리 : /ftp_user/kjbank/test/senddata/findsystem +// 백업디렉터리 : ? +// 파일명: +// KED_20191015142047_20191015_H01_1_35766653888617_1_1_1058675080000.TIF +// KEDFS_20191015142047_20191015_H06_1_35766653888617_1_1_1058675080000.TIF + + +public class FTPKF extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String REMOTE_PATH = "remote.path"; + private static final String BACKUP_PATH = "backup.path"; + private static final String FIN_EXT = "fin.ext"; + private static final String FILE_EXT = "file.ext"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPKF] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String backupPath = pmanager.getProperties(propName).getProperty(BACKUP_PATH); + if ( backupPath == null ){ + throw new Exception("해당 기관에 백업 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + BACKUP_PATH); + } + + String finExt = pmanager.getProperties(propName).getProperty(FIN_EXT); + if (finExt == null){ + finExt = ".fin"; + } + + String fileExt = pmanager.getProperties(propName).getProperty(FILE_EXT); + if (fileExt == null) { + fileExt = ".tif"; + } + + logger.debug( "[FTPKF]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate ); +// if ( !remotePath.endsWith("/") ) +// remotePath = remotePath + "/"; + + backupPath = backupPath.replaceAll("#YYYYMMDD#", baseDate ); + if ( !backupPath.endsWith("/") ) + backupPath = backupPath + "/"; + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + FTPFile[] list = null; + try { + list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + // .fin 파일에서 원본 파일을 찾기 위해서 + Map fileMap = new HashMap(); + for (int i = 0; i < list.length; i++) { + fileMap.put(list[i].getName(), list[i]); + } + + for (int i = 0 ; i < list.length; i++){ + FTPFile file = list[i]; + if ( file.getName().endsWith(finExt) ){ + String finFileName = file.getName(); + + // a.fin을 a.tif로 변경 + String recvFileName = finFileName.substring(0, finFileName.length() - finExt.length()); + recvFileName += fileExt; + FTPFile recvFtpFile = fileMap.get(recvFileName); + + if (recvFtpFile == null) { + throw new Exception(file.getName() + " 파일에 해당하는 원본 파일 [" + recvFileName + "] 이 없습니다."); + } + + batchDoc.getBatchMsg().getHeader().setFileSize(recvFtpFile.getSize()); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(recvFtpFile.getName()); + LogUtil.setLogFileStart(batchDoc); + + //FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + recvFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, recvFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + //batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + recvFileName; + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File(StringUtil.realToRootDir(recvFile)); + + try { + File rcvArchFile = new File(StringUtil.realToArchDir(recvFile)); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + //setFileHeaderAndTrailer(batchDoc, rcvRealFile); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + } else { + throw new Exception("파일수신에 실패하였습니다." + recvFileName); + } + + // 원본 파일 백업 + try { + FTPUtil.renameWithMkdirs(ipaddress, port, userid, passwd, remotePath + recvFileName, backupPath, recvFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + } catch (Exception e) { + logger.error("파일 백업에 실패하였습니다." + recvFileName, e); + throw new Exception("파일 백업에 실패하였습니다."); + } + + // .fin 파일 백업 + try { + FTPUtil.rename(ipaddress, port, userid, passwd, remotePath + file.getName(), backupPath + file.getName(), true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + } catch (Exception e) { + logger.error(".fin 파일 백업에 실패하였습니다." + file.getName(), e); + throw new Exception(".fin 파일 백업에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + } + } + } + + }catch ( Exception e ){ + if ( e.getMessage() != null && !e.getMessage().contains("No such file")) + throw e; + } + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPKF] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPKM.java b/src/com/eactive/eai/adapter/ftp/FTPKM.java new file mode 100644 index 0000000..a2d8419 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPKM.java @@ -0,0 +1,277 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +/** + * 한국조폐공사(KMS) 연동 + * Java 1.7에서 jsch로 연동 불가하여 sshj 사용 + * Bandwith 삭제함 + * SFTP 송수신 중단 안됨 + */ + + +public class FTPKM extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String SEND_REMOTE_PATH = "send.remote.path"; + private static final String SEND_DELAY_SEC = "send.delay.sec"; + private static final String RECV_REMOTE_PATH = "recv.remote.path"; + private static final String REQ_FILE_NAME = "req.file.name"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPKM] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //Shell 명령어를 Runtime 으로 실행 + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + String remotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + long delaySec = 60 * 1000; + try { + delaySec = Long.parseLong(pmanager.getProperties(propName).getProperty(SEND_DELAY_SEC)); + Thread.sleep(delaySec * 1000); + }catch ( Exception e){} + + String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + //String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName(); + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + + setFileHeaderAndTrailer(batchDoc, new File(sendFileName)); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + FTPUtil.store(ipaddress, port, userid, passwd, remotePath + remoteFileName, sendFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); +// FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName, +// connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER), authType); + + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + this.disconnect(); + } + logger.info("[FTPKM] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPKM] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(RECV_REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + logger.debug( "[FTPKM]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + if ( DatetimeUtil.isRightDate(reqFileName.substring(bizCode.length()))){ + reqFileName = pmanager.getProperties(propName).getProperty(REQ_FILE_NAME); + batchDoc.getBatchMsg().getHeader().setFileName(reqFileName); + } + logger.debug( "[FTPKM]reqFileName:" + reqFileName ); + + try { + FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + for ( int inx = 0 ; inx < list.length; inx++){ + FTPFile file = list[inx]; + if ( file.getName().equals(reqFileName) ){ + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(file.getName()); + LogUtil.setLogFileStart(batchDoc); + FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true, + batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName(); + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + } + } + } + }catch ( Exception e ){ + if ( !e.getMessage().contains("No such file")) + throw e; + } + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPKM] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPKN.java b/src/com/eactive/eai/adapter/ftp/FTPKN.java new file mode 100644 index 0000000..8cbd87c --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPKN.java @@ -0,0 +1,303 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +// KT-NET 자료 송수신 ( SFTP ) +// IP : 10.0.249.28 (R), 10.0.249.29 (T) PORT : 30022 +// ASIS -- ID : kjbsftp PWD: sftpKjb +// 파일명 +//송신시 /recv/doc +//수신시 /send/doc +// KJ[연도네자리][신청번호].pdf + + +// 차세대 +// ID : gjbsftp PW: sftpGjb +//송신시 /recv/doc +//수신시 /send/doc + + +public class FTPKN extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String SEND_REMOTE_PATH = "send.remote.path"; + private static final String SEND_DELAY_SEC = "send.delay.sec"; + private static final String RECV_REMOTE_PATH = "recv.remote.path"; + private static final String REQ_FILE_NAME = "req.file.name"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPKN] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //Shell 명령어를 Runtime 으로 실행 + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + String remotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH); + } + + long delaySec = 60 * 1000; + try { + delaySec = Long.parseLong(pmanager.getProperties(propName).getProperty(SEND_DELAY_SEC)); + Thread.sleep(delaySec * 1000); + }catch ( Exception e){} + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + //String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName(); + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + + setFileHeaderAndTrailer(batchDoc, new File(sendFileName)); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + //FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName, + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + this.disconnect(); + } + logger.info("[FTPKN] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPKN] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(RECV_REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + logger.debug( "[FTPKN]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + if ( DatetimeUtil.isRightDate(reqFileName.substring(bizCode.length()))){ + reqFileName = pmanager.getProperties(propName).getProperty(REQ_FILE_NAME); + batchDoc.getBatchMsg().getHeader().setFileName(reqFileName); + } + logger.debug( "[FTPKN]reqFileName:" + reqFileName ); + + + try { + FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + for ( int inx = 0 ; inx < list.length; inx++){ + FTPFile file = list[inx]; + if ( file.getName().equals(reqFileName) ){ + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(file.getName()); + LogUtil.setLogFileStart(batchDoc); + //FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + //batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName(); + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + //setFileHeaderAndTrailer(batchDoc, rcvRealFile); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + } + } + } + }catch ( Exception e ){ + if ( !e.getMessage().contains("No such file")) + throw e; + } + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPKN] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPKS.java b/src/com/eactive/eai/adapter/ftp/FTPKS.java new file mode 100644 index 0000000..78ed892 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPKS.java @@ -0,0 +1,235 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +// KED 파일 수신 ( SFTP ) +// IP : 10.0.249.35 PORT : 22 +// ID : kjbank PWD: kjbank2015 +// 파일명: test/YYYYMMDD/kjbank_YYYYMMDD.jar (TEST) +// prod/YYYYMMDD/kjbank_YYYYMMDD.jar (PROD) + +public class FTPKS extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String REMOTE_PATH = "remote.path"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPKS] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + logger.debug( "[FTPKS]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate ); + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate + ".jar"; + logger.debug( "[FTPKS]reqFileName:" + reqFileName ); + + + boolean isFileInTheServer = false; + try { + FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + //FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, false, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + + for ( int inx = 0 ; inx < list.length; inx++){ + FTPFile file = list[inx]; + if ( file.getName().equals(reqFileName) ){ + isFileInTheServer = true; + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + file.isFile(); + break; + } + } + }catch ( Exception e ){ + if ( !e.getMessage().contains("No such file")) + throw e; + } + + if ( isFileInTheServer ){ + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(reqFileName); + LogUtil.setLogFileStart(batchDoc); + //FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + reqFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, reqFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + //FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath + reqFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), + // connTimeout, setTimeout, false, bandWidth, logger); + + //batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName; + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + //setFileHeaderAndTrailer(batchDoc, rcvRealFile); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + + } + + } + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPKS] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPMC.java b/src/com/eactive/eai/adapter/ftp/FTPMC.java new file mode 100644 index 0000000..e3ef2b3 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPMC.java @@ -0,0 +1,234 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +// 여신 메타 자료 수신 ( SFTP ) +// IP : 10.0.249.68 PORT : 22 +// ID : kjbankftp PWD: !@$#kjbank@mcgFTP +// 수신: +// 파일명 META_YYYYMMDDHH.jar +// TEST / PROD 별도 서버 구성 +// 접속후 send 폴더에 파일이 존재 함. +// 파일 수신 후 send/send.done 폴더 아래로 파일 이동 바람. +public class FTPMC extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String REMOTE_PATH = "remote.path"; + private static final String REMOTE_BACKUP_PATH = "remote.backup.path"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다."); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPMC] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + String remote_backup_Path = pmanager.getProperties(propName).getProperty(REMOTE_BACKUP_PATH); + + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + logger.debug( "[FTPMC]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + + reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate; + logger.debug( "[FTPMC]reqFileName:" + reqFileName ); + + + try { + FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + for ( int inx = 0 ; inx < list.length; inx++){ + FTPFile file = list[inx]; + if ( file.getName().startsWith(reqFileName) ){ + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(file.getName()); + LogUtil.setLogFileStart(batchDoc); + //FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + //batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName(); + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + //setFileHeaderAndTrailer(batchDoc, rcvRealFile); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + } + + try { + FTPUtil.rename(ipaddress, port, userid, passwd,remotePath + file.getName(), remotePath +remote_backup_Path +"/" + file.getName(), true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + } catch (Exception e){ + throw new Exception("파일수신후 백업디렉토리로 RENAME 실패하였습니다."); + } + } + } + }catch ( Exception e ){ + if ( !e.getMessage().contains("No such file")) + throw e; + } + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPMC] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPNC.java b/src/com/eactive/eai/adapter/ftp/FTPNC.java new file mode 100644 index 0000000..4e267d3 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPNC.java @@ -0,0 +1,322 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +// NICE CB 자료 송수신 ( SFTP ) +// IP : 10.94.50.207 PORT : 22 +// ID : kjb01 PWD: kjb1111 +// 파일명 +// 송신: +// F13_MXALINF 90 당행CB정보송신 +// F13_CSALINB 90 당행CB정보송신 +// 1A9_REWOINF 90 당행조기경보회원등록(부동산) +// 수신: +// NICE_MXALINF_F13 Y 90 나이스CB정보수신 +// NICE_CSALINB_F13 Y 90 나이스CB정보수신 +// NICE_MXALINF_F13_CARD N 90 나이스CB정보수신 +// NICE_REWORLT_1A9 N 90 나이스부동산권리정보(정상분) +// NICE_REWOERR_1A9 N 90 나이스부동산권리정보(오류분) +// NICE_EWRECHG_1A9 N 90 나이스부동산권리정보(변경분) +// TEST / PROD 구분이 없음, TEST파일의 경우 파일명 어딘가에 TEST라는 표시가 있으면 됨. +// 김효희 과장. 02-2122-4033 +public class FTPNC extends Transfer implements SocketService{ + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + private static final String REMOTE_PATH = "remote.path"; + private static final String POSTFIX = "post.fix"; + + public void sendFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPNC] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //Shell 명령어를 Runtime 으로 실행 + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + //String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName(); + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + setFileHeaderAndTrailer(batchDoc, new File(sendFileName)); + + //나이스 테스트 파일명 "TEST_" 운영path는 반드시 "/"로 끝나야 한다. + String fullPath = remotePath+remoteFileName; + String [] arr = fullPath.split("/"); + + remoteFileName = arr[arr.length-1]; + remotePath = fullPath.replace(remoteFileName, ""); + + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + //FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName, + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + //FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remoteFileName, sendFileName, + // connTimeout, setTimeout, false, bandWidth, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + logger.debug("guid ["+batchDoc.getBatchMsg().getHeader().getUUID()+"]"+"FTPUtil.store finish<<<<<<<<<<<<<<<<<<<<<<<"); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + this.disconnect(); + } + logger.info("[FTPNC] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]"); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger.info("[FTPNC] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + //2. System FTP Shell 명령어를 Runtime 으로 실행 + try { + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + String jobName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getBizCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH); + String postfix = null; + try{ + postfix = pmanager.getProperties(jobName).getProperty(POSTFIX); + }catch( Exception e ){} + + if ( remotePath == null ){ + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH); + } + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE); + if (StringUtils.isBlank(authType)) { + authType = AUTH_TYPE_ID; // id + } + + //20220712 + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10"); + int connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10"); + int setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + + logger.debug( "[FTPNC]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + if ( reqFileName != null && reqFileName.length() > 8 ){ + if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){ + baseDate = reqFileName.substring(reqFileName.length() - 8 ); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + } + } + + reqFileName = "NICE_" + batchDoc.getBatchMsg().getHeader().getBizCode() + "." + baseDate.substring(2); + if ( postfix != null && !!postfix.equals("")){ + reqFileName = reqFileName + postfix; + } + logger.debug( "[FTPNC]reqFileName:" + reqFileName ); + + + try { + FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + for ( int inx = 0 ; inx < list.length; inx++){ + FTPFile file = list[inx]; + if ( file.getName().equals(reqFileName) ){ + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(file.getName()); + LogUtil.setLogFileStart(batchDoc); + //FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER)); + FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), + connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType); + + //batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName(); + File rcvRealFile = new File( recvFile ); + File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + //setFileHeaderAndTrailer(batchDoc, rcvRealFile); + rcvRealFile.renameTo(rcvArchFile); + rcvChkFile.createNewFile(); + }else{ + throw new Exception("파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + } catch (Exception e) { + throw e; + } + } + } + }catch ( Exception e ){ + if ( !e.getMessage().contains("No such file")) + throw e; + } + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + this.disconnect(); + } + logger.info("[FTPNC] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + + } + + @Override + public Socket getCurrentSocket() { + return null; + } + + @Override + public boolean connect() { + return false; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public void setControl(Object control) { + + } + + @Override + public void notifyMessage() { + + } + + @Override + public boolean idle(long timeout) { + return false; + } + + @Override + public int getCurrentState() { + return 0; + } + + @Override + public boolean isConnected() throws IOException { + return false; + } + + @Override + public boolean isActive() { + return false; + } + + @Override + public void checkActivity() { + + } + + @Override + public String getRemoteIPAddress() { + return null; + } + + @Override + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + return firstActivity; + } + + @Override + public long getLastActivity() { + return lastActivity; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/ftp/FTPNT.java b/src/com/eactive/eai/adapter/ftp/FTPNT.java new file mode 100644 index 0000000..0edb92e --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPNT.java @@ -0,0 +1,766 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; +import java.nio.file.Files; +import java.util.Properties; + +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.util.Timeout; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.core5.http.ContentType; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; +import org.quartz.JobKey; +import org.quartz.SchedulerException; +import org.quartz.impl.matchers.GroupMatcher; +import com.eactive.eai.common.util.Logger; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.agent.web.FepFileSupport; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.doc.Header; +import com.eactive.eai.batch.ftp.SFTPAdaptor; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.scheduler.Scheduler; +import com.eactive.eai.common.scheduler.SchedulerKeys; +import com.eactive.eai.common.scheduler.SchedulerManager; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.SftpATTRS; + +/** + * 차세대 지방세입 자동이체를 지원한다. + * + * 1. SFTPClient를 하나 만들어서 사용한다. + * 2. 전송할 파일이 검사한 후 계속 전송한다.(send.max.iteration 기관 프로퍼티: 없으면 하나만 전송) + * + */ +public class FTPNT extends Transfer implements SocketService { + /** 송신 폴더 */ + private static final String SEND_REMOTE_PATH = "send.remote.path"; + /** 수신 폴더 */ + private static final String RECV_REMOTE_PATH = "recv.remote.path"; + + + // 송신완료파일 생성관련 프로퍼티 + private static final String SEND_COMPLETE_CREATE_YN = "send.complete.create.yn"; + private static final String SEND_COMPLETE_FILE_EXT = "send.complete.file.ext"; + + /** 인증 방법 1 = id, 2 = key 방식 */ + private static final String AUTH_TYPE = "sftp.auth.type"; + + /** 큐에서 가져오는 최대 갯수. 없으면 하나만 전송 */ + private static final String SEND_MAX_ITERATION = "send.max.iteration"; + + public final static String PHASECODE_NORMAL_END = "END"; + + /** 송신 완료 전송 */ + private static final String SEND_NOTIFY_YN = "send.notify.yn"; + /** 송신 완료을 알릴 송신 파일 이름 Regular Expression */ + private static final String SEND_NOTIFY_FILENAME_PATTERN = "send.notify.filename.pattern"; + + /** , 로 구분한 송신 완료 전송 URL */ + private static final String SEND_NOTITY_URLS = "send.notify.urls"; + private static final String SEND_NOTITY_CONNECTION_TIMEOUT = "send.notify.connection.timeout"; + private static final String SEND_NOTITY_READ_TIMEOUT = "send.notify.read.timeout"; + + /** 수신 완료 전송 여부 */ + private static final String RECV_NOTIFY_YN = "recv.notify.yn"; + + /** 파일 수신 후 계정계로 파일 전송 Job 실행 */ + private static final String RECV_ROOT_JOB_NAME = "EF003"; + + @Override + public void sendFile(BatchDoc batchDoc) throws Exception { + ChannelSftp channelSftp = null; + Session session = null; + try { + logger = (com.eactive.eai.common.util.Logger) batchDoc.getLogger(); + String propName = FtpSupport.getInstitutionPropertyName(batchDoc); + Properties institutionProperties = PropManager.getInstance().getProperties(propName); + + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String authType = institutionProperties.getProperty(AUTH_TYPE, AUTH_TYPE_ID); + // 설정이 없으면 기존 처럼 한 번만 돈다. + int iteration = FtpSupport.getIntProperty(institutionProperties, SEND_MAX_ITERATION, 1, (Logger) logger); + int connTimeout = FtpSupport.getIntProperty(institutionProperties, CONNECTION_TIMEOUT, 10, (Logger) logger); + int setTimeout = FtpSupport.getIntProperty(institutionProperties, READ_TIMEOUT, 10, (Logger) logger); + String bandWidthLimit = institutionProperties.getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + session = SFTPAdaptor.getSessionJSCH(ipaddress, port, userid, passwd, authType, connTimeout, setTimeout, (Logger) logger); + + internalSendFile(session, batchDoc, bandWidth, (Logger) logger); + + for (int i = 1; i < iteration; i++) { + // Queue에 있는 지 확인한다. + BatchDoc newDoc = checkMoreFile(batchDoc); + if (newDoc == null) { + break; + } + String uuid = newDoc.getBatchMsg().getHeader().getUUID(); + String subUuid = newDoc.getBatchMsg().getBody().getSubUUID(); + try { + internalSendFile(session, newDoc, bandWidth, logger); + + newDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + setDefaultEndStage(newDoc); + // FlowController Log + LogUtil.setLog(newDoc); + // master 정보 + LogUtil.updateLogMaster(newDoc); + // master 작업상태 정보: 정상 종료 + LogUtil.setEndLog(newDoc); + } finally { + // 진행중에서 삭제. 반드시 삭제되어야 함 + SchedulerMessageManager.getInstance().deleteJobFromProcessing(uuid, subUuid); + } + } + } finally { + closeJsch(logger, session, channelSftp); + } + } + + /** + * 파일 하나를 전송한다. + */ + protected void internalSendFile(Session session, BatchDoc batchDoc, int bandWidthLimit, Logger logger) throws Exception { + logger.info("[FTPNT] ■ 대외기관→FEP 파일 송신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + + // 전송 성공 여부 + boolean result = false; + // 계정계 통보 + String notifyCBSFilename = null; + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String sendNotifyYn = "N"; + try { + String propName = FtpSupport.getInstitutionPropertyName(batchDoc); + Properties institutionProperties = PropManager.getInstance().getProperties(propName); + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + String hdrfileName = hdrInfo.substring(19, hdrInfo.length() - 2).trim(); + + String remotePath = null; + if (hdrfileName.contains("/")) { + int position = hdrfileName.lastIndexOf("/"); + remotePath = hdrfileName.substring(0, position); + remoteFileName = hdrfileName.substring(position + 1); + } + + if (remotePath == null) { + remotePath = institutionProperties.getProperty(SEND_REMOTE_PATH); + } + if (remotePath == null) { + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH); + } + + + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String sendCompleteCreateYn = institutionProperties.getProperty(SEND_COMPLETE_CREATE_YN, "n"); + String sendCompleteFileExt = ""; + if (!sendCompleteCreateYn.equalsIgnoreCase("y") ) { + sendCompleteCreateYn = "n"; + } + else { + sendCompleteCreateYn = "y"; + sendCompleteFileExt = institutionProperties.getProperty(SEND_COMPLETE_FILE_EXT, "done"); + } + + notifyCBSFilename = institutionProperties.getProperty(SEND_NOTIFY_FILENAME_PATTERN); + sendNotifyYn = institutionProperties.getProperty(SEND_NOTIFY_YN, "N"); + + // 실제 파일이름 +// String orgFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + // FEP 에서 Rename(송신Real->송신Arch)한 파일이름 + String sendFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + logger.debug( "[FTPNT]sendFileName:" + remoteFileName); + logger.debug( "[FTPNT]remotePath:" + remotePath); + + //File 시작시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + String sendFilePath = batchDoc.getBatchMsg().getHeader().getFilePath(); + + ChannelSftp channelSftp = null; + try { + channelSftp = (ChannelSftp) session.openChannel("sftp"); + channelSftp.connect(); + SFTPAdaptor.storeJSCH(batchDoc, channelSftp, remotePath, remoteFileName, sendFilePath + File.separator + sendFileName, bandWidthLimit, logger); + + // 송신완료파일 생성 및 업로드 + if ( sendCompleteCreateYn == "y" ) { + String completeFileName = remoteFileName + "." + sendCompleteFileExt; + File completeFile = new File(sendFilePath + File.separatorChar + completeFileName); + completeFile.createNewFile(); + + SFTPAdaptor.storeJSCH(batchDoc, channelSftp, remotePath, completeFileName, sendFilePath + File.separator + completeFileName, bandWidthLimit, logger); + Files.delete(completeFile.toPath()); + } + } catch (Exception e) { + logger.error("[SFTP1]파일송신에 실패하였습니다.", e); + throw e; + } finally { + if (channelSftp != null) { + channelSftp.disconnect(); + } + } + + //File 종료시간 설정 + setLastActivity(); + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + result = true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID()); + // SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출. + this.disconnect(); + + // 파일 이름 패턴이 통보하는 이름과 매칭되면 + if ("y".equalsIgnoreCase(sendNotifyYn) && StringUtils.isNotBlank(notifyCBSFilename) && remoteFileName.matches(notifyCBSFilename)) { + sendResult("S", result, batchDoc, "", "", 1, remoteFileName); + } + } + + logger.info("[FTPNT] ■ FEP → VAN사 파일 송신 완료."); + } + + /** + * 송신 결과를 계정계로 알려준다. + * + * @param sendOrReceive 송수신 구분. S: 송신, R: 수신 + * @param batchDoc + * @param remoteFileName + * @param result + */ + private void sendResult(String sendOrReceive, boolean resultCode, BatchDoc batchDoc, String listFileName, String listFileYn, int fileCount, String remoteFilename) { + logger = batchDoc.getLogger(); + String propName = FtpSupport.getInstitutionPropertyName(batchDoc); + Properties institutionProperties = PropManager.getInstance().getProperties(propName); + + String notifyUrls = institutionProperties.getProperty(SEND_NOTITY_URLS); + int connectionTimeout = FtpSupport.getIntProperty(institutionProperties, SEND_NOTITY_CONNECTION_TIMEOUT, 10, logger); + int readTimeout = FtpSupport.getIntProperty(institutionProperties, SEND_NOTITY_READ_TIMEOUT, 10, logger); + + //PostMethod method = null; + if (StringUtils.isBlank(notifyUrls)) { + logger.error("notifyUrls is blank"); + return; + } + + notifyUrls = notifyUrls.trim(); + String message = FepFileSupport.getNotifyMessage(sendOrReceive, resultCode, batchDoc, listFileName, listFileYn, fileCount, remoteFilename); + for (String notifyUrl : notifyUrls.split("\\s*,\\s*")) { + try { + HttpPost post = new HttpPost(notifyUrl); + + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(Timeout.ofSeconds(connectionTimeout)) + .setResponseTimeout(Timeout.ofSeconds(readTimeout)) + .build(); + post.setConfig(requestConfig); + + StringEntity entity = new StringEntity( + "msg=" + message, + ContentType.create("application/x-www-form-urlencoded", "EUC-KR") + ); + + post.setEntity(entity); + + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = client.execute(post)) { + + int status = response.getCode(); + if (status != HttpStatus.SC_OK) { + logger.error("http status error {" + status + "}, url = {" + notifyUrl + "}"); + } + + // 응답 읽기 + String responseMessage = EntityUtils.toString(response.getEntity(), "EUC-KR"); + logger.info("Url {" + notifyUrl + "} response = {" + responseMessage + "}"); + } + break; + } catch (Exception e) { + logger.error("url = {"+notifyUrl+"}, msg={"+message+"}"); + logger.error(e.getLocalizedMessage(), e); + } + + + } + } + + + /** + * 수신 결과를 계정계로 알려준다. + * 수신 이벤트 job을 trigger한다. + * + * @param batchDoc + * @param remoteFileName + * @param result + * @throws SchedulerException + */ + private void sendReceiveResult(boolean resultCode, BatchDoc batchDoc, String listFileName, String listFileYn, int fileCount, String remoteFilename) throws SchedulerException { + logger = batchDoc.getLogger(); + SchedulerManager schedulerManager = SchedulerManager.getInstance(); + Scheduler scheduler = schedulerManager.getScheduler(SchedulerKeys.DEFAULT_SCHEDULER_ID); + org.quartz.Scheduler quartzScheduler = scheduler.getQuartzScheduler(); + for (String groupName : quartzScheduler.getJobGroupNames()) { + // get jobkey + for (JobKey jobKey : quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { + String jobName = jobKey.getName(); + String jobGroup = jobKey.getGroup(); + if (jobName.equals(RECV_ROOT_JOB_NAME)) { + logger.info("triggering jobName = {"+jobName+"}, jogGroup = {"+jobGroup+"}"); + quartzScheduler.triggerJob(jobKey); + break; + } + } + } + + sendResult("R", resultCode, batchDoc, listFileName, listFileYn, fileCount, remoteFilename); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + logger = batchDoc.getLogger(); + logger.info("[FTPNT] ■ 대외기관→FEP 파일 수신 시작...... "); + firstActivity = System.currentTimeMillis(); + setLastActivity(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc); + ChannelSftp channelSftp = null; + Session session = null; + String recvNotifyYn = "N"; + int fileCount = 0; + boolean resultCode = false; + try { + String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP(); + int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + String userid = batchDoc.getBatchMsg().getHeader().getUserID(); + String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword(); + + String propName = FtpSupport.getInstitutionPropertyName(batchDoc); + Properties institutionProperties = PropManager.getInstance().getProperties(propName); + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + + String hdrFileName = hdrInfo.substring(19, hdrInfo.length() - 2).trim(); + String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String requestFileName = remoteFileName; + + String remotePath = null; + if (hdrFileName.contains("/")) { + requestFileName = hdrFileName; + int position = hdrFileName.lastIndexOf("/"); + remotePath = hdrFileName.substring(0, position); + remoteFileName = hdrFileName.substring(position + 1); + } + if (remotePath == null) { + remotePath = institutionProperties.getProperty(RECV_REMOTE_PATH); + } + if (remotePath == null) { + throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH); + } + + if ( !remotePath.endsWith("/") ) + remotePath = remotePath + "/"; + + String authType = institutionProperties.getProperty(AUTH_TYPE, AUTH_TYPE_ID); + recvNotifyYn = institutionProperties.getProperty(RECV_NOTIFY_YN, "N"); + + int connTimeout = FtpSupport.getIntProperty(institutionProperties, CONNECTION_TIMEOUT, 10, logger); + int setTimeout = FtpSupport.getIntProperty(institutionProperties, READ_TIMEOUT, 10, logger); + String bandWidthLimit = institutionProperties.getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", ""); + int bandWidth = Integer.parseInt(bandWidthLimit); + + String listFileName = ""; // 수신한 LIST 파일:EBG00_EBGR_LISTTR 형식 + String listFileYn = "N"; // LIST 파일 수신 여부 + + logger.debug( "[FTPNT]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName()); + + try { + session = SFTPAdaptor.getSessionJSCH(ipaddress, port, userid, passwd, authType, connTimeout, setTimeout, logger); + channelSftp = (ChannelSftp) session.openChannel("sftp"); + channelSftp.connect(); + + // 파일을 가져올지 디렉터리를 가져올지 + boolean oneFile = false; + if (!FtpSupport.hasWildcard(remoteFileName)) { + SftpATTRS sa = SFTPAdaptor.lstatJSCH(channelSftp, remotePath, remoteFileName); + if (sa.isReg()) { + oneFile = true; + } + } + // 파일 하나만 수신한다. + if (oneFile) { + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(remoteFileName); + + SFTPAdaptor.cdJSCH(channelSftp, remotePath); + SFTPAdaptor.retrieveJSCH(batchDoc, channelSftp, remoteFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), bandWidth, logger); + + File file = new File(batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + remoteFileName); + batchDoc.getBatchMsg().getHeader().setFileSize(file.length()); + + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + remoteFileName; + File rcvRealFile = new File( recvFile ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + File rcvRootFile = new File( StringUtil.realToRootDir(recvFile) ); + rcvRootFile.createNewFile(); + + // LIST 파일이면 통보 내용으로 설정한다. + if (remoteFileName.toUpperCase().startsWith("LIST")) { + listFileYn = "Y"; + Header header = batchDoc.getBatchMsg().getHeader(); + + listFileName = header.getProcessCode() + "_" + header.getInstitutionCode() + "_" + remoteFileName; + } + } else { + throw new Exception("[FTPNT]파일수신에 실패하였습니다."); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + resultCode = true; + } catch (Exception e) { + throw e; + } + } else { + FTPFile[] list = SFTPAdaptor.lsJSCH(channelSftp, remotePath, remoteFileName, logger); + + SFTPAdaptor.cdJSCH(channelSftp, remotePath); + for ( int inx = 0 ; inx < list.length; inx++ ){ + //강제중지 설정시 + if (batchDoc.isUserCancel()){ + throw new Exception("사용자가 전송을 중지 했습니다."); + } + + FTPFile file = list[inx]; + + if (!file.isFile()) { + continue; + } + + batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize()); + batchDoc.getBatchMsg().getBody().setRecCnt(1); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchDoc.getBatchMsg().getHeader().setFileName(file.getName()); + LogUtil.setLogFileStart(batchDoc); + SFTPAdaptor.retrieveJSCH(batchDoc, channelSftp, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), bandWidth, logger); + + String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName(); + File rcvRealFile = new File( recvFile ); + + try { + File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) ); + if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) { + rcvRealFile.renameTo(rcvArchFile); + File rcvRootFile = new File( StringUtil.realToRootDir(recvFile) ); + rcvRootFile.createNewFile(); + + // LIST 파일이면 통보 내용으로 설정한다. + if (file.getName().toUpperCase().startsWith("LIST")) { + listFileYn = "Y"; + Header header = batchDoc.getBatchMsg().getHeader(); + + listFileName = header.getProcessCode() + "_" + header.getInstitutionCode() + "_" + file.getName(); + } + } else { + throw new Exception("[FTPNT]파일수신에 실패하였습니다."); + } + fileCount++; + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileEnd(batchDoc); + resultCode = true; + } catch (Exception e) { + throw e; + } + } + } + } catch ( Exception e ){ + if ( !e.getMessage().contains("No such file") ) { + resultCode = false; + throw e; + } + } finally { + closeJsch(logger, session, channelSftp); + + if ("y".equalsIgnoreCase(recvNotifyYn)) { + sendReceiveResult(resultCode, batchDoc, listFileName, listFileYn, fileCount, requestFileName); + } + } + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error( errMsg, ex ); + throw ex; + } finally { + batchDoc.setSftpChannel(null); + this.disconnect(); + } + + logger.info("[FTPNT] ■ VAN사 → FEP 파일 수신 완료."); + } + + @Override + public void shutdown() { + // TODO Auto-generated method stub + + } + + @Override + public Socket getCurrentSocket() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean connect() { + // TODO Auto-generated method stub + return false; + } + + @Override + public ConfigurationContext getContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setControl(Object control) { + // TODO Auto-generated method stub + + } + + @Override + public void notifyMessage() { + // TODO Auto-generated method stub + + } + + @Override + public boolean idle(long timeout) { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getCurrentState() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean isConnected() throws IOException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isActive() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void checkActivity() { + // TODO Auto-generated method stub + + } + + @Override + public String getRemoteIPAddress() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setLastActivity() { + // TODO Auto-generated method stub + + } + + @Override + public long getFirstActivity() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public long getLastActivity() { + // TODO Auto-generated method stub + return 0; + } + + /** + * FlowController END를 위한 값으로 설정한다. + * @param batchDoc 설정 값을 변경할 배치 작업 + */ + private void setDefaultEndStage(BatchDoc batchDoc) { + batchDoc.getBatchMsg().getBody().setFlowPhaseCode(PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getBody().setPhaseType(PHASECODE_NORMAL_END); + //Phase 쪽 단계정보 설정 + batchDoc.getBatchMsg().getPhaseinfo().setRuleCode (this.getClass().getSimpleName()); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseCode (PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseType (PHASECODE_NORMAL_END); + batchDoc.getBatchMsg().getPhaseinfo().setFlowClassName ("com.eactive.eai.batch.job.jobModule.Component.END"); + batchDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (0); + batchDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (""); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq ("1"); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue (""); + } + + /** + * 같은 업무, 기관 코드의 작업이 큐에 있는지 확인한다. + * + * @param batchDoc + * @return 큐에서 가져온 배치 잡 + */ + private BatchDoc checkMoreFile(BatchDoc batchDoc) { + logger = batchDoc.getLogger(); + + BatchDoc newDoc = null; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return null; + } + newDoc = EAIBatchMsgManager.createBatchMsg(true); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandle(info); + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(newDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER); + + //BatchMsgDoc 값 설정 + newDoc.getBatchMsg().getHeader().setUUID(info.getUUID()); + newDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID()); + newDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode()); + newDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName()); + newDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType()); + newDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode()); + newDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName()); + newDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + newDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + newDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + newDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + newDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + newDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + newDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + newDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + newDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + newDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + newDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + newDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + newDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + newDoc.getBatchMsg().getHeader().setUserID(batchDoc.getBatchMsg().getHeader().getUserID()); + newDoc.getBatchMsg().getHeader().setUserPassword(batchDoc.getBatchMsg().getHeader().getUserPassword()); + newDoc.getBatchMsg().getHeader().setPort(batchDoc.getBatchMsg().getHeader().getPort()); + newDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode()); + newDoc.getBatchMsg().getHeader().setRequestResponse(info.getRqstRspnsDstcd()); + newDoc.getBatchMsg().getHeader().setRemoteIP(batchDoc.getBatchMsg().getHeader().getRemoteIP()); + + // 다음 파일의 체크 파일 가져오기 + if (info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) + || info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND)) { + String hdrInfoName = info.getHdrInfoName(); + newDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + newDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + newDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + + String dirPath = newDoc.getBatchMsg().getHeader().getFilePath(); + String renamedFileName = newDoc.getBatchMsg().getHeader().getRenamedFileName(); + File file = new File(dirPath + File.separatorChar + renamedFileName); + if (!file.exists()) { + throw new Exception(); + } + long fileLen = file.length(); + + newDoc.getBatchMsg().getHeader().setFileSize(fileLen); + } + } catch ( Exception e){ + logger.error(newDoc == null ? "batchDoc is null" : newDoc.toString(), e); + return null; + } + + return newDoc; + } + + private void closeJsch(Logger logger, Session session, ChannelSftp channelSftp) { + if (channelSftp != null && channelSftp.isConnected()) { + try { + channelSftp.disconnect(); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } + if (session != null) { + try { + session.disconnect(); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + + } + } +} diff --git a/src/com/eactive/eai/adapter/ftp/FtpSupport.java b/src/com/eactive/eai/adapter/ftp/FtpSupport.java new file mode 100644 index 0000000..1fc14f5 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FtpSupport.java @@ -0,0 +1,110 @@ +package com.eactive.eai.adapter.ftp; + +import java.util.Properties; + +import com.eactive.eai.common.util.Logger; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; + +public class FtpSupport { + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + + /** + * 기관 프라퍼티 이름을 얻는다. + * @param batchDoc + * @return + */ + public static String getInstitutionPropertyName(BatchDoc batchDoc) { + return PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + } + + /** + * properties에서 propertyKey에 해당하는 정수 값을 얻는다. + * 값이 없거나 오류가 발생하면 defaultValue를 얻는다. + * + * @param properties 프라퍼티 + * @param propertyKey 키 + * @param defaultValue 기본값 + * @param logger 로거 + * @return 프러퍼티 값의 정수 또는 기본값 + */ + public static int getIntProperty(Properties properties, String propertyKey, int defaultValue, Logger logger) { + int returnValue = defaultValue; + String propertyValue = properties.getProperty(propertyKey); + + if (propertyValue != null) { + try { + returnValue = Integer.parseInt(propertyValue); + } catch(Exception e) { + logger.error("{"+"propertyKey"+"} = {"+"propertyValue"+"}" +"["+ e.getMessage() +"]"); + } + } + return returnValue; + } + + /** + * SFTP wild character *, ? 가 있는지 확인한다. + * @param filename 검사할 파일 이름 + * @return *, ?가 있으면 true + */ + public static boolean hasWildcard(String filename) { + return filename != null && (filename.contains("*") || filename.contains("?")); + } + + /** + * 기관 Properties 를 얻는다. + * @param batchDoc 배치 정보 + * @return 기관 Properties + */ + public static Properties getInstProperties(BatchDoc batchDoc) { + PropManager pmanager = PropManager.getInstance(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}"; + return pmanager.getProperties(propName); + } + + /** + * 파일 Properties 를 얻는다. + * @param batchDoc 배치 정보 + * @return 파일 Properties + */ + public static Properties getFileProperties(BatchDoc batchDoc) { + PropManager pmanager = PropManager.getInstance(); + + String propName = PROP_GROUP_NAME_PREFIX + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getBizCode() + "}"; + return pmanager.getProperties(propName); + } + + /** + * 자동, 수동 스케줄을 판단하고, 수동인 경우 baseDate를 바꾼다. + * + * @param batchDoc + * @return + */ + public static boolean isManaulRecive(BatchDoc batchDoc) { + boolean isManualReceive = false; + + String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String baseDate = DatetimeUtil.getCurrentDate(); + + if (reqFileName != null && reqFileName.length() > 8) { + if (DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8))) { + baseDate = reqFileName.substring(reqFileName.length() - 8); + isManualReceive = true; + } + } + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + return isManualReceive; + } +} diff --git a/src/com/eactive/eai/adapter/ftp/SFTPConstants.java b/src/com/eactive/eai/adapter/ftp/SFTPConstants.java new file mode 100644 index 0000000..f4e1073 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/SFTPConstants.java @@ -0,0 +1,51 @@ +package com.eactive.eai.adapter.ftp; + +/** + * SFTP 프로퍼티 관련 상수 + */ +public class SFTPConstants { + /** 인증 방법 1 = id, 2 = key 방식 */ + public static final String SFTP_AUTH_TYPE = "sftp.auth.type"; + /** 인증 방법 id */ + public static final String SFTP_AUTH_TYPE_ID = "1"; + /** 인증 방법 key */ + public static final String SFTP_AUTH_TYPE_KEY = "2"; + + /** YN 의 Y */ + public static final String YES = "y"; + /** YN 의 N */ + public static final String NO = "n"; + + /** 파일이름에 치환할 날짜, 시간 포맷. -, _ 지원 */ + public static final String DATE_PATTERN = "\\{([yMdHms\\-_]+)\\}"; + + // 파일경로 관련 기관 프로퍼티 + public static final String SEND_REMOTE_PATH = "send.remote.path"; + public static final String RECV_REMOTE_PATH = "recv.remote.path"; + + // 송신완료파일 생성관련 기관 프로퍼티 + public static final String SEND_COMPLETE_CREATE_YN = "send.complete.create.yn"; + public static final String SEND_COMPLETE_FILE_EXT = "send.complete.file.ext"; + + // 파일 프러퍼티 + /** 접수일자 날짜 조정 */ + public static final String FILE_RECV_ADD_YEAR = "file.recv.add.year"; + public static final String FILE_RECV_ADD_MONTH = "file.recv.add.month"; + public static final String FILE_RECV_ADD_DAY = "file.recv.add.day"; + + /** 기본 수신 폴더에 파일 별 경로 추가. 파일접수일자 포함 */ + public static final String FILE_RECV_ADD_PATH = "file.recv.add.path"; + /** 자동 수신할 파일이름 패턴(*.gz) */ + public static final String FILE_RECV_AUTO_FILENAME = "file.recv.auto.filename"; + /** 스케줄 수신 파일 이름 */ + public static final String FILE_RECV_MANUAL_FILENAME = "file.recv.manual.filename"; + + /** 큐에서 가져오는 최대 갯수. 없으면 하나만 전송 */ + public static final String SEND_MAX_ITERATION = "send.max.iteration"; + + public final static String PHASECODE_NORMAL_END = "END"; + + private SFTPConstants() { + // no construct + } +} diff --git a/src/com/eactive/eai/adapter/ftp/Transfer.java b/src/com/eactive/eai/adapter/ftp/Transfer.java new file mode 100644 index 0000000..a8a54c5 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/Transfer.java @@ -0,0 +1,289 @@ +package com.eactive.eai.adapter.ftp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPReply; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.util.Logger; + + +//public abstract class Transfer extends Thread implements SocketService { +public abstract class Transfer{ + + //리모트 전송 프라퍼티 정보 + public static final String DIRECTION_SEND = "송신"; //DB에 입력되는 값 + public static final String DIRECTION_RECEIVE = "수신"; //DB에 입력되는 값 + + public static final String SEND_SCRIPT_PATH = "script.send"; //VAN 송신 쉘스크립트 경로 + public static final String RECV_SCRIPT_PATH = "script.recv"; //VAN 수신 쉘스크립트 경로 + public static final String SEND_TITLE = "send.title"; //VAN 송신 TITLE + public static final String RECV_TITLE = "recv.title"; //VAN 송신 TITLE + public static final String ORG_ID = "org.id"; //상대방 ID + + //sftp 20220713 + protected static final String CONNECTION_TIMEOUT = "connection.timeout"; + protected static final String READ_TIMEOUT = "read.timeout"; + protected static final String BADNWIDTH = "io.bandwidth"; + + protected long firstActivity; + protected long lastActivity; + + protected Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + protected String scriptErrorMsg = ""; + protected String scriptOutputMsg = ""; + protected FTPClient ftpClient = null; + + /** 인증 방법 1 = id, 2 = key 방식 */ + public static final String AUTH_TYPE = "sftp.auth.type"; + public static final String AUTH_TYPE_ID = "1"; + public static final String AUTH_TYPE_KEY = "2"; + + //protected static EAIBatchMessageDocument batchDoc; + + public static void sendFileByEvent(BatchDoc batchDoc) throws Exception { + transferFileByEvent(DIRECTION_SEND, batchDoc); + } + + public static void recvFileByEvent(BatchDoc batchDoc) throws Exception { + transferFileByEvent(DIRECTION_RECEIVE, batchDoc); + } + //------------------------------------------------------------------------------------------- + // + //------------------------------------------------------------------------------------------- + public static void transferFileByEvent(String sendRecvType, BatchDoc batchDoc) throws Exception { + Logger logger = (Logger) batchDoc.getLogger(Logger.LOGGER_ADAPTER); + + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ Event 송수신 시작......"); + + //파라미터 체크 + if (!sendRecvType.equals(DIRECTION_SEND) && !sendRecvType.equals(DIRECTION_RECEIVE)) throw new Exception("{송수신구분} 파라미터 오류"); + + String protocol = batchDoc.getBatchMsg().getHeader().getRuleCode(); + + String className = Transfer.class.getName(); + className = className.substring(0, className.lastIndexOf('.')+1) + protocol; +// logger.debug("[Transfer]className-->" + className + "<--"); + @SuppressWarnings("rawtypes") + Class cl = Class.forName(className); + Transfer transfer = (Transfer)cl.newInstance(); + + //--------------------------------------------------------------------- + // 파일 송수신 수행 + transfer.transferFile(sendRecvType, batchDoc); + + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ VAN사 모듈 송수신 완료."); + } + + public void transferFile( String sendRecvType, BatchDoc batchDoc) throws Exception { + logger = (Logger) batchDoc.getLogger(Logger.LOGGER_ADAPTER); + + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ 파일 송수신 수행 시작......"); + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ⓟ 송수신구분 : ["+ sendRecvType +"] (송신: EAI→VAN사, 수신: VAN사→EAI)"); + + try { + if (sendRecvType.equals(DIRECTION_SEND)) { +//// ================================================================= +//// 송신 (EAI -> VAN) +//// ================================================================= + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ 파일 송신..."); + sendFile(batchDoc); + } else if (sendRecvType.equals(DIRECTION_RECEIVE)) { +// ================================================================= +// 수신 (VAN -> EAI) +// ================================================================= + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ 파일 수신..."); + recvFile(batchDoc); + } + } catch (Exception ex) { + throw new Exception("FTP 모듈 이용한 파일 송수신 실패!\n caused by..."+ ex.toString()); + } + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ 파일 송수신 수행 완료."); + +} + + protected void runSystemScript(String[] command) throws Exception { + + String cmdLine = command[0]; + for ( int inx=1; inx < command.length; inx++) + cmdLine += " " + command[inx]; + logger.info("[VAN송수신] [Runtime.Exec] ▶ System Command Runtime 수행 시작..."); + logger.info("[VAN송수신] [Runtime.Exec] ⓟ Command : ["+ cmdLine +"]"); + + //1. System Shell 명령어를 Runtime 으로 실행 + Process process = Runtime.getRuntime().exec(command); + + //2. Runtime 실행 결과 저장 + BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorLine = null; + StringBuffer errorBuffer = new StringBuffer(); + try { + while ((errorLine = errorReader.readLine()) != null) { + if (errorBuffer.length() > 0) errorBuffer.append("\n"); + errorBuffer.append(errorLine); + logger.debug("[VAN송수신] [Runtime.Exec] stderr> "+ errorLine); + } + } catch (Exception e) { + logger.error( e.getMessage(), e ); + } + + BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String outputLine = null; + StringBuffer outputBuffer = new StringBuffer(); + + try { + while ((outputLine = outputReader.readLine()) != null) { + if (outputBuffer.length() > 0) outputBuffer.append("\n"); + outputBuffer.append(outputLine); + logger.debug("[VAN송수신] [Runtime.Exec] stdout> "+ outputLine); + } + } catch (Exception e) { + logger.error( e.getMessage(), e ); + } + + int exitVal = process.waitFor(); + + scriptErrorMsg = errorBuffer.toString(); + scriptOutputMsg = outputBuffer.toString(); + + logger.info("[VAN송수신] [Runtime.Exec] ☞ Exit Value : "+ exitVal); + logger.info("[VAN송수신] [Runtime.Exec] ▶ System Command Runtime 수행 완료."); + + String errMsg = "Runtime.Exec 으로 실행한 Command exit value ("+ exitVal +") 가 정상이 아닙니다. \n" + + "(Command : "+ cmdLine +")\n" + + "(STDOUT : "+ scriptErrorMsg +"\n" + + "(STDERR : "+ scriptOutputMsg ; + if (exitVal != 0) throw new Exception(errMsg); + } + + protected void connect(String ipaddress, int port) throws Exception { + + try { + + if (port < 1) { + logger.warn("[com.eactive.eai.adapter.ftp.Transfer]해당 서버["+ port +"] 에 연결할 FTP 포트번호가 주어지지 않았습니다. 디폴트 포트번호 '21' 을 설정합니다."); + port = 21; + } + logger.info("[com.eactive.eai.adapter.ftp.Transfer]▶ FTP 서버 연결 시도... " + ipaddress + ":" + port); + + + if (ftpClient!=null && ftpClient.isConnected()) { + logger.info("[com.eactive.eai.adapter.ftp.Transfer]▶ 해당 FTP 서버에 이미 연결되어 있습니다."); + return; + } + + ftpClient = new FTPClient(); + ftpClient.setControlEncoding("EUC-KR"); + ftpClient.connect(ipaddress, port); + + int reply = ftpClient.getReplyCode(); + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ☞ 응답코드 : "+ reply); + + if (!FTPReply.isPositiveCompletion(reply)) { + try { + logger.error("[com.eactive.eai.adapter.ftp.Transfer] FTP 서버 연결에 실패하였습니다."); + ftpClient.disconnect(); + + } catch (Exception ex) { + logger.error("[com.eactive.eai.adapter.ftp.Transfer] FTP 서버 연결에 실패후 에러 발생하였습니다.", ex); + } + throw new Exception("FTP 연결 응답코드("+ reply +") 가 비정상입니다."); + } + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ FTP 서버에 연결되었습니다."); + + } catch (Exception ex) { + String errMsg = "FTP 연결 오류!\n caused by..."+ ex.toString(); + logger.error(errMsg, ex); + throw new Exception(errMsg); + } + } + + //------------------------------------------------------------------------------------------- + // + //------------------------------------------------------------------------------------------- + public void disconnect() { + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ FTP 서버 연결 해제 시도..."); + try { + if (ftpClient!=null && ftpClient.isConnected()) ftpClient.disconnect(); + logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ FTP 서버 연결이 해제 되었습니다."); + } catch (Exception ex) { + logger.error( ex.getMessage(), ex); + } + } + + public abstract void sendFile( BatchDoc batchDoc) throws Exception; + + public abstract void recvFile( BatchDoc batchDoc ) throws Exception; + + //파일 송수신 시 파일의 헤더, 트레일러 값을 배치메시지에 설정 + public void setFileHeaderAndTrailer(BatchDoc batchDoc, File f) { + + //파일이 존재하지 않거나 디렉토리면 리턴 + if (f == null || !f.exists() || f.isDirectory()) { + logger.info( "["+ (f==null? "": f.getAbsolutePath()) +"]: 파일이 존재하지 않거나 디렉토리입니다. 파일헤더,트레일러 설정안함."); + return; + } + + FileInputStream fin = null; + try { + long fileHeaderSize = 500; //파일헤더 로그 디폴트 사이즈 + long fileTrailerSize = 500; //파일트레일러 로그 디폴트 사이즈 + BatchJobInfoVO jobInfo = DirInfoManager.getInstance().getFileInfo(batchDoc.getBatchMsg().getHeader().getJobCode()); + if (jobInfo != null) { + fileHeaderSize = jobInfo.getFileHeaderLogSize(); + fileTrailerSize = jobInfo.getFileTrailerLogSize(); + } + + if (fileHeaderSize == 0 && fileTrailerSize == 0) return; + + fin = new FileInputStream(f); + long fileSize = f.length(); + + //DB값, 파일사이즈, 4000Byte(로그저장 varchar 최대값) 중 최소값 설정 + fileHeaderSize = Math.min(Math.min(fileHeaderSize , fileSize), 4000L); + fileTrailerSize = Math.min(Math.min(fileTrailerSize, fileSize), 4000L); + + byte[] bufHeader = new byte[(int)fileHeaderSize ]; + byte[] bufTrailer = new byte[(int)fileTrailerSize]; + int readSize = 0; + + //파일 헤더 값 READ + if (fileHeaderSize > 0) { + readSize = fin.read(bufHeader, 0, bufHeader.length); + } + + //파일 트레일러 값 READ + if (fileTrailerSize > 0 && readSize >= 0 && readSize <= fileSize) { + int overlapSize = 0; //헤더와 트레일러의 겹치는 Byte 사이즈 + long skipSize = (fileSize - readSize) - fileTrailerSize; + + if (skipSize > 0) { //헤더와 트레일러가 겹치지 않음 -> 트레일러까지 위치 이동 + fin.skip(skipSize); + + } else if (skipSize < 0) { //헤더와 트레일러가 겹침 -> 오버랩핑되는 헤더의 뒷부분을 트레일러의 앞부분으로 카피 + overlapSize = Math.abs((int)skipSize); + System.arraycopy(bufHeader, readSize - overlapSize, bufTrailer, 0, overlapSize); + } + if (readSize < fileSize) { + readSize = fin.read(bufTrailer, overlapSize, bufTrailer.length - overlapSize); + } + } + + batchDoc.getBatchMsg().setFileHeader(new String(bufHeader)); + batchDoc.getBatchMsg().setFileTrailer(new String(bufTrailer)); + + } catch (Exception ex) { + logger.error( "★★★★★ 파일내용 헤더, 트레일러 DB로그 설정시 오류 발생 !! ★★★★★", ex); + } finally { + try { if (fin != null) fin.close(); } catch (Exception e) {} + } + } + +} diff --git a/src/com/eactive/eai/adapter/listener/AdapterException.java b/src/com/eactive/eai/adapter/listener/AdapterException.java new file mode 100644 index 0000000..e1b321b --- /dev/null +++ b/src/com/eactive/eai/adapter/listener/AdapterException.java @@ -0,0 +1,43 @@ +package com.eactive.eai.adapter.listener; + +/** +* 1. 기능 : Adapter 통신 시 예외처리를 위한 Exception +* 2. 처리 개요 : +* * - Adapter 예외처리 +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : TestCall +* @since :JDK v1.4.2 +*/ +public class AdapterException extends Exception +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : Default 생성자 함수 + * 2. 처리 개요 : + * - Default 생성자 함수 + * 3. 주의사항 + * + **/ + public AdapterException() { + super("AdapterException is occured."); + } + + /** + * 1. 기능 : Exception 발생 원인을 저장하는 생성자 함수 + * 2. 처리 개요 : + * - Exception 발생 원인을 저장하는 생성자 함수 + * 3. 주의사항 + * + *@param msg Exception 발생 원인 + **/ + public AdapterException(String msg) { + super(msg); + } +} diff --git a/src/com/eactive/eai/adapter/listener/AdapterListener.java b/src/com/eactive/eai/adapter/listener/AdapterListener.java new file mode 100644 index 0000000..6974ca7 --- /dev/null +++ b/src/com/eactive/eai/adapter/listener/AdapterListener.java @@ -0,0 +1,46 @@ +package com.eactive.eai.adapter.listener; + +import com.eactive.eai.adapter.AdapterVO; + +/** + * 1. 기능 : Adapter start 및 stop 작업을 위한 Interface + * 2. 처리 개요 : + * - Adapter start + * - Adapter stop + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public interface AdapterListener +{ + /** + * 1. 기능 : 어댑터 정보를 저장하는 setter method + * 2. 처리 개요 : + * - 어댑터 정보를 저장한다. + * 3. 주의사항 + * + * @param info 어댑터 정보 VO + **/ + public void setAdapterInfo(AdapterVO info); + + /** + * 1. 기능 : Adapter start + * 2. 처리 개요 : + * - 해당 어댑터를 시작한다. + * 3. 주의사항 + * + **/ + public void start() throws AdapterException; + + /** + * 1. 기능 : Adapter stop + * 2. 처리 개요 : + * - 해당 어댑터를 중지한다. + * 3. 주의사항 + * + **/ + public void stop() throws AdapterException; +} diff --git a/src/com/eactive/eai/adapter/listener/AdapterListenerSupport.java b/src/com/eactive/eai/adapter/listener/AdapterListenerSupport.java new file mode 100644 index 0000000..b251c29 --- /dev/null +++ b/src/com/eactive/eai/adapter/listener/AdapterListenerSupport.java @@ -0,0 +1,64 @@ +package com.eactive.eai.adapter.listener; + +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : AdapterListener 인터페어스를 구현한 Base 클래스 +* 2. 처리 개요 : +* - AdapterListener 인터페이스의 구현을 위한 Base 클래스 +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : AdapterListener, AdapterManager +* @since :JDK v1.4.2 +*/ +public class AdapterListenerSupport implements AdapterListener +{ + /** + * default logger + */ + protected Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + /** + * 어댑터 정보 + */ + protected AdapterVO info; + + /** + * 1. 기능 : 어댑터 정보를 저장하는 setter method + * 2. 처리 개요 : + * - 어댑터 정보를 저장한다. + * 3. 주의사항 + * + * @param info 어댑터 정보 VO + **/ + public void setAdapterInfo(AdapterVO info) { + this.info = info; + } + + /** + * 1. 기능 : Adapter start + * 2. 처리 개요 : + * - 해당 어댑터를 시작한다. + * 3. 주의사항 + * + **/ + public void start() throws AdapterException { + if(logger.isDebugEnabled()){ + logger.debug("[AdapterListener] It is started. - "+info); + } + } + + /** + * 1. 기능 : Adapter stop + * 2. 처리 개요 : + * - 해당 어댑터를 중지한다. + * 3. 주의사항 + * + **/ + public void stop() throws AdapterException { + + } +} diff --git a/src/com/eactive/eai/adapter/socket/SocketAdapter.java b/src/com/eactive/eai/adapter/socket/SocketAdapter.java new file mode 100644 index 0000000..8f26cf3 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/SocketAdapter.java @@ -0,0 +1,62 @@ +package com.eactive.eai.adapter.socket; + +import com.eactive.eai.adapter.WLIDefaultAdapter; +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.service.OutboundControl; + +import java.util.Properties; + +/** +* 1. 기능 : Outbound Socket Adapter를 Access하기 위한 Java Class로 SocketControl에서 사용함. +* 2. 처리 개요 : +* * - OutboundControl Object를 통해 Outbound Socket을 통해 수동시스템과 Socket인터페이스를 위한 +* SocketAdapter Class +* 3. 주의사항 +* - Outbound Process에서 Outbound Socket의 Adapter Group Name에 대한 Property를 지정해야한다. +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class SocketAdapter extends WLIDefaultAdapter +{ + public static final String ADAPTER_GORUP_NAME="ADAPTER_GROUP_NAME"; + + static SocketAdapter socketAdapter = new SocketAdapter(); + + private SocketAdapter() {} + + public static SocketAdapter getInstance() + { + return socketAdapter; + } + + /** + * 1. 기능 : SocketAdapter의 실행 Method + * 2. 처리 개요 : + * - OutboundControl Object를 생성 후 요청된 메시지를 Assign한 후 CallService를 통해 + * 해당 Outbound Adapter Group의 Socket Connection을 얻은 후 메시지 송수신에 따른 결과를 + * 리턴한다. + * 3. 주의사항 + * + * @param prop WLI OutboundAdapter의 Property정보, SocketAdapter의 경우 ADAPTER_GROUP_NAME + * Property Key에 Adapter Group Name을 지정한다. + * @param message Outbound process에서 요청하는 메시지 Object로 byte[] 속성의 메시지여야한다. + * @return 결과메시지 Object로 SYNC 유형의 경우 byte[] 메시지가 리턴된다. + * @exception Exception + **/ + public Object execute(Properties prop, Object message) throws Exception { + OutboundControl control = new OutboundControl(); + String adapterGroupName = prop.getProperty(ADAPTER_GORUP_NAME); + control.setAdapterGroupName( adapterGroupName ); + + byte[] msg = null; + if ( message instanceof byte[]) { + msg = (byte[]) message; + } else { + throw new Exception( CommonLib.getMessage("BECEAIASO003") ); + } + + return control.callService( adapterGroupName, msg ); + } +} diff --git a/src/com/eactive/eai/adapter/socket/SocketAdapterListener.java b/src/com/eactive/eai/adapter/socket/SocketAdapterListener.java new file mode 100644 index 0000000..cfeec49 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/SocketAdapterListener.java @@ -0,0 +1,43 @@ +package com.eactive.eai.adapter.socket; + +import com.eactive.eai.adapter.listener.AdapterException; +import com.eactive.eai.adapter.listener.AdapterListenerSupport; +import com.eactive.eai.adapter.socket.config.*; + +/** + * 1. 기능 : Socket Adapter의 기동/중지를 위한 Adapter Listener로 FrameWork에서 SocketAdapter를 + * 중지/기동하기 위한 Socket Adapter Listener이다. + * 2. 처리 개요 : + * - SocketAdapterManager Instance를 얻은 후 해당 Adapter에 대한 Stop/Start 기능을 수행한다. + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ +public class SocketAdapterListener extends AdapterListenerSupport +{ + + public void start() throws AdapterException { + + SocketAdapterManager manager = SocketAdapterManager.getInstance(); + try { + manager.start(info); // info : AdapterVO 의 인스탄스 + } catch(Exception e) { + logger.error("[SocketAdapterListener] cannot start : " + e.getMessage(), e); + throw new AdapterException("SocketAdapter] start Error. - "+e.getMessage()); + } + } + + public void stop() throws AdapterException { + + SocketAdapterManager manager = SocketAdapterManager.getInstance(); + try { + if ( info == null ) throw new Exception(" AdapterVO가 NULL입니다."); + manager.stop(info); // info : AdapterVO의 인스탄스 + } catch(Exception e) { + logger.error("[SocketAdapterListener] cannot stop : " + e.getMessage(), e); + throw new AdapterException("SocketAdapter] stop Error. - "+e.getMessage()); + } + } +} diff --git a/src/com/eactive/eai/adapter/socket/common/CommonLib.java b/src/com/eactive/eai/adapter/socket/common/CommonLib.java new file mode 100644 index 0000000..006753f --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/common/CommonLib.java @@ -0,0 +1,280 @@ +package com.eactive.eai.adapter.socket.common; + +/** + * 1. 기능 : SocketAdapter에서 사용되는 공통기능 제공 + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.SimpleTimeZone; + +/** + * 송수신 메시지 SPEC. + * llzz + syncFlag + user data(전문포맷전체를 사용자 DATA로 본다.) + * - llzz(2BYTE/4BYTE) UNSIGNED INTEGER로 처리한다. -- ConfigurationContext에 저장 + * default는 4byte로 한다. + * - syncFlag - 'S' - R/R, 'A' - ASYNC, 'K' - ACK ONLY(이 경우, SEVER의 ACK를 받는다. + * - llzz+K[ACK|NACK] + * - user data,... + * + */ +public class CommonLib { + + public static final char SPACE = ' '; + + public static final char ZERO = '0'; + + public static final String EMPTY_STRING = ""; + + public static final String EMPTY_STRING_ARRAY[] = new String[0]; + + public static final int NEGOTIATING_PROTOCOL = 1; + + public static final int PROCESSING_PROTOCOL = 2; + + public static final byte[] SYNC_PROTOCOL_MESSAGE = "SYNC".getBytes(); + + public static final byte[] ASYNC_PROTOCOL_MESSAGE = "ASYN".getBytes(); + + public static final byte[] NACK_MESSAGE = "NACK PROTOCOL VIOLATION".getBytes(); + + public static final byte[] ACK_MESSAGE = "ACK".getBytes(); + + private static final SimpleDateFormat SDF_YYYYMMDDHHMMSSMS_DASH_CEMI_COL = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" ); + + /** + * BYTE ARRAY값을 HEXA STRING으로 변환하여 String을 리턴한다. + * @param abyte + * @return + */ + public static String byte2Hex(byte[] abyte) { + StringBuffer s = new StringBuffer(); + if (abyte == null) + return s.toString(); + for (int i = 0; i < abyte.length; i++) + s.append( Integer.toHexString((abyte[i] & 0xf0) >> 4).toUpperCase() ).append( Integer.toHexString(abyte[i] & 0xf).toUpperCase() ); + return s.toString(); + } + + /** + * HEXA String값을 BYTE ARRAY로 변환한다. + * @param s + * @return + */ + public static byte[] hex2Bytes(String s) { + byte abyte[] = new byte[s.length() / 2]; + for (int j = 0; j < abyte.length; j++) + abyte[j] = (byte) Integer.parseInt(s.substring(2 * j, 2 * j + 2), 16); + return abyte; + } + + public static java.lang.String getCurrentDateTime() { // YYYYMMDDHHMMSS + return (new SimpleDateFormat("yyyyMMddHHmmss")).format(new java.util.Date()); + } + + public static String getCurrentTime(long timeLong) + { + // 1hour(ms) = 60s * 60m * 1000ms + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + sdf.setTimeZone(new SimpleTimeZone(9 * 60 * 60 * 1000, "KST")); + return sdf.format(new java.util.Date(timeLong)); + } // end of getCurrentTime() + + public static String getDate(long timeLong) + { + // 1hour(ms) = 60s * 60m * 1000ms + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + sdf.setTimeZone(new SimpleTimeZone(9 * 60 * 60 * 1000, "KST")); + return sdf.format(new java.util.Date(timeLong)); + } // end of getCurrentTime() + + public static String getTimestamp() { + return (SDF_YYYYMMDDHHMMSSMS_DASH_CEMI_COL).format(new java.util.Date()); + } + + /** + * 주어진 String값을 주어진 길이많큼 Padding/Trim한다. + * @param svalue - 입력스트링 + * @param isRightJustify - true이면 RIGHT JUSTIFY, false이면 LEFT JUSTIFY + * @param padding - Padding 문자 + * @param length - 리턴할 스트링의 바이트수 + * @return 포맷팅된 String결과 + */ + public static String stringFormat(String svalue, boolean isRightJustify, char padding, int length) { + if ( svalue == null ) return svalue; + + StringBuffer mpad = new StringBuffer(); + StringBuffer fmtStr = new StringBuffer(); + + String tvalue = svalue; + int pLength = 0; + + pLength = length - svalue.getBytes().length; + + if (pLength == 0) + return svalue; + else if ( pLength < 0) { + byte[] abytes = null; + if (isRightJustify) { + abytes = (new String( svalue.getBytes(), -(pLength), length)).getBytes(); + } else { + abytes = (new String( svalue.getBytes(), 0, length)).getBytes(); + } + + if ( abytes.length == length ) { + return new String( abytes ); + } else { + tvalue = new String( abytes ); + pLength = length - tvalue.length(); + } + } + + for(int i =0; i < pLength ; i++) { + mpad.append( padding ); + } + + if ( isRightJustify ) { + return fmtStr.append(mpad).append(tvalue).toString(); + } else { + return fmtStr.append(tvalue).append(mpad).toString(); + } + } + + public static java.lang.String getFormatString(long value, int length) + { + DecimalFormat df = new DecimalFormat("000000000000000000"); + String fs = df.format( value ); + return fs.substring(fs.length() - length); + } + + public static java.lang.String getFormatString(int value, int length) + { + DecimalFormat df = new DecimalFormat("000000000000000000"); + String fs = df.format((long)value); + return fs.substring(fs.length() - length); + } + + /** + * 메시지 비교 + */ + public static boolean compare(byte[] source, byte[] target) { + if ( source.length != target.length ) return false; + + for ( int i=0; i < source.length; i++ ) { + if ( source[i] != target[i] ) return false; + } + return true; + } + + /** + * 송수신전문에 대한 DUMP를 프린트할 수 있는 포맷으로 변환하여 String Array로 리턴한다. + * @param bytes + * @return + */ + public static String[] makeDumpFormat(byte[] bytes) { + if (bytes == null || bytes.length == 0) + return CommonLib.EMPTY_STRING_ARRAY; + + String[] dumps = new String[bytes.length / 16 + ((bytes.length % 16) == 0 ? 4 : 5)]; + dumps[0] = "/==========.========================================..==================."; + dumps[1] = "| Offset | 0 1 2 3 4 5 6 7 8 9 A B C D E F || U S E R D A T A |"; + dumps[2] = "|----------+----------------------------------------||------------------|"; + dumps[dumps.length - 1] = "'=========='========================================''==================/"; + + int len = 0; + byte PERIOD = 0x2E; + char aChar = ' '; + boolean isDBCS = false; + boolean isHalfDBCS = false; + + for (int i = 3; i < dumps.length - 1; i++) { + len = ( ((bytes.length - (i - 2) * 16) >= 0) ? 16 : (bytes.length - (i - 3)*16) ); + byte[] buf = new byte[len]; + System.arraycopy( bytes, (i-3)*16, buf, 0, len ); + StringBuffer strBuf = new StringBuffer(); + //dumps[i] = EMPTY_STRING; + + strBuf.append("| ").append( stringFormat( new String( Integer.toHexString((i-3)*16) ).toUpperCase(), true, ZERO, 8) ).append(" | "); + + String hexStr = byte2Hex( buf ); + StringBuffer fmtStr = new StringBuffer(); + + int k = hexStr.length()/8 + ((hexStr.length() % 8) == 0 ? 0 : 1); + for (int j=0; j < k ; j++) { + int l = ((hexStr.length() - (j+1)*8 ) >= 0 ? 8 : (hexStr.length() - j*8 )); + fmtStr.append( hexStr.substring(j*8, j*8 + l ) ).append(" "); + } + + strBuf.append( stringFormat(fmtStr.toString(), false, SPACE, 39) ).append("|| "); + + k = 0; + // 한글 및 특수문자가 깨지게 표시되는 것 을 방지한다. + for ( int j=0; j < len; j++) { + if ( buf[j] >> 7 == 0 ) { + // Single Byte Character + if ( isDBCS ) { + isDBCS = false; + if ( k != 0 && ((k % 2) == 1 )) { + buf[j - 1] = PERIOD; + } + } + aChar = (char)buf[j]; + if ( Character.isWhitespace( aChar ) || Character.isISOControl( aChar ) || buf[j] == 0 ) { + buf[j] = PERIOD; + } + continue; + } + // Double Bytes Character. + if ( !isDBCS ) isDBCS = true; + if ( j == 0 && isHalfDBCS ) { + buf[j] = PERIOD; + isDBCS = false; + continue; + } + // To check the DBCS pairwise + k++; + } + if ( isDBCS && ((k%2)==1) ) { + buf[ len -1 ] = PERIOD; + isHalfDBCS = true; + } else { + isHalfDBCS = false; + } + + dumps[i] = strBuf.append( stringFormat(new String(buf), false, SPACE, 16) ).append(" |").toString(); + } + return dumps; + } + + public static String getDumpMessage( byte[] message ) { + String[] dumpMsg = makeDumpFormat( message ); + StringBuffer dump = new StringBuffer(); + dump.append("\n"); + for(int i=0; i < dumpMsg.length; i++) { + dump.append( dumpMsg[i] ).append("\n"); + } + + return dump.toString(); + } + + public static String getMessage(String msgCode, String[] params) { + return ExceptionUtil.getErrorCode(msgCode, params); + } + + public static String getMessage(String msgCode) { + return ExceptionUtil.getErrorCode(msgCode); + } + + public static String getDebugMessage(String msgCode, String[] params) { + return ExceptionUtil.getErrorCode(msgCode, params); + } + +} diff --git a/src/com/eactive/eai/adapter/socket/common/DiagLogger.java b/src/com/eactive/eai/adapter/socket/common/DiagLogger.java new file mode 100644 index 0000000..4d781ef --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/common/DiagLogger.java @@ -0,0 +1,9 @@ +package com.eactive.eai.adapter.socket.common; + +public class DiagLogger { + + public static final int DEFAULT = 0; // WARNING, ERROR, FATAL인 경우 에러로깅 + public static final int INFO = 1; // INFO 수준의 LOGGING을 수행한다. + public static final int DEBUG = 2; // DEBUG 수준의 송수신전문 및 에러 메인처리내용의 모든수준의 로깅을 수행한다. + +} diff --git a/src/com/eactive/eai/adapter/socket/common/SocketAdapterException.java b/src/com/eactive/eai/adapter/socket/common/SocketAdapterException.java new file mode 100644 index 0000000..71b5f16 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/common/SocketAdapterException.java @@ -0,0 +1,116 @@ +/* + * Created on 2005. 2. 26. + * + */ +package com.eactive.eai.adapter.socket.common; + +/** + * @author janet + * + */ +public class SocketAdapterException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public static final int UNEXPECTED_TERMINATION = 1; + + public static final int REMOTE_HOST_DISCONNECTED = 2; + + public static final int INTERNAL_ERROR = 5; + + public static final int CHANNEL_FAILURE = 6; + + public static final int CANCELLED_CONNECTION = 8; + + public static final int CONNECT_FAILED = 10; + + public static final int CONNECTION_CLOSED = 12; + + public static final int AGENT_ERROR = 13; + + public static final int SESSION_STREAM_ERROR = 15; + + int reason; + + Throwable cause; + + /** + * Create an exception with the given description and reason. + * @param msg + * @param reason + */ + + public SocketAdapterException(String msg, int reason) { + this(msg, reason, null); + } + + /** + * Create an exception with the given cause and reason. + * @param reason + * @param cause + */ + public SocketAdapterException(int reason, Throwable cause) { + this(null, reason, cause); + } + + /** + * Create an exception with the given description and cause. The reason given + * will be INTERNAL_ERROR. + * + * @param msg + * @param cause + */ + public SocketAdapterException(String msg, Throwable cause) { + this(msg, INTERNAL_ERROR, cause); + } + + /** + * + * @param msg + */ + public SocketAdapterException(String msg) { + this(msg, INTERNAL_ERROR, null); + } + + /** + * Create an exception by providing the cause of the error. This constructor + * sets the reason to INTERNAL_ERROR. + * @param cause + */ + public SocketAdapterException(Throwable cause) { + this("An unexpected exception was caught: " + cause.getMessage(), cause); + } + + /** + * Create an exception with the given description cause, reason. + * @param msg + * @param reason + * @param cause + */ + public SocketAdapterException(String msg, int reason, Throwable cause) { + super(msg); + this.cause = cause; + this.reason = reason; + } + + /** + * Get the reason for the exception + * @return + */ + public int getReason() { + return reason; + } + + /** + * If an INTERNAL_ERROR reason is given this method MAY return the cause of + * the error. + * @return + */ + public Throwable getCause() { + return cause; + } + +} diff --git a/src/com/eactive/eai/adapter/socket/common/StopWatch.java b/src/com/eactive/eai/adapter/socket/common/StopWatch.java new file mode 100644 index 0000000..f75f49e --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/common/StopWatch.java @@ -0,0 +1,68 @@ +package com.eactive.eai.adapter.socket.common; + +public class StopWatch { + private long startTime = -1; + private long stopTime = -1; + + public StopWatch() { + } + + public void start() { + this.startTime = System.currentTimeMillis(); + } + + public void stop() { + this.stopTime = System.currentTimeMillis(); + } + + public void reset() { + this.startTime = -1; + this.stopTime = -1; + } + + public long getTime() { + if (stopTime == -1) { + return (System.currentTimeMillis() - this.startTime); + } else { + return (this.stopTime - this.startTime); + } + } + + public String toString() { + return getTimeString(); + } + + protected String getTimeString() { + int HIM = 60 * 60 * 1000; + int MIM = 60 * 1000; + int hours; + int minutes; + int seconds; + int milliseconds; + long time = getTime(); + hours = (int) (time / HIM); + time = time - (hours * HIM); + minutes = (int) (time / MIM); + time = time - (minutes * MIM); + seconds = (int) (time / 1000); + time = time - (seconds * 1000); + milliseconds = (int) time; + + return hours + "h:" + minutes + "m:" + seconds + "s:" + milliseconds + "ms"; + } + + static public void main(String[] strs) { + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + + try { + Thread.currentThread(); + Thread.sleep(1500); + } catch (InterruptedException ie) { + // ignore + ; + } + + stopWatch.stop(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/socket/config/ConfigurationContext.java b/src/com/eactive/eai/adapter/socket/config/ConfigurationContext.java new file mode 100644 index 0000000..5baec22 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/config/ConfigurationContext.java @@ -0,0 +1,473 @@ +package com.eactive.eai.adapter.socket.config; + +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.common.DiagLogger; + +import java.io.Serializable; + + +/** +* 1. 기능 : SocketAdapter의 구성정보 및 속성을 나타내는 Object Class +* 2. 처리 개요 : +* - 구성정보의 DEFAULT값을 갖고 있으며, 각 속성에 대한 getter/setter 기능을 제공한다. +* 3. 주의사항 +* - 해당 Property의 기본속성값을 확인하여, 해당 Property의 속성지정을 생략시 어떤 값을 갖는지 +* 확인하여야한다. +* @param +* @return +* @exception +**/ + +public class ConfigurationContext implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + public static final String INBOUND_SOCKET = "INBOUND"; + public static final String OUTBOUND_SOCKET = "OUTBOUND"; + public static final String IOBOUND_SOCKET = "IOBOUND"; + + public static final String SERVER_SOCKET = "SERVER"; + public static final String CLIENT_SOCKET = "CLIENT"; + public static final String ADMIN_SOCKET = "ADMIN"; + + public static final String SYNC_MODE = "SYNC"; + public static final String ASYNC_MODE = "ASYN"; + + public static final String TRUE_FLAG = "Y"; + public static final String FALSE_FLAG = "N"; + + /** + * Configuration properties + */ + private String adapterGroupName = ""; // SOCKET ADADAPTER GROUP NAME + private String adapterName = ""; // SOCKET ADAPTER 구성 이름 + + private String boundUsage = INBOUND_SOCKET; // INBOUND | OUTBOUND + private String socketType = SERVER_SOCKET; // SERVER | CLIENT + + private String hostName = "localhost"; // BIND할 서버의 호스트명 또는 IP ADDRESS + private int portNumber = 0; // BIND할 서버의 PORT NUMBER + + private String localHostName = ""; // Client Socket Type에 한하여 설정 + private int localPortNumber = 0; // Client Socket Type으로 원격서버와 연결시 BIND할localPortNumber + + private int connLimitPerIp = 0; // SERVER TYPE SOCKET의 경우 REMOTE의 특정 IP별 CONNECTION 수를 제한시키는 것 + private int maxConnection = 1; // 원격시스템과 Socket Connection 최대허용 수 + // Server Socket의 경우 - Server Listening port로 접속허용할 최대 수 + // Client Socket의 경우 - Remote Host의 지정 포트로 연결할 최대 Connection 수 + + private int defaultSession = 2; // Inbound의 Default Session 유지 수 + private int maxSession = 5; // INBOUND의 경우한하여 의미가 있음. + // Socket Adapter의 N개의 Connection에 대해 WLI session을 연결할 최대 수 (실행 Thread Pool의 Session수) + + private int timeout = 0; // SOCKET READ TIMEOUT값 설정 + // 송수신 메시지의 Socket Read Timeout값을 설정 (단위 : 초) [timeout으로 변경] + + private int sessionTimeout = 10; // 10초의 Session Timeout Time + + private String responseType = SYNC_MODE; // SYNC_MODE, ASYNC_MODE + private String socketReuse = TRUE_FLAG; // "Y" - Socket Connection reuse + // "N" - try to connect each transaction + + private int llFieldIndex = 0; // LL필드 시작 Index + private int llFieldLength = 2; // LL필드길이 2-unsigned short, 4 ~ 8 Numeric Char + private String ackProtocol = FALSE_FLAG; // ACK송수신 여부 -- Client Type의 Socket에 적용되며, 서버는 Protocol에 의해 작동판단... + + private String bwkClsCd = ""; // 업무구분코드 + private boolean responseOnly = false; // 어댑터가 응답전용모드인지 여부 + private boolean usePollMsg = false; // polling 여부 + + private int traceLevel = DiagLogger.DEFAULT; // 추적관리 수준 - 0, 1, 2 + private String description = ""; // Socket Adapter Configuration에 대한 용도설명 + // + private boolean started = true; + + + private AdapterVO adapterInfo = null; + + public void setAdapterVO(AdapterVO info) { + this.adapterInfo = info; + } + + public AdapterVO getAdapterVO() { + return this.adapterInfo; + } + + + public ConfigurationContext() { + } + + public ConfigurationContext(String adapterGroupName, String adapterName, String boundUsage, String socketType, + String hostName, int portNumber ) { + + this.adapterGroupName = adapterGroupName; + this.adapterName = adapterName; + this.boundUsage = boundUsage; + this.socketType = socketType; + this.hostName = hostName; + this.portNumber = portNumber; + + } + + /** + * @return Returns the adapterGroupName. + */ + public String getAdapterGroupName() { + return adapterGroupName; + } + /** + * @param adapterGroupName The adapterGroupName to set. + */ + public void setAdapterGroupName(String adapterGroupName) { + this.adapterGroupName = adapterGroupName; + } + /** + * @return Returns the defaultSession. + */ + public int getDefaultSession() { + return defaultSession; + } + /** + * @param defaultSession The defaultSession to set. + */ + public void setDefaultSession( + int defaultSession) { + this.defaultSession = defaultSession; + } + + /** + * @return Returns the socketReuse. + */ + public String getSocketReuse() { + return socketReuse; + } + /** + * @return Returns the connLimitPerIp. + */ + public int getConnLimitPerIp() { + return connLimitPerIp; + } + /** + * @param connLimitPerIp The connLimitPerIp to set. + */ + public void setConnLimitPerIp(int connLimitPerIp) { + this.connLimitPerIp = connLimitPerIp; + } + /** + * @return Returns the adapterName. + */ + public String getAdapterName() { + return adapterName; + } + /** + * @param adapterName The adapterName to set. + */ + public void setAdapterName(String adapterName) { + this.adapterName = adapterName; + } + /** + * @return Returns the bizCode. + */ + public String getBwkClsCd() { + return bwkClsCd; + } + /** + * @param bizCode The bizCode to set. + */ + public void setBwkClsCd(String bizCode) { + this.bwkClsCd = bizCode; + } + + public String getAckProtocol() { + return ackProtocol; + } + /** + * @param bizCode The bizCode to set. + */ + public void setAckProtocol(String ackProtocol) { + this.ackProtocol = ackProtocol; + } + + /** + * @return Returns the boundUsage. + */ + public String getBoundUsage() { + return boundUsage; + } + /** + * @param boundUsage The boundUsage to set. + */ + public void setBoundUsage(String boundUsage) { + this.boundUsage = boundUsage; + } + /** + * @return Returns the description. + */ + public String getDescription() { + return description; + } + /** + * @param description The description to set. + */ + public void setDescription(String description) { + this.description = description; + } + /** + * @return Returns the hostName. + */ + public String getHostName() { + return hostName; + } + /** + * @param hostName The hostName to set. + */ + public void setHostName(String hostName) { + this.hostName = hostName; + } + /** + * @return Returns the llFieldLength. + */ + public int getLlFieldIndex() { + return llFieldIndex; + } + /** + * @param llFieldLength The llFieldLength to set. + */ + public void setLlFieldIndex(int llFieldIndex) { + this.llFieldIndex = llFieldIndex; + } + /** + * @return Returns the llFieldLength. + */ + public int getLlFieldLength() { + return llFieldLength; + } + /** + * @param llFieldLength The llFieldLength to set. + */ + public void setLlFieldLength(int llFieldLength) { + this.llFieldLength = llFieldLength; + } + /** + * @return Returns the localHostName. + */ + public String getLocalHostName() { + return localHostName; + } + /** + * @param localHostName The localHostName to set. + */ + public void setLocalHostName(String localHostName) { + this.localHostName = localHostName; + } + /** + * @return Returns the localPortNumber. + */ + public int getLocalPortNumber() { + return localPortNumber; + } + /** + * @param localPortNumber The localPortNumber to set. + */ + public void setLocalPortNumber(int localPortNumber) { + this.localPortNumber = localPortNumber; + } + + /** + * @return Returns the maxConnection. + */ + public int getMaxConnection() { + return maxConnection; + } + + /** + * @param maxConnection The maxConnection to set. + */ + public void setMaxConnection( + int maxConnection) { + this.maxConnection = maxConnection; + } + + /** + * @return Returns the maxSession. + */ + public int getMaxSession() { + return maxSession; + } + /** + * @param maxSession The maxSession to set. + */ + public void setMaxSession(int maxSession) { + this.maxSession = maxSession; + } + /** + * @return Returns the portNumber. + */ + public int getPortNumber() { + return portNumber; + } + /** + * @param portNumber The portNumber to set. + */ + public void setPortNumber(int portNumber) { + this.portNumber = portNumber; + } + /** + * @return Returns the readTimeout. + */ + public int getTimeout() { + return timeout; + } + /** + * @param readTimeout The readTimeout to set. + */ + public void setTimeout(int readTimeout) { + this.timeout = readTimeout; + } + + public int getSessionTimeout() { + return sessionTimeout; + } + /** + * @param readTimeout The readTimeout to set. + */ + public void setSessionTimeout(int sessionTimeout) { + this.sessionTimeout = sessionTimeout; + } + + /** + * @return Returns the responseType. + */ + public String getResponseType() { + return responseType; + } + + public boolean isSyncMode() { + return ( this.responseType.equals( SYNC_MODE ) ) ; + } + + public boolean isAckProtocol() { + return ( this.ackProtocol.equals( TRUE_FLAG ) ) ; + } + + public boolean isResponseOnly() { + return responseOnly; + } + + public void setResponseOnly(boolean responseOnly) { + this.responseOnly = responseOnly; + } + + public boolean isUsePollMsg() { + return usePollMsg; + } + + public void setUsePollMsg(boolean usePollMsg) { + this.usePollMsg = usePollMsg; + } + + /** + * @param responseType The responseType to set. + */ + public void setResponseType(String responseType) { + this.responseType = responseType; + } + /** + * @return Returns the socketReuse. + */ + public boolean isSocketReuse() { + return socketReuse.equals( TRUE_FLAG ); + } + /** + * @param socketReuse The socketReuse to set. + */ + public void setSocketReuse(boolean socketReuse) { + this.socketReuse = (socketReuse ? TRUE_FLAG : FALSE_FLAG); + } + + public void setSocketReuse(String socketReuse) { + this.socketReuse = socketReuse; + } + + + /** + * @return Returns the socketType. + */ + public String getSocketType() { + return socketType; + } + /** + * @param socketType The socketType to set. + */ + public void setSocketType(String socketType) { + this.socketType = socketType; + } + /** + * @return Returns the traceLevel. + */ + public int getTraceLevel() { + return traceLevel; + } + /** + * @param traceLevel The traceLevel to set. + */ + public void setTraceLevel(int traceLevel) { + this.traceLevel = traceLevel; + } + + public void setStarted(boolean on) { + this.started = on; + } + + public boolean isStarted() { + return this.started; + } + + public String toString() { + StringBuffer strBuff = new StringBuffer(); + strBuff.append( this.adapterName ).append( " [Adapter의 등록정보입니다. : " ); + strBuff.append(" adapter.group.name=").append( this.adapterGroupName ).append(","); + strBuff.append(" bound.usage=").append( this.boundUsage ).append(","); + strBuff.append(" socket.type=").append( this.socketType ).append(","); + strBuff.append(" host.name=").append( this.hostName ).append(","); + strBuff.append(" port.number=").append( this.portNumber).append(","); + strBuff.append(" local.host.name=").append( this.localHostName ).append(","); + strBuff.append(" local.port.number=").append( this.localPortNumber ).append(","); + if ( this.connLimitPerIp > 0 ) { + strBuff.append(" connection.limit.per.ip=").append( this.connLimitPerIp ).append(","); + } else { + strBuff.append(" connection.limit.per.ip=0(UNLIMITED)" ).append(","); + } + + if ( this.maxConnection > 0 ) { + strBuff.append(" max.connection=").append( this.maxConnection ).append(","); + } else { + strBuff.append(" max.connection=0(UNLIMITED)" ).append(","); + } + + strBuff.append(" default.session=").append( this.defaultSession ).append(","); + strBuff.append(" max.session=").append( this.maxSession ).append(","); + strBuff.append(" timeout=").append( this.timeout ).append(","); + strBuff.append(" session.timeout=").append( this.sessionTimeout ).append(","); + strBuff.append(" response.type=").append( this.responseType ).append(","); + strBuff.append(" socket.reuse=").append( this.socketReuse ).append(","); + strBuff.append(" ll.field.index=").append( this.llFieldIndex ).append(","); + strBuff.append(" ll.field.length=").append( this.llFieldLength ).append(","); + strBuff.append(" ack.support=").append( this.ackProtocol ).append(","); + strBuff.append(" business.work.class.code=").append( this.bwkClsCd ).append(","); + + if ( this.traceLevel == 2 ) { + strBuff.append(" trace.level=").append( this.traceLevel ).append("(DEBUG)").append(","); + } else if ( this.traceLevel == 1 ) { + strBuff.append(" trace.level=").append( this.traceLevel ).append("(INFO)").append(","); + } else { + strBuff.append(" trace.level=").append( this.traceLevel ).append("(ERROR)").append(","); + } + + strBuff.append(" description=").append(this.description).append("]"); + + return strBuff.toString(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/socket/config/Keys.java b/src/com/eactive/eai/adapter/socket/config/Keys.java new file mode 100644 index 0000000..360a047 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/config/Keys.java @@ -0,0 +1,51 @@ +package com.eactive.eai.adapter.socket.config; + +/** +* 1. 기능 : Socket Adapter의 구성정보를 지정하기 위한 property의 KEY값을 나타낸다. +* 2. 처리 개요 : +* - +* 3. 주의사항 +* +* @param +* @return +* @exception +**/ +public interface Keys { + + /** + * Socket Adapter의 Adapter Group명을 나타낸는 KEY값 + */ + public static final String ADAPTER_GROUP_NAME = "adapter.group.name"; + + /** + * Socket Adapter가 INBOUND/OUTBOUND/IOBOUND용인지 나타내기위한 KEY값 + */ + public static final String BOUND_USAGE = "bound.usage"; + + /** + * Socket Adapter의 SOCKET유형이 [SERVER|CLIENT]에 구분을 나타 + */ + public static final String SOCKET_TYPE = "socket.type"; + public static final String HOST_NAME = "host.name"; + public static final String PORT_NUMBER = "port.number"; + public static final String LOCAL_HOST_NAME = "local.host.name"; + public static final String LOCAL_PORT_NUMBER = "local.port.number"; + public static final String CONN_LIMIT_PER_IP = "connection.limit.per.ip"; + public static final String MAX_CONNECTION = "max.connection"; + public static final String DEFAULT_SESSION = "default.session"; + public static final String MAX_SESSION = "max.session"; + public static final String TIMEOUT = "timeout"; + public static final String SESSION_TIMEOUT = "session.timeout"; + public static final String RESPONSE_TYPE = "response.type"; + public static final String SOCKET_REUSE = "socket.reuse"; + public static final String LL_FIELD_INDEX = "ll.field.index"; + public static final String LL_FIELD_LENGTH = "ll.field.length"; + public static final String ACK_PROTOCOL = "ack.support"; + public static final String WORK_CLASS_CODE = "business.work.class.code"; + public static final String TRACE_LEVEL = "trace.level"; + public static final String DESCRIPTION = "description"; + public static final String RESPONSE_ONLY = "response.olny"; + public static final String USE_POLLING = "use.polling"; + + +} diff --git a/src/com/eactive/eai/adapter/socket/config/RequestDescriptor.java b/src/com/eactive/eai/adapter/socket/config/RequestDescriptor.java new file mode 100644 index 0000000..4f22f4a --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/config/RequestDescriptor.java @@ -0,0 +1,65 @@ +package com.eactive.eai.adapter.socket.config; + +import com.eactive.eai.adapter.RequestDispatcher; +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.service.InboundControl; +import com.eactive.eai.adapter.socket.service.SocketLogManager; +import com.eactive.eai.common.util.Logger; + +public class RequestDescriptor { + + private InboundControl control; + + private static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); + + public RequestDescriptor(InboundControl control) { + this.control = control; + } + + public void request() { + + logger.debug("################ RequestDescriptor.request() 호출됨."); + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + //BatchDoc batchMsgDoc = null; + + try { + //Properties prop = new Properties(); + ConfigurationContext ctx = SocketAdapterManager.getInstance().getContext( control.getAdapterName() ); + + if ( ctx.getDescription().equals("ECHO SESSION") ) { + //수신 메시지와 동일하게 설정 + control.setResponse( control.getRequest() ); + + //SocketAdapter adapter = SocketAdapter.getInstance(); + //prop.put( SocketAdapter.ADAPTER_GORUP_NAME, "SOCKET_Test_AIX_OUT"); + //resp = (byte[]) adapter.execute( prop, control.getRequest() ); + //control.setResponse( resp ); + + } else { + //================================================================================================ + //Client Request 메시지 처리 요청 + RequestDispatcher reqDispacher = RequestDispatcher.getRequestDispatcher( control.getAdapterGroupName() ); + reqDispacher.handle(control); + //batchMsgDoc = reqDispacher.handle(control); + + //control.setResponse( batchMsgDoc.getEAIBatchMessage().getSendTelegram().getBytes() ); + //control.setBatchMsgDoc(batchMsgDoc); + //================================================================================================ + } + + } catch ( Throwable e ) { + control.setLastError( e ); + String errMsg = CommonLib.getMessage("BECEAIASI001", new String[] { e.getMessage() } ); + errLogger.error( errMsg, e ); + errLogger.error( CommonLib.getDumpMessage( control.getRequest() )); + + control.setResponse( errMsg.getBytes() ); + } + + logger.debug("################ RequestDescriptor.request() 종료. (수행 시간: "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec)"); + } +} diff --git a/src/com/eactive/eai/adapter/socket/config/SocketAdapterManager.java b/src/com/eactive/eai/adapter/socket/config/SocketAdapterManager.java new file mode 100644 index 0000000..d3bac8b --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/config/SocketAdapterManager.java @@ -0,0 +1,1522 @@ +package com.eactive.eai.adapter.socket.config; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; +import java.util.Timer; + +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.service.AdminTable; +import com.eactive.eai.adapter.socket.service.ConnectionManager; +import com.eactive.eai.adapter.socket.service.InboundClient; +import com.eactive.eai.adapter.socket.service.OutboundChannelManager; +import com.eactive.eai.adapter.socket.service.RecoveryManager; +import com.eactive.eai.adapter.socket.service.SessionChannel; +import com.eactive.eai.adapter.socket.service.SessionManager; +import com.eactive.eai.adapter.socket.service.SessionService; +import com.eactive.eai.adapter.socket.service.SocketLogManager; +import com.eactive.eai.adapter.socket.service.SocketServer; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + +public class SocketAdapterManager { + + public static long CONNECTION_CHECK_CYCLE = 60 * 1000L; // every 60 sec. + public static long RECOVERY_CHECK_CYCLE = 15 * 1000L; // every 15 sec. + public static long UNUSED_CONNECTION_TIMEOUT = 0L; // 10 * 60 * 1000L; + // 10분간 미상용시 Connection Close; + // 0으로 설정시 강제적으로 미사용 소켓을 CLOSE하지 않음.... + private static SocketAdapterManager instance = new SocketAdapterManager(); + private Logger logger = SocketLogManager.getInstance().getLogger(); + + private HashMap> stateTable; // Connection 정보를 AdapterGroup별 I/O BOUND별 Socket reference를 같는다. + private LinkedList errorTable; // Client Socket의 Connection 에러에 대한 내용을 관리한다. + private HashMap>sessionTable;// Inbound Session관리를 위한 Table + + private ConnectionManager connManager; + private RecoveryManager recoverManager; + private SessionManager sessionManager; + + private Timer connTimer; + private Timer recoverTimer; + + private boolean started; + // TO Support STOP & START by Adapter + // KEY = AdapterName, Value=AdminTable for stop/start + private HashMap adminTableMap; + // KEY = RemoteIP:Port, Value=SocketService Object; + private HashMapcontrolMap; + + private SocketAdapterManager() { + stateTable = new HashMap>(); + errorTable = new LinkedList(); + sessionTable = new HashMap>(); + adminTableMap = new HashMap(); + controlMap = new HashMap(); + + connManager = null; + recoverManager = null; + sessionManager = SessionManager.getInstance(); + started = false; + } + + public static SocketAdapterManager getInstance() { + return instance; + } + + public void start() { + started = true; + } + + public HashMap> getAllSessions() { + return this.stateTable; + } + + private void startManagers() { + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA001") ); + } + + // Connection Manager starting... + stateTable.clear(); + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA002") ); + } + this.connManager = new ConnectionManager( stateTable ); + this.connTimer = new Timer(); + this.connTimer.schedule( this.connManager, CONNECTION_CHECK_CYCLE, CONNECTION_CHECK_CYCLE ); + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA003") ); + } + + // Recovery Manager starting... + errorTable.clear(); + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA004") ); + } + this.recoverManager = new RecoveryManager( errorTable ); + this.recoverTimer = new Timer(); + this.recoverTimer.schedule( this.recoverManager, RECOVERY_CHECK_CYCLE, RECOVERY_CHECK_CYCLE ); + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA005") ); + } + + // Session Manager starting... + this.sessionManager.removeAll(); + this.sessionTable.clear(); + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA006") ); + } + // OUTBOUND Connection POOL CLEAR + OutboundChannelManager.getInstance().removeAll(); + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA007") ); + } + + started = true; + + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA008") ); + } + //this.logger.info("Socket adapter manager started..."); + } + + // return SocketService Object list.... + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Object[] getAllAdminList() { + // AdminTable Object list + Object[] adminTables = adminTableMap.values().toArray(); + LinkedList serviceList = new LinkedList(); + + for ( int i = 0; i < adminTables.length; i++ ) { + AdminTable adminTable = (AdminTable) adminTables[i]; + Object[] services = adminTable.getConnections(); + for ( int j=0; j < services.length; j++ ) { + serviceList.add( services[j] ); + } + } + + return serviceList.toArray(); + } + + private Object[] getAdminList( String adapterName ) { + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + if ( adminTable == null ) return null; + return adminTable.getConnections(); + } + + // DEUBG LEVEL 조정 또는 MAXCONNECTION MAXSESSION 수 조정용... + public ConfigurationContext getContext( String adapterName ) { + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + if ( adminTable == null ) return null; + return adminTable.getContext(); + } + + public void setContext( ConfigurationContext context ) { + AdminTable adminTable = (AdminTable) adminTableMap.get( context.getAdapterName() ); + if ( adminTable == null ) return; + adminTable.setContext( context ); + } + + // Group별 Session수 조정을 위한 인터페이스 + public String adjustSession( String adapterName, int newSessions ) throws Exception { + StringBuffer strBuff = new StringBuffer(); + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + + if ( adminTable == null ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA001", new String[] { adapterName } )); + return strBuff.toString(); + } + + String adapterGroupName = adminTable.getAdapterGroupName(); + ConfigurationContext ctx = adminTable.getContext(); + if ( ctx.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET ) ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA002", new String[] { adapterName } )); + return strBuff.toString(); + } + + SessionChannel sChannel = SessionManager.getInstance().getChannel( adapterGroupName ); + + if ( sChannel == null ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA019", new String[] { adapterName } )); + return strBuff.toString(); + } + + int oldSessions = sChannel.getMaxNumOfSessions(); + + // Sessions수는 Max값에 대해 큰값만 지원한다. + if ( oldSessions > newSessions ) { + strBuff.append( CommonLib.getMessage("BWCEAIMSA001", new String[] { adapterName, Integer.toString(oldSessions) } )); + return strBuff.toString(); + } else if ( oldSessions == newSessions ) { + strBuff.append( CommonLib.getMessage("BICEAIMSA009", new String[] { adapterName, Integer.toString(oldSessions) } )); + return strBuff.toString(); + } + // + sChannel.setMaxNumOfSessions( newSessions ); + for ( int i = oldSessions+1; i <= newSessions; i++ ) { +// SessionService session = new SessionService( adapterGroupName, true, i, adminTable.getContext().getTraceLevel() ); + SessionService session = new SessionService( adapterGroupName, true, i ); + session.start(); + } + strBuff.append( CommonLib.getMessage("BICEAIMSA010", new String[] { adapterName, Integer.toString(oldSessions), Integer.toString(newSessions) } )); + return strBuff.toString(); + } + + // Connection 수 조정을 위한 작업 + public String adjustConnection( String adapterName, int newConnections ) { + StringBuffer strBuff = new StringBuffer(); + + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + if ( adminTable == null ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA003", new String[] { adapterName } )); + return strBuff.toString(); + } + //String key = adminTable.getAdapterGroupName(); + // Connection수는 Max값에 대해 큰값만 지원한다. + ConfigurationContext context = adminTable.getContext(); + int oldConnections = context.getMaxConnection(); + + if ( oldConnections > newConnections ) { + strBuff.append( CommonLib.getMessage("BWCEAIMSA002", new String[] { adapterName, Integer.toString(oldConnections) } )); + return strBuff.toString(); + } + + context.setMaxConnection( newConnections ); + + if ( context.getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) { + strBuff.append( CommonLib.getMessage("BICEAIMSA011", new String[] { adapterName, Integer.toString(oldConnections), Integer.toString(newConnections) } )); + return strBuff.toString(); + } + + // Client Socket Type에 대해서 Connection 수를 증가 시킨다.... + // INBOUND & OUTBOUND + + if ( context.getBoundUsage().equals( ConfigurationContext.INBOUND_SOCKET ) ) { + // CLIENT TYPE의 Socket에 대해 MAX CONNECTION 수 만큼 미리 CONNECTION을 맺는다. + for ( int j=oldConnections; j < newConnections; j++ ) { + InboundClient aService = new InboundClient( context ); + adminTable.addConnection( aService ); + aService.start(); + } + // OUTBOUND SOCKET CONFIGURATION +// } else if ( context.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET ) ) { +// // CLIENT TYPE의 Socket에 대해 MAX CONNECTION 수 만큼 미리 CONNECTION을 맺는다. +// for ( int j=oldConnections; j < newConnections; j++ ) { +// OutboundClient aService = new OutboundClient( context ); +// adminTable.addConnection( aService ); +// aService.start(); +// } + } // End of Connection 증가... + + strBuff.append( CommonLib.getMessage("BICEAIMSA011", new String[] { adapterName, Integer.toString(oldConnections), Integer.toString(newConnections) } )); + return strBuff.toString(); + } + + public long getTimeout( String adapterGroupName ) { + long timeout = 3000L; // default Timeout Time + + try { + LinkedList list = stateTable.get( adapterGroupName ); + if ( list == null ) { + return timeout; + } + + if ( list.size() == 0 ) return timeout; + + SocketService cInfo = list.getFirst(); + + timeout = cInfo.getContext().getSessionTimeout() * 1000L; + } catch( Exception e ) {} + + return timeout; + } + + /** + * Adapter Name별 Socket Adapter starting... + * + */ + public String start( String adapterGroupName, String adapterName ) { + StringBuffer strBuff = new StringBuffer(); + AdapterManager aMgr = AdapterManager.getInstance(); + AdapterVO config = aMgr.getAdapterVO(adapterGroupName, adapterName); + + if ( config == null ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA004", new String[] { adapterGroupName, adapterName } )); + return strBuff.toString(); + } + + if ( config.isStarted() ) { + strBuff.append( CommonLib.getMessage("BWCEAIMSA003", new String[] { adapterGroupName, adapterName } )); + return strBuff.toString(); + } + + try { + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA012", new String[] { adapterGroupName, adapterName } )); + } + + config.start(); + + strBuff.append( CommonLib.getMessage("BICEAIMSA013", new String[] { adapterGroupName, adapterName } )); + if(logger.isInfoEnabled()){ + this.logger.info( strBuff.toString() ); + } + + } catch( Exception e ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA020", new String[] { adapterGroupName, adapterName, e.getMessage() } )); + + logger.error( strBuff.toString(), e ); + } + + return strBuff.toString(); + } + + public String stop( String adapterGroupName, String adapterName ) { + StringBuffer strBuff = new StringBuffer(); + AdapterManager aMgr = AdapterManager.getInstance(); + AdapterVO config = aMgr.getAdapterVO(adapterGroupName, adapterName); + + if ( config == null ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA005", new String[] { adapterGroupName, adapterName } )); + return strBuff.toString(); + } + if ( !config.isStarted() ) { + strBuff.append( CommonLib.getMessage("BWCEAIMSA004", new String[] { adapterGroupName, adapterName } )); + return strBuff.toString(); + } + + try { + if(logger.isInfoEnabled()){ + this.logger.info( CommonLib.getMessage("BICEAIMSA014", new String[] { adapterGroupName, adapterName } )); + } + config.stop(); + strBuff.append( CommonLib.getMessage("BICEAIMSA015", new String[] { adapterGroupName, adapterName } )); + if(logger.isInfoEnabled()){ + this.logger.info( strBuff.toString() ); + } + + } catch( Exception e ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA021", new String[] { adapterGroupName, adapterName, e.getMessage() } )); + + logger.error( strBuff.toString(), e ); + } + + return strBuff.toString(); + } + + // START A SOCKET ADAPTER CONFIGURATION + public void start(AdapterVO config) throws Exception { + + ConfigurationContext context = null; + + if ( !started ) { + startManagers(); + } + + try { + // Configuration Context 생성 + logger.info("createContext start : GROUP[" + config.getAdapterGroupName() + "] -> ADAPTER[" + config.getName() + "]"); + context = createContext(config); + logger.info("createContext end ==============================================================="); + config.setContext(context); + + // adminTable CONFIGURATION + String key = context.getAdapterGroupName(); + String adapterName = context.getAdapterName(); + AdminTable adminTable = adminTableMap.get( adapterName ); + + //socket START 설정 + context.setStarted( true ); + + if ( adminTable == null ) { + adminTable = new AdminTable( key, adapterName, context ); + adminTableMap.put( adapterName, adminTable ); + } else { + adminTable.setContext( context ); + adminTable.initialize(); + } + + Object o = stateTable.get( key ); + if ( o == null ) { + stateTable.put( key, new LinkedList() ); + if ( !context.getSocketType().equals( ConfigurationContext.ADMIN_SOCKET ) ) { + sessionTable.put( key, new LinkedList() ); + } + } + + // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + // INBOUND 또는 IOBOUND SOCKET 인 경우 기동처리 + // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + if ( context.getBoundUsage().equals( ConfigurationContext.INBOUND_SOCKET ) + || context.getBoundUsage().equals( ConfigurationContext.IOBOUND_SOCKET ) ) { + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + // SERVER TYPE의 Socket인 경우 + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + if ( context.getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) { + SocketServer aService = new SocketServer( context ); + + // SessionChannel : 세션 정보 관리 + if ( !this.sessionManager.hasChannel( key ) ) { + // Create a new SessionChannel : 세션의 기본 세션수, 최대세션수, 세션 타임아웃 + SessionChannel channel = new SessionChannel( context.getDefaultSession(), context.getMaxSession(), context.getSessionTimeout() ); + // SessionManager에 해당 AdapterGroup의 Session정보 등록 + sessionManager.start( key, channel ); + + // Session Starting..... + for ( int k=0; k < context.getMaxSession(); k++ ) { +// SessionService session = new SessionService( context.getAdapterGroupName(), true, (k+1), context.getTraceLevel() ); + SessionService session = new SessionService( context.getAdapterGroupName(), true, (k+1)); + // 쓰레드가 시작되면, SocketAdapterManager를 통해 SessionManager의 pool 에 add 한다. + session.start(); + } + } + + // adminTable의 connections 벡터에 서버소켓 스레드 인스탄스 등록.. + adminTable.addConnection( aService ); + + aService.start(); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + // CLIENT TYPE의 Socket인 경우 + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + } else if( context.getSocketType().equals( ConfigurationContext.CLIENT_SOCKET ) ) { + // CLIENT TYPE의 Socket에 대해 MAX CONNECTION 수 만큼 미리 CONNECTION을 맺는다. + for ( int j=0; j < context.getMaxConnection(); j++ ) { + // 해당 그룹의 SessionChannel을 가지고 있는가 ? + if ( !this.sessionManager.hasChannel( key ) ) { + // Create a new SessionChannel + SessionChannel channel = new SessionChannel( context.getDefaultSession(), context.getMaxSession(), context.getSessionTimeout() ); + // SessionManager에 해당 AdapterGroup의 Session정보 등록 + sessionManager.start( key, channel ); + // Session Starting..... + for ( int k=0; k < context.getMaxSession(); k++ ) { +// SessionService session = new SessionService( context.getAdapterGroupName(), true, (k+1), context.getTraceLevel() ); + SessionService session = new SessionService( context.getAdapterGroupName(), true, (k+1)); + session.start(); + } + } + if ( context.getBoundUsage().equals( ConfigurationContext.INBOUND_SOCKET ) ) { + InboundClient aService = null; + aService = new InboundClient( context ); + adminTable.addConnection( aService ); + aService.start(); +// } else { +// if ( !OutboundChannelManager.getInstance().hasChannel( key )) { +// OutboundChannel channel = new OutboundChannel(context.getSessionTimeout()*1000); +// OutboundChannelManager.getInstance().addConnectionGroup( key, channel ); +// } +// ReaderClient aService = new ReaderClient( context ); +// adminTable.addConnection( aService ); +// aService.start(); + } + } // end of for + } else { + // AdminServer로 변경필요... + SocketServer aService = new SocketServer( context ); + adminTable.addConnection( aService ); + aService.start(); + } + + // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + // OUTBOUND 인 경우 기동처리 + // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + } else if ( context.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET ) ) { + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + // SERVER TYPE의 Socket인 경우 + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + if ( context.getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) { + SocketServer aService = new SocketServer( context ); + adminTable.addConnection( aService ); + aService.start(); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + // CLIENT TYPE의 Socket인 경우 + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + } else { +// // CLIENT TYPE의 Socket에 대해 MAX CONNECTION 수 만큼 미리 CONNECTION을 맺는다. +// for ( int j=0; j < context.getMaxConnection(); j++ ) { +// OutboundClient aService = null; +// aService = new OutboundClient( context ); +// if ( !OutboundChannelManager.getInstance().hasChannel( key )) { +// OutboundChannel channel = new OutboundChannel(context.getSessionTimeout()*1000); +// OutboundChannelManager.getInstance().addConnectionGroup( key, channel ); +// } +// adminTable.addConnection( aService ); +// aService.start(); +// } + } + } + + } catch ( Exception e ) { + String errMsg = CommonLib.getMessage("BECEAIMSA020", new String[]{ config.getAdapterGroupName(), config.getName(), e.getMessage()}); + logger.error( errMsg, e ); + throw new Exception( errMsg ); + } + } + + public void changeAdapterStatus(SocketService service, boolean on) { + AdapterManager aMgr = AdapterManager.getInstance(); + AdapterVO config = aMgr.getAdapterVO(service.getContext().getAdapterGroupName(), service.getContext().getAdapterName()); + if ( config == null ) return; + + config.setStatus( on ); + } + + private ConfigurationContext createContext( AdapterVO config ) throws Exception { + return createContext( config, false ); + } + + private ConfigurationContext createContext( AdapterVO config, boolean flag ) throws Exception { + + ConfigurationContext context = new ConfigurationContext(); + context.setAdapterVO(config); + + context.setAdapterGroupName( config.getAdapterGroupName() ); + context.setAdapterName( config.getName() ); + + PropManager manager = PropManager.getInstance(); + Properties prop = manager.getProperties( config.getPropGroupName() ); + String errMsg = null; + + if ( prop.getProperty(Keys.ADAPTER_GROUP_NAME) == null ) { + errMsg = CommonLib.getMessage("BECEAIMSA016", new String[]{"Socket Adapter그룹명", "adapter.group.name"} ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + + context.setBoundUsage( prop.getProperty(Keys.BOUND_USAGE, context.getBoundUsage()) ); + if ( "INBOUND,OUTBOUND,IOBOUND".indexOf(context.getBoundUsage()) < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.BOUND_USAGE, context.getBoundUsage(), "[ INBOUND | OUTBOUND | IOBOUND ]" } ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + + context.setSocketType( prop.getProperty(Keys.SOCKET_TYPE, context.getSocketType()) ); + if ( "SERVER, CLIENT, ADMIN".indexOf( context.getSocketType() ) < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.SOCKET_TYPE, context.getSocketType(), "[ SERVER | CLIENT | ADMIN ]" } ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + + + //==================================================================================================================== + //서버 IP 설정 + //TSEAIBJ05 테이블의 'SysAnsrLnkgIP' 필드값 사용시 (TSEAIBJ05에 정보가 등록 안된경우 Property 정보 사용) + if (config.getBatchServerIP() != null) { + context.setHostName( config.getBatchServerIP().trim() ); + + } else { + context.setHostName( prop.getProperty(Keys.HOST_NAME, context.getHostName()) ); + } + + //서버 PortNo 설정 + //TSEAIBJ05 테이블의 'LnkgPortInfoName' 필드값 사용시 (TSEAIBJ05에 정보가 등록 안된경우 Property 정보 사용) + if (config.getBatchServerPortNo() != null) { + context.setPortNumber( Integer.parseInt( config.getBatchServerPortNo().trim() ) ); + + } else { + context.setPortNumber( Integer.parseInt( prop.getProperty(Keys.PORT_NUMBER, Integer.toString(context.getPortNumber()))) ); + } + //==================================================================================================================== + + + context.setLocalHostName( prop.getProperty(Keys.LOCAL_HOST_NAME, context.getLocalHostName()) ); + context.setLocalPortNumber( Integer.parseInt( prop.getProperty(Keys.LOCAL_PORT_NUMBER, Integer.toString(context.getLocalPortNumber() )) )); + + try { + if ( context.getSocketType().equals( ConfigurationContext.CLIENT_SOCKET ) ) { + context.setMaxConnection( Integer.parseInt( prop.getProperty(Keys.MAX_CONNECTION, Integer.toString( context.getMaxConnection())))); + if ( context.getMaxConnection() <= 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.MAX_CONNECTION, Integer.toString( context.getMaxConnection() ), "[ CLIENT TYPE의 Sokcet인 경우 0 보다 크다 ]" } ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + + } else { + context.setMaxConnection( Integer.parseInt( prop.getProperty(Keys.MAX_CONNECTION, "0")) ); + if ( context.getMaxConnection() < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.MAX_CONNECTION, Integer.toString( context.getMaxConnection() ), "[ SERVER TYPE의 Socket인 경우 0 보다 크거나 같다 ]" } ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + } + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.MAX_CONNECTION, prop.getProperty(Keys.MAX_CONNECTION), "[ 0 보다 크거나 같다 ]" } ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + + try { + context.setConnLimitPerIp( Integer.parseInt( prop.getProperty(Keys.CONN_LIMIT_PER_IP, Integer.toString( context.getConnLimitPerIp()))) ); + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.CONN_LIMIT_PER_IP, prop.getProperty(Keys.DEFAULT_SESSION), "[ 0 보다 크거나 같다 ]" } ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + + try { + context.setDefaultSession( Integer.parseInt( prop.getProperty(Keys.DEFAULT_SESSION, Integer.toString( context.getDefaultSession())))); + if ( context.getDefaultSession() <= 0 && "INBOUND,IOBOUND".indexOf( context.getBoundUsage() ) >= 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.DEFAULT_SESSION, Integer.toString( context.getDefaultSession() ), "[ INBOUND/IOBOUND의 경우 0 보다 크다 ]" } ); + + logger.error( errMsg ); + + throw new Exception( errMsg ); + } + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.DEFAULT_SESSION, prop.getProperty(Keys.DEFAULT_SESSION), "[ 0 보다 크다 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + try { + context.setMaxSession( Integer.parseInt( prop.getProperty(Keys.MAX_SESSION, Integer.toString( context.getMaxSession())))); + if ( context.getMaxSession() <= 0 && "INBOUND,IOBOUND".indexOf( context.getBoundUsage() ) >= 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.MAX_SESSION, Integer.toString( context.getMaxSession() ), "[ INBOUND/IOBOUND의 경우 0 보다 크다 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.MAX_SESSION, prop.getProperty(Keys.MAX_SESSION), "[ 0 보다 크다 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + try { + context.setTimeout( Integer.parseInt( prop.getProperty(Keys.TIMEOUT, Integer.toString( context.getTimeout())))); + if ( context.getTimeout() < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.TIMEOUT, Integer.toString( context.getTimeout() ), "[ 0 보다 크거나 같다 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.TIMEOUT, prop.getProperty(Keys.TIMEOUT), "[ 0 보다 크거나 같다 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + try { + context.setSessionTimeout( Integer.parseInt( prop.getProperty(Keys.SESSION_TIMEOUT, Integer.toString( context.getSessionTimeout())))); + //if ( context.getSessionTimeout() < 1 ) { + // errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.SESSION_TIMEOUT, Integer.toString( context.getSessionTimeout() ), "[ 0 보다 크다 ]" } ); + // logger.error( errMsg ); + // throw new Exception( errMsg ); + //} + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.TIMEOUT, prop.getProperty(Keys.SESSION_TIMEOUT), "[ 0 보다 크다 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + context.setResponseType( prop.getProperty(Keys.RESPONSE_TYPE, context.getResponseType())); + if ( "SYNC,ASYN".indexOf(context.getResponseType()) < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.RESPONSE_TYPE, context.getResponseType(), "[ SYNC | ASYN ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + /* + if ( context.getBoundUsage().equals( ConfigurationContext.IOBOUND_SOCKET ) + && context.getResponseType().equals( ConfigurationContext.SYNC_MODE ) ) { + + errMsg = CommonLib.getMessage("BECEAIMSA018", new String[]{ context.getResponseType() } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + */ + + context.setSocketReuse( prop.getProperty(Keys.SOCKET_REUSE, context.getSocketReuse())); + if ( "Y,N".indexOf(context.getSocketReuse()) < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.SOCKET_REUSE, context.getSocketReuse(), "[ Y | N ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + try { + context.setLlFieldIndex( Integer.parseInt( prop.getProperty(Keys.LL_FIELD_INDEX, Integer.toString(context.getLlFieldIndex())))); + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.LL_FIELD_INDEX, prop.getProperty(Keys.LL_FIELD_INDEX), "[ 0 | 2 | 4 | 5 | 6 | 7 | 8 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + try { + context.setLlFieldLength( Integer.parseInt( prop.getProperty(Keys.LL_FIELD_LENGTH, Integer.toString(context.getLlFieldLength())))); + //if ( "0,2,4,5,6,7,8".indexOf( Integer.toString( context.getLlFieldLength() ) ) < 0 ) { + // errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.LL_FIELD_LENGTH, Integer.toString( context.getLlFieldLength() ), "[ 0 | 2 | 4 | 5 | 6 | 7 | 8 ]" } ); + // logger.error( errMsg ); + // throw new Exception( errMsg ); + //} + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.LL_FIELD_LENGTH, prop.getProperty(Keys.LL_FIELD_LENGTH), "[ 0 | 2 | 4 | 5 | 6 | 7 | 8 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + context.setAckProtocol( prop.getProperty(Keys.ACK_PROTOCOL, context.getAckProtocol())); + if ( "Y,N".indexOf(context.getAckProtocol()) < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.ACK_PROTOCOL, context.getAckProtocol(), "[ Y | N ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + context.setBwkClsCd( prop.getProperty(Keys.WORK_CLASS_CODE, context.getBwkClsCd())); + String strResponseOnly = prop.getProperty(Keys.RESPONSE_ONLY); + if ( strResponseOnly != null && "y,Y,yes,Yes,YES".indexOf(strResponseOnly) > -1 ){ + context.setResponseOnly(true); + } + + String strUsePoll = prop.getProperty(Keys.USE_POLLING); + if ( strUsePoll != null && "y,Y,yes,Yes,YES".indexOf(strUsePoll) > -1 ){ + context.setUsePollMsg(true); + } + + + + try { + context.setTraceLevel( Integer.parseInt( prop.getProperty(Keys.TRACE_LEVEL, Integer.toString(context.getTraceLevel())))); + if ( "0,1,2".indexOf( Integer.toString( context.getTraceLevel() ) ) < 0 ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.TRACE_LEVEL, Integer.toString( context.getTraceLevel() ), "[ 0 | 1 | 2 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + } catch( NumberFormatException e ) { + errMsg = CommonLib.getMessage("BECEAIMSA017", new String[]{Keys.TRACE_LEVEL, prop.getProperty(Keys.TRACE_LEVEL), "[ 0 | 1 | 2 ]" } ); + logger.error( errMsg ); + throw new Exception( errMsg ); + } + + context.setDescription( prop.getProperty(Keys.DESCRIPTION, context.getDescription())); + + if ( flag ) { + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA038", new String[]{ context.toString() })); + } + } + + return context; + } + + public String getConnectionInfo(String adapterGroupName ) { + StringBuffer strBuff = new StringBuffer(); + if ( adapterGroupName == null || adapterGroupName.equals("") ) { + Object[] groupName = stateTable.keySet().toArray(); + for ( int i=0; i < groupName.length; i++) { + strBuff.append( getGroupConnectionInfo( (String)groupName[i] )); + } + } else { + return getGroupConnectionInfo( adapterGroupName ); + } + return strBuff.toString(); + } + + // Adapter Connection Summary정보 리턴 + // 요약정보의 Start/Stop 정보를 표현한다. + public String getConnectionSummary() { + StringBuffer strBuff = new StringBuffer(); + AdapterManager adapterMgr = AdapterManager.getInstance(); + + // AdapterManager에서 전체 Adapter Group목록을 조회한다. + List allGroupList = adapterMgr.getAllAdapterGroupNames(); + if ( allGroupList == null ) { + return CommonLib.getMessage("BICEAIMSA038", new String[]{"어뎁터그룹정보가 없습니다."}); + } + + ArrayList netGroupList = new ArrayList(); + // 전체 Adapter Group에서 NET Adapter의 Group만을 추출한다.... + for ( int i=0; i < allGroupList.size(); i++ ) { + String netGroup = allGroupList.get( i ); + if ( adapterMgr.getAdapterGroupVO( netGroup ).getType().equals(com.eactive.eai.adapter.Keys.TYPE_NET) ) { + netGroupList.add( netGroup ); + } + } + if ( netGroupList.size() < 1 ) { + return CommonLib.getMessage("BICEAIMSA038", new String[]{"소켓 어뎁터그룹정보가 없습니다."}); + } + Collections.sort( netGroupList ); + + Object[] groupName = netGroupList.toArray(); + + for ( int i=0; i < groupName.length; i++) { + String grpInfo = getGroupConnectionInfo( (String)groupName[i] ); + + AdapterGroupVO adapterGroup = adapterMgr.getAdapterGroupVO( (String)groupName[i] ); + if ( adapterGroup == null ) continue; + String[] adapterNames = adapterGroup.getAdapterNames(); + if ( adapterNames == null ) continue; + + // Connection 목록이 없는 경우 + if ( grpInfo.indexOf("BECEAIMSA006") >= 0 || grpInfo.indexOf("BWCEAIMSA005") >= 0 ) { + for ( int j=0; j < adapterNames.length; j++ ) { + int maxConn = 0; + try { + //maxConn = createContext( adapterGroup.getAdapterVO( adapterNames[j] )).getMaxConnection(); + maxConn = this.getContext( adapterNames[j] ).getMaxConnection(); + } catch( Exception e ) { + continue; + } + strBuff.append( (String)groupName[i] ).append(",").append( adapterNames[j] ).append(","); + if ( maxConn == 0 ) { + strBuff.append( "UNLIMITED" ); + } else { + strBuff.append( maxConn ); + } + strBuff.append( ",0,0,0,"); + strBuff.append( adapterGroup.getAdapterVO(adapterNames[j]).isStarted() ); + strBuff.append("\n"); + } + continue; + } + + // Connection List를 갖고 있는 경우. + // some action .... + + // 그룹명을 포함한 Connection List + String[] gInfoList = grpInfo.split("\n"); + // 그룹명을 제외한 Connection List + String[] aInfoList = new String[ gInfoList.length ]; + + for ( int j=0; j < gInfoList.length; j++ ) { + try { + aInfoList[ j ] = gInfoList[j].split(",", 2)[1]; + } catch( Exception e ) {} + } + + // Adapter명별로 정렬 + Arrays.sort( aInfoList ); + + String tmpName = ""; + StringBuffer nameBuff = new StringBuffer(); + int sendCount = 0; + int recvCount = 0; + int connCount = 0; + + for ( int j =0; j < gInfoList.length; j++ ) { + if ( aInfoList[j] == null || aInfoList[j].equals("") ) continue; + + String [] aInfoBySocket = aInfoList[ j ].split(","); + if ( aInfoBySocket == null || aInfoBySocket.length < 12 ) continue; + + if ( !tmpName.equals( aInfoBySocket[0] ) && !tmpName.equals("") ) { + // 요약정보 생성 + int maxConn = 0; + try { + //maxConn = createContext( adapterGroup.getAdapterVO( tmpName )).getMaxConnection(); + maxConn = this.getContext( tmpName ).getMaxConnection(); + } catch( Exception e ) {} + + strBuff.append( groupName[i] ).append(","); + strBuff.append( tmpName ).append(","); + if ( maxConn == 0 ) { + strBuff.append( "UNLIMITED" ).append(","); + } else { + strBuff.append( maxConn ).append(","); + } + strBuff.append( connCount ).append(","); + strBuff.append( sendCount ).append(","); + strBuff.append( recvCount ).append(","); + strBuff.append( "true" ).append("\n"); + + nameBuff.append( tmpName ).append(","); + // 임시 값 초기화 + tmpName = aInfoBySocket[0]; + sendCount = 0; + recvCount = 0; + connCount = 0; + } + + tmpName = aInfoBySocket[0]; + + try { + sendCount += Integer.parseInt( aInfoBySocket[7] ); + recvCount += Integer.parseInt( aInfoBySocket[8] ); + } catch( Exception e ) {} + + if ( aInfoBySocket[9].equals("true") ) { + connCount += 1; + } + } + // 최종Adapter에 대한 정보 + if ( !tmpName.equals("") ) { + int maxConn = 0; + try { + // maxConn = createContext( adapterGroup.getAdapterVO( tmpName )).getMaxConnection(); + maxConn = this.getContext( tmpName ).getMaxConnection(); + } catch( Exception e ) {} + + strBuff.append( groupName[i] ).append(","); + strBuff.append( tmpName ).append(","); + if ( maxConn == 0 ) { + strBuff.append( "UNLIMITED" ).append(","); + } else { + strBuff.append( maxConn ).append(","); + } + strBuff.append( connCount ).append(","); + strBuff.append( sendCount ).append(","); + strBuff.append( recvCount ).append(","); + strBuff.append( "true" ).append("\n"); + nameBuff.append( tmpName ); + } + + // Adapter Group List에는 있으나, Connection List에 없는 Adapter정보 + for ( int k=0; k < adapterNames.length; k++ ) { + if ( nameBuff.toString().indexOf( adapterNames[k] ) >= 0 ) continue; + // + int maxConn = 0; + try { + maxConn = createContext( adapterGroup.getAdapterVO( adapterNames[k] )).getMaxConnection(); + } catch( Exception e ) { + continue; + } + strBuff.append( (String)groupName[i] ).append(",").append( adapterNames[k] ).append(","); + if ( maxConn == 0 ) { + strBuff.append( "UNLIMITED" ); + } else { + strBuff.append( maxConn ); + } + strBuff.append( ",0,0,0,"); + strBuff.append( adapterGroup.getAdapterVO(adapterNames[k]).isStarted() ); + strBuff.append("\n"); + } + } + + return strBuff.toString(); + } + + private String getGroupConnectionInfo(String adapterGroupName) { + StringBuffer strBuff = new StringBuffer(); + + LinkedList list = stateTable.get( adapterGroupName ); + if ( list == null ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA006", new String[]{ adapterGroupName } )).append("\n"); + return strBuff.toString(); + } + for (SocketService cInfo : list) { + strBuff.append( cInfo.toString() ).append("\n"); + } + +// Object[] x = list.toArray(); +// for( int i=0; i < x.length; i++ ) { +// SocketService cInfo = (SocketService) x[i]; +// } + + if ( list.size() == 0 ) { + strBuff.append( CommonLib.getMessage("BWCEAIMSA005", new String[]{ adapterGroupName } )).append("\n"); + } + + return strBuff.toString(); + } + public boolean isActiveAdapter(String adapterName) { + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + if ( adminTable == null ) return false; + return adminTable.getContext().isStarted(); + } + + public String getSessionInfo(String adapterGroupName ) { + if ( adapterGroupName == null || adapterGroupName.equals("") ) { + return SessionManager.getInstance().getSessionInfo(); + } else { + return SessionManager.getInstance().getSessionInfo( adapterGroupName ); + } + } + // STOP A SOCKET ADAPTER CONFIGURATION + public void stop( AdapterVO config ) throws Exception { + String adapterName = config.getName(); // AdapterName + Object[] controlList = getAdminList( adapterName ); + + if ( controlList == null ) { + String errMsg = CommonLib.getMessage("BWCEAIMSA004", new String[]{ config.getAdapterGroupName(), config.getName()}); + throw new Exception( errMsg ); + } + + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + adminTable.getContext().setStarted( false ); + + for ( int i=0; i < controlList.length; i++ ) { + SocketService service = (SocketService) controlList[i]; + removeConnection( service ); + adminTable.removeConnection( service ); + service.shutdown(); + } + + adminTable.initialize(); + //adminTableMap.remove( adminTable ); + } + + + public void stop() { + if ( !isStarted() ) return; + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA022") ); + } + + this.started = false; + + // CONNECTION MANAGER STOP + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA016") ); + } + this.connTimer.cancel(); + this.connTimer = null; + this.connManager = null; + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA017") ); + } + + // RECOVERY MANAGER STOP + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA018") ); + } + this.recoverTimer.cancel(); + this.recoverTimer = null; + this.recoverManager = null; + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA019") ); + } + + // SESSION MANAGER STOP + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA020") ); + } + + // SESSION TABLE 및 IDLE TABLE에서 해당 THREAD모두 STOP + this.removeAllSession(); + this.sessionManager.stop(); + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA021") ); + } + + OutboundChannelManager.getInstance().removeAll(); + + controlMap.clear(); + + if ( getAllAdminList().length < 1 ) { + stateTable.clear(); + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA023") ); + } + return; + } + + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA024") ); + } + + Object[] dList = getAllAdminList(); + for ( int i=0; i < dList.length; i++) { + SocketService aService = (SocketService)dList[i]; + aService.shutdown(); + AdminTable adminTable = (AdminTable) adminTableMap.get( aService.getContext().getAdapterName() ); + if ( adminTable != null ) { + adminTable.removeConnection( aService ); + } + } + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA025") ); + + logger.info( CommonLib.getMessage("BICEAIMSA023") ); + } + } + + public synchronized void addConnection( SocketService service ) { + ConfigurationContext context = service.getContext(); + String key = context.getAdapterGroupName(); + String adapterName = context.getAdapterName(); + // Outbound Socket Connection의 경우... + // OutboundChannelManager 에 Connection을 추가시킨다. + // if ( context.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET ) ) { + + LinkedList list = stateTable.get( key ); + list.add( service ); + + if ( context.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET ) ) { + OutboundChannelManager.getInstance().addConnection(key, service); + } + + if ( context.getSocketType().equals( ConfigurationContext.CLIENT_SOCKET ) ) { + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + if ( adminTable != null ) { + adminTable.checkRecoverStatus(); + } + } + + // RemoteIP:Port관리 + if ( context.getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) { + try { + String remoteInfo = new StringBuffer().append( service.getCurrentSocket().getInetAddress().getHostAddress()).append(":").append( service.getCurrentSocket().getPort()).toString(); + controlMap.put( remoteInfo, service ); + } catch ( Exception e ) {} + } + } + + public synchronized void removeConnection( SocketService service ) { + ConfigurationContext context = service.getContext(); + String key = context.getAdapterGroupName(); + + if ( context.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET ) ) { + OutboundChannelManager.getInstance().removeConnection(key, service); + } + + LinkedList list = stateTable.get( key ); + list.remove( service ); + + if ( context.getSocketType().equals( ConfigurationContext.CLIENT_SOCKET ) ) { + AdminTable adminTable = (AdminTable) adminTableMap.get( context.getAdapterName() ); + if ( adminTable != null ) { + adminTable.removeConnection( service ); + } + } + + // RemoteIP:Port관리 + if ( context.getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) { + try { + if ( controlMap.containsValue( service ) ) { + Object[] x = controlMap.keySet().toArray(); + for ( int i = 0; x != null && i < x.length; i++ ) { + String remoteInfo = (String)x[i]; + Object y = controlMap.get( remoteInfo ); + if ( y == null ) continue; + if ( ((SocketService)y) == service ) { + controlMap.remove( remoteInfo ); + break; + } + } + } + } catch ( Exception e ) {} + } + + } + + public synchronized String disconnect(String remoteIP, String port) { + StringBuffer strBuff = new StringBuffer(); + String remoteInfo = new StringBuffer().append( remoteIP ).append(":").append( port ).toString(); + + Object x = controlMap.get( remoteInfo ); + try { + if ( x != null ) { + SocketService svc = (SocketService)x; + StringBuffer connInfo = new StringBuffer(); + connInfo.append("Local Address="); + connInfo.append( svc.getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(svc.getCurrentSocket().getLocalPort()).append(", "); + connInfo.append("Remote Address="); + connInfo.append( svc.getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(svc.getCurrentSocket().getPort()); + + svc.shutdown(); + strBuff.append( CommonLib.getMessage("BICEAIMSA026",new String[]{ connInfo.toString() })); + } else { + strBuff.append( CommonLib.getMessage("BECEAIMSA007",new String[]{ remoteInfo })); + } + } catch ( Exception e ) { + strBuff.append( CommonLib.getMessage("BECEAIMSA007",new String[]{ remoteInfo })); + } + return strBuff.toString(); + } + + /* + * SessionService 스레드가 시작할때 이걸 호출함. + */ + public synchronized void addSession( SessionService session ) { + String key = session.getAdapterGroupName(); + this.sessionManager.addSession( key, session ); + LinkedList list = sessionTable.get( key ); + list.add( session ); + } + + @SuppressWarnings("rawtypes") + public void removeAllSession() { + // SESSION TABLE에서 해당 SESSION THREAD STOPPING + Object[] it = this.sessionTable.values().toArray(); + if ( it == null ) { + return; + } + + SessionService session = null; + LinkedList sessionList = null; + for ( int i=0; i < it.length; i++ ) { + sessionList = (LinkedList) it[i]; + + Object[] sit = sessionList.toArray(); + for(int j=0; j < sit.length; j++ ) { + session = (SessionService)sit[j]; + try { + session.shutdown(); + } catch(Exception e) {} + } + } + } + + @SuppressWarnings("rawtypes") + public String getSessionStatusInfo() { + Object[] it = this.sessionTable.values().toArray(); + + if ( it == null ) { + return CommonLib.getMessage("BICEAIMSA038", new String[]{"세션정보가 없습니다."}); + } + + StringBuffer strBuff = new StringBuffer(); + strBuff.append("\n"); + SessionService session = null; + LinkedList sessionList = null; + for ( int i=0; i < it.length; i++ ) { + sessionList = (LinkedList) it[i]; + + Object[] sit = sessionList.toArray(); + for(int j=0; j < sit.length; j++ ) { + session = (SessionService)sit[j]; + try { + strBuff.append( session.toString() ).append("\n"); + } catch(Exception e) {} + } + } + + return strBuff.toString(); + + } + + public synchronized void removeSession( SessionService session ) { + String key = session.getAdapterGroupName(); + this.sessionManager.removeSession(key, session); + LinkedList list = sessionTable.get( key ); + list.remove( session ); + + } + public void removeError(SocketService service) { + if ( errorTable != null ) { + this.errorTable.remove( service ); + } + } + + public void removeState(SocketService service) { + if ( stateTable != null ) { + String key = service.getContext().getAdapterGroupName(); + + if ( service.getContext().getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET) ) { + OutboundChannelManager.getInstance().removeConnection(key, service); + } + + LinkedList list = stateTable.get( key ); + list.remove( service ); + this.errorTable.remove( service ); + + } + } + + public boolean checkActiveStatus(String adapterGroupName, String adapterName) { + boolean good = false; + LinkedList list = stateTable.get( adapterGroupName ); + if ( list == null || list.size() < 1 ) return false; + for ( int i = 0; i < list.size(); i++ ) { + try { + SocketService aSvc = (SocketService) list.get( i ); + if ( aSvc.getContext().getAdapterName().equals( adapterName ) ) { + good = true; + break; + } + } catch ( Exception e ) {} + } + + return good; + } + + public synchronized boolean addError( SocketService service ) { + if ( started ) { + //if ( service.getContext().getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET) ) { + if ( service.getContext().getSocketType().equals( ConfigurationContext.CLIENT_SOCKET ) ) { + String key = service.getContext().getAdapterGroupName(); + String adapterName = service.getContext().getAdapterName(); + + if ( service.getContext().getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET) ) { + OutboundChannelManager.getInstance().removeConnection(key, service); + } + + LinkedList list = stateTable.get( key ); + list.remove( service ); + this.errorTable.remove( service ); + + AdminTable adminTable = (AdminTable) adminTableMap.get( adapterName ); + if ( adminTable != null ) { + adminTable.checkErrorStatus(); + } + } + + return this.errorTable.add( service ); + } else { + return false; + } + } + + public boolean isStarted() { + return this.started; + } + + /** + * Socket Adapter Administation Command Provider.... + */ + public String executeCommand( String command ) { + + String commands = "stop,start,get,set,disconnect"; + String options = "connection,session,trace,config"; + String inCmd = command ; + + if ( inCmd == null || inCmd.equals("") ) { + return CommonLib.getMessage("BECEAIMSA011", new String[]{ command }); + } + + String[] cList = inCmd.split(" "); + if ( cList.length < 3 ) { + return CommonLib.getMessage("BECEAIMSA011", new String[]{ command }); + } + String cmd = cList[0].toLowerCase(); + String option = cList[1].toLowerCase(); + + if ( commands.indexOf( cmd ) < 0 ) { + return CommonLib.getMessage("BECEAIMSA011", new String[]{ command }); + } else if ( (cmd.equals("get") || cmd.equals("set")) + && options.indexOf( option ) < 0 ) { + return CommonLib.getMessage("BECEAIMSA012", new String[]{ command }); + } + + String rtnMsg = " "; + if ( cmd.equals("stop") ) { + rtnMsg = this.stop( cList[1], cList[2] ); + } else if ( cmd.equals("start") ) { + rtnMsg = this.start( cList[1], cList[2] ); + } else if ( cmd.equals("get") ) { + // Connections + if ( option.equals("connection") ) { + if ( cList[2].equalsIgnoreCase("all") ) { + rtnMsg = this.getConnectionInfo( null ); + } else if ( cList[2].equalsIgnoreCase("summary") ) { + rtnMsg = this.getConnectionSummary(); + } else { + rtnMsg = this.getConnectionInfo( cList[2] ); + } + // Config + } else if ( option.equals("config") ) { + ConfigurationContext ctx = this.getContext( cList[2] ); + if ( ctx == null ) { + rtnMsg = CommonLib.getMessage("BECEAIMSA028", new String[] { cList[2] } ); + } else { + rtnMsg = this.getContext( cList[2] ).toString(); + } + // Sessions + } else { + if ( cList[2].equalsIgnoreCase("all") ) { + rtnMsg = this.getSessionInfo( null ); + } else { + rtnMsg = this.getSessionInfo( cList[2] ); + } + } + } else if ( cmd.equals("set") ) { + if ( cList.length < 4 ) { + return CommonLib.getMessage("BECEAIMSA012", new String[]{ command }); + } + // Connections + int newCount = 0; + try { + newCount = Integer.parseInt( cList[3] ); + } catch ( Exception e ) { + return CommonLib.getMessage("BECEAIMSA012", new String[]{ command }); + } + + if ( option.equals("connection") ) { + rtnMsg = this.adjustConnection( cList[2], newCount ); + // Sessions + } else if ( option.equals("session") ) { + try { + rtnMsg = this.adjustSession( cList[2], newCount ); + } catch( Exception e ) { + rtnMsg = CommonLib.getMessage("BECEAIMSA013", new String[]{ cList[2], e.getMessage() } ); + } + // trace level 조정 + } else { + ConfigurationContext ctx = this.getContext( cList[2] ); + if ( newCount < 0 || newCount > 2 ) { + rtnMsg = CommonLib.getMessage("BECEAIMSA014"); + } + if ( ctx == null ) { + rtnMsg = CommonLib.getMessage("BECEAIMSA015", new String[]{ cList[2] } ); + return rtnMsg;// 20250910 npe 첨부 + } + ctx.setTraceLevel( newCount ); + String newLevel = ""; + + if ( newCount == 0 ) newLevel = "0(ERROR)"; + else if ( newCount == 1 ) newLevel = "1(INFO)"; + else newLevel = "2(DEBUG)"; + + rtnMsg = CommonLib.getMessage("BICEAIMSA037", new String[]{ cList[2], newLevel }); + } + } else if ( cmd.equals("disconnect") ) { + if ( cList.length < 3 ) { + return CommonLib.getMessage("BECEAIMSA012", new String[]{ command }); + } + + rtnMsg = this.disconnect( cList[1], cList[2] ); + } else { + return CommonLib.getMessage("BECEAIMSA011", new String[]{ command }); + } + + return rtnMsg; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append("\n■ stateTable : cnt="+ stateTable.size()); + for(Iterator iter = stateTable.keySet().iterator(); iter.hasNext();) { + Object key = iter.next(); + sb.append("\n ▣ " + key + " : " + (stateTable.get(key)).size()); + for(Iterator iter2 = (stateTable.get(key)).iterator(); iter2.hasNext();) { + sb.append("\n ▷ " + iter2.next() + " : "); + } + } + sb.append("\n■ errorTable : " + errorTable); + sb.append("\n■ sessionTable : cnt="+ sessionTable.size()); + for(Iterator iter = sessionTable.keySet().iterator(); iter.hasNext();) { + Object key = iter.next(); + sb.append("\n ▣ " + key + " : cnt=" + (sessionTable.get(key)).size()); + for(Iterator iter2 = (sessionTable.get(key)).iterator(); iter2.hasNext();) { + sb.append("\n ▷ " + iter2.next() + " : "); + } + } + + sb.append(connManager); + sb.append(recoverManager); + sb.append(sessionManager); + sb.append(OutboundChannelManager.getInstance().toString()); + + sb.append("\n■ adminTableMap : cnt="+ adminTableMap.size()); + for(Iterator iter = adminTableMap.keySet().iterator(); iter.hasNext();) { + Object key = iter.next(); + sb.append("\n ▣ " + key + " : " + adminTableMap.get(key)); + } + sb.append("\n■ controlMap : cnt="+ controlMap.size()); + for(Iterator iter = controlMap.keySet().iterator(); iter.hasNext();) { + Object key = iter.next(); + sb.append("\n ▣ " + key + " : " + controlMap.get(key)); + } + + return sb.toString(); + } + + public SocketService getSocketService(String adapterGroupName, String adapterName) + { + Object[] services = this.getAllAdminList(); + for (int i=0; i< services.length; i++) { + SocketService ss = (SocketService)services[i]; + ConfigurationContext ctx = ss.getContext(); + + if (ctx.getAdapterGroupName().equalsIgnoreCase(adapterGroupName) && + ctx.getAdapterName().equalsIgnoreCase(adapterName)) + { + return ss; + } + } + return null; + } + + public String getAllServerSocketInformation() + { + logger.info("SocketAdapterManager.getAllServerSocketInformation called"); + StringBuffer sb = new StringBuffer(); + Object[] services = this.getAllAdminList(); + logger.info("SocketAdapterManager.getAllServerSocketInformation: AdminTable count = " + services.length); + for (int i=0; i< services.length; i++) { + + SocketService ss = (SocketService)services[i]; + ConfigurationContext ctx = ss.getContext(); + if (ss.isActive()) { + sb.append("[ACTIVE]"); + } else { + sb.append("[INACTIVE]"); + } + sb.append("[" + ctx.getAdapterGroupName() + "]"); + sb.append("[" + ctx.getAdapterName() + "]"); + sb.append(" USAGE: SERVER SOCKET "); + sb.append(" PORT : (" + ctx.getLocalPortNumber() + ")"); + sb.append("
\n"); + + + } + return sb.toString(); + } + + public int getSocketServiceCount(String adapterGroupName, String adapterName) { + int cnt = 0; + + LinkedList serviceList = stateTable.get(adapterGroupName); + for (int i=0; i timeout); + } + + public boolean isActive() { + return active; + } + + public synchronized void shutdown() { + active = false; + + if (this.socket == null) { + logger.info("OutboundSocketClient : socket 이 null 입니다."); + return; + } + if (this.socket.isClosed()) { + logger.info("OutboundSocketClient : socket 이 이미 close 되었습니다."); + return; + } + + try { + socket.setSoLinger(true, 100); + socket.shutdownInput(); + socket.shutdownOutput(); + socket.close(); + logger.info("OutboundSocketClient : Outbound Socket Closed !!"); + + } catch (Exception ex) { + logger.error("★★★★★ Outbound Socket Close 시 오류 발생 !! ★★★★★", ex); + } + } + + public Socket getCurrentSocket() { + return this.socket; + } + + public boolean connect() { + return true; + } + + public void disconnect() { + shutdown(); + } + + public void setControl(Object control) { + } + + public void notifyMessage() { + } + + public int getCurrentState() { + return this.currentState; + } + + public boolean isConnected() throws IOException { + return this.socket.isConnected(); + } + + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + public void checkActivity() { + } + + public long getFirstActivity() { + return firstActivity; + } + + public long getLastActivity() { + return lastActivity; + } + +} diff --git a/src/com/eactive/eai/adapter/socket/service/AdminServer.java b/src/com/eactive/eai/adapter/socket/service/AdminServer.java new file mode 100644 index 0000000..6743aaf --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/AdminServer.java @@ -0,0 +1,531 @@ +//package com.eactive.eai.adapter.socket.service; +// +//import java.io.IOException; +//import java.net.Socket; +//import java.nio.ByteBuffer; +//import java.nio.channels.ClosedSelectorException; +//import java.nio.channels.SelectionKey; +//import java.nio.channels.Selector; +//import java.nio.channels.SocketChannel; +//import java.util.Iterator; +// +//import com.eactive.eai.adapter.socket.common.CommonLib; +//import com.eactive.eai.adapter.socket.common.DiagLogger; +//import com.eactive.eai.adapter.socket.common.SocketAdapterException; +//import com.eactive.eai.adapter.socket.config.ConfigurationContext; +//import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public class AdminServer extends Thread implements SocketService { +// +// private ConfigurationContext context; +// private SocketChannel socketChannel; +// private SocketServer proxy; +// private Selector selector; +// private SelectionKey key; +// +// private boolean active; +// +// // 상태정보 +// private int sendCount; +// private int recvCount; +// private long firstActivity; +// private long lastActivity; +// +// // IO BUFFER +// private ByteBuffer incomingMessage; +// private ByteBuffer outgoingMessage; +// private ByteBuffer lenBuffer; +// +// // Logger +// private Logger logger; +// private String remoteIPAddress; +// +// public AdminServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) { +// String name = this.getName(); +// this.setName( context.getAdapterName() + "-CONNECTION-ADMIN" + name.substring( name.lastIndexOf("-")) ); +// +// this.context = context; +// this.socketChannel = socketChannel; +// this.proxy = proxy; +// +// sendCount = 0; +// recvCount = 0; +// firstActivity = System.currentTimeMillis(); +// lastActivity = System.currentTimeMillis(); +// +// incomingMessage = null; +// outgoingMessage = null; +// +// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() ); +// lenBuffer.clear(); +// +// logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName()); +// remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress(); +// active = true; +// } +// +// private boolean isSyncMode() { +// return this.context.isSyncMode(); +// } +// +// public String getRemoteIPAddress() { +// return this.remoteIPAddress; +// } +// +// private long getTimeout() { +// return ( this.context.getTimeout() * 1000L ); +// } +// +// private boolean isSocketReuse() { +// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); +// } +// +// private int getTraceLevel() { +// return context.getTraceLevel(); +// } +// /** +// * @return Returns the context. +// */ +// public ConfigurationContext getContext() { +// return context; +// } +// +// public void run() { +// SocketAdapterManager.getInstance().addConnection( this ); +// +// String socketInfo = this.getSocketInfo(this.socketChannel); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIMSA034", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); +// } +// +// try { +// openSelector(); +// } catch(IOException e) { +// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "openSelector", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// active = false; +// } +// +// Iterator iterator; +// long start = System.currentTimeMillis(); +// while( active ) { +// try { +// int selected = selector.select( getTimeout() ); +// if( selected == 0 ) { +// long waitTime = System.currentTimeMillis() - start; +// if ( lenBuffer.position() > 0 && waitTime >= getTimeout() ) { +// String errMsg = CommonLib.getMessage("BECEAIMSA024", new String[]{context.getAdapterName(), socketInfo, Long.toString(getTimeout()), "수신", getReadingMessage() }); +// logger.error( errMsg ); +// active = false; +// } +// continue; +// } +// } catch(IOException e) { +// if ( lenBuffer.position() > 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "select", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// } +// active = false; +// } catch(ClosedSelectorException e ) { +// continue; +// } catch(Exception e) {} +// +// if ( selector == null || !selector.isOpen() ) continue; +// +// iterator = selector.selectedKeys().iterator(); +// +// while( iterator.hasNext() ) { +// key = (SelectionKey)iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// if(key.isReadable()) { // is Readable ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // +// try { +// +// start = System.currentTimeMillis(); +// if( processReadMessage() ) { // Read Done +// byte[] message = incomingMessage.array(); +// +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIMSA001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// +// this.checkActivity(); +// lastActivity = System.currentTimeMillis(); +// recvCount++; +// +// byte[] rtnValue = SocketAdapterManager.getInstance().executeCommand( new String(message) ).getBytes(); +// +// incomingMessage.clear(); +// lenBuffer.clear(); +// +// start = System.currentTimeMillis(); +// +// if ( isSyncMode() ) { +// // 동기, SYNC로 간주합니다. +// makeFormat( rtnValue ); +// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); +// //selector.wakeup(); +// } else { +// // 비동기, ASYNC로 간주합니다. +// socketChannel.register(selector, SelectionKey.OP_READ); +// //selector.wakeup(); +// } +// } +// } catch(Exception e) { +// if ( lenBuffer.position() > 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// } +// active = false; +// } finally { +// if(!active) continue; +// } +// } // end of readable... +// +// if( key.isWritable() ) { // is Writable ? - - - - - - - - - - - - - - - - - - - // +// try { +// if( processWriteMessage() ) { +// +// sendCount++; +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIMSA001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), socketInfo, getWritingMessage()})); +// } +// +// outgoingMessage.clear(); +// lenBuffer.clear(); +// +// socketChannel.register(selector, SelectionKey.OP_READ); // write end. so read only. +// } +// } catch(IOException e) { +// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "processWriteMessage", e.getMessage(), "송신메시지", getWritingMessage() } ); +// logger.error( errMsg , e); +// active = false; +// } +// } // end of writables... +// } // End of while(iterator.hasNext()) +// +// if ( !isSocketReuse() ) { +// active = false; +// } +// +// } // enf of while - active +// +// try { +// closeSelector(); +// } catch(IOException e) {} +// +// +// SocketAdapterManager.getInstance().removeConnection( this ); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIMSA035", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); +// } +// +// proxy.quiesceShutdown(this); +// interrupt(); +// +// } +// +// private String getReadingMessage() { +// String rMsg = ""; +// if ( incomingMessage != null && incomingMessage.position() > 0 ) { +// byte[] dMsg = new byte[ incomingMessage.position() ]; +// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length ); +// rMsg = CommonLib.getDumpMessage( dMsg ); +// } +// return rMsg; +// } +// +// private String getWritingMessage() { +// String rMsg = ""; +// if ( outgoingMessage != null && outgoingMessage.position() > 0 ) { +// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ]; +// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length ); +// rMsg = CommonLib.getDumpMessage( debugMsg ); +// } +// return rMsg; +// } +// +// private String getSocketInfo(SocketChannel channel) { +// StringBuffer connInfo = new StringBuffer(); +// +// connInfo.append("Local Address="); +// connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", "); +// connInfo.append("Remote Address="); +// connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort()); +// +// return connInfo.toString(); +// } +// +// public boolean idle(long timeout) { +// long idleTime = System.currentTimeMillis() - this.lastActivity; +// return ( idleTime > timeout ); +// } +// +// public boolean isActive() { +// return active; +// } +// +// public void shutdown() { +// active = false; +// try { +// closeSelector(); +// } catch( Exception e ) {} +// +// interrupt(); +// } +// +// public Socket getCurrentSocket() { +// return socketChannel.socket(); +// } +// +// public boolean connect() { +// return true; +// } +// +// public void disconnect() { +// shutdown(); +// proxy.quiesceShutdown(this); +// } +// +// private void openSelector() throws IOException { +// +// if ( selector == null || !selector.isOpen() ) { +// selector = Selector.open(); +// } +// socketChannel.socket().setTcpNoDelay(true); +// socketChannel.configureBlocking(false); +// socketChannel.register(selector, SelectionKey.OP_READ); +// +// } +// +// private void closeSelector() throws IOException { +// if(selector != null) { +// selector.wakeup(); +// +// for(Iterator iterator = selector.keys().iterator(); iterator.hasNext();) { +// try { +// key = iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// key.cancel(); +// if(socketChannel != null) { +// Socket socket = socketChannel.socket(); +// if(socket != null) { +// socket.setSoLinger(false, 0); +// try { socket.close(); } catch(Exception e) {} +// } +// socketChannel.close(); +// } +// } catch(IOException ioexception) { } +// } +// selector.close(); +// } +// selector = null; +// } +// +// public void setControl(Object control) { +// } +// +// public void notifyMessage() { +// } +// +// +// private boolean processReadMessage() throws Exception { +// +// int i = 0; +// boolean flag = false; +// +// while ( lenBuffer.position() < lenBuffer.capacity() ) { +// i = socketChannel.read( lenBuffer ); +// if ( i <= 0 ) break; +// flag = true; +// } +// +// if(i == -1) { +// if ( lenBuffer.position() > 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA010", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) ); +// } else { +// String errMsg = CommonLib.getMessage("BICEAIMSA036", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}); +// if(logger.isInfoEnabled()){ +// logger.info( errMsg ); +// } +// throw new SocketAdapterException( errMsg ); +// } +// } +// if ( lenBuffer.position() != lenBuffer.capacity() ) return false; +// +// int length = 0; +// +// try { +// if ( flag ) { +// length = checkLengthField( lenBuffer ); +// incomingMessage = ByteBuffer.allocate( length ); +// incomingMessage.clear(); +// } +// } catch(Exception le) { +// throw le; +// } +// +// i = 0; +// while ( incomingMessage.position() < incomingMessage.capacity()) { +// i = socketChannel.read(incomingMessage); +// if ( i <= 0 ) break; +// } +// +// if(i == -1) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA010", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) ); +// } else { +// if ( incomingMessage.position() == incomingMessage.capacity() ) { +// return true; +// } else { +// return false; +// } +// } +// } +// +// private boolean processWriteMessage() throws IOException { +// +// outgoingMessage.flip(); +// +// while ( outgoingMessage.hasRemaining() && active ) { +// socketChannel.write(outgoingMessage); +// } +// +// return true; +// } +// +// // Writing전에 확인... +// public boolean isConnected() throws IOException { +// return true; +// } +// +// public int getCurrentState() { +// return CommonLib.PROCESSING_PROTOCOL; +// } +// +// private void resetCount() { +// this.recvCount = 0; +// this.sendCount = 0; +// } +// +// public void checkActivity() { +// long currentTime = System.currentTimeMillis(); +// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) { +// this.resetCount(); +// } +// } +// +// private int checkLengthField(ByteBuffer buffer) throws SocketAdapterException { +// int length = 0; +// +// if ( buffer.capacity() == 2 ) { +// length = ( buffer.getShort(0) & 0xFFFF ); +// } else if ( buffer.capacity() == 4 ) { +// length = ( buffer.getInt(0) ); +// if ( length < 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA027", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } else { +// String lenStr = new String( buffer.array() ); +// try { +// length = Integer.parseInt( lenStr ); +// } catch ( NumberFormatException e ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA027", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } +// return length; +// } +// +// private byte[] makeLengthField(int length) { +// byte[] lenField = null; +// +// if ( lenBuffer.capacity() == 2 ) { +// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() ); +// tmpBuffer.clear(); +// tmpBuffer.putShort( (short) (length & 0xFFFF) ); +// lenField = tmpBuffer.array(); +// } else { +// String lenStr = CommonLib.getFormatString( length, lenBuffer.capacity() ); +// lenField = lenStr.getBytes(); +// } +// +// return lenField; +// } +// +// private void makeFormat(byte[] data) throws SocketAdapterException { +// +// int i = data.length + lenBuffer.capacity(); +// +// if(outgoingMessage == null) { +// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() ); +// } else { +// if( i != outgoingMessage.capacity() ) +// outgoingMessage = ByteBuffer.allocate( i ); +// } +// +// outgoingMessage.clear(); +// outgoingMessage.put( makeLengthField( data.length ) ); +// outgoingMessage.put( data ); +// } +// +// /** +// * @return Returns the socketchannel. +// */ +// public SocketChannel getSocketchannel() { +// return socketChannel; +// } +// /** +// * @param socketchannel The socketchannel to set. +// */ +// public void setSocketchannel(SocketChannel socketchannel) { +// this.socketChannel = socketchannel; +// } +// +// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각 +// public String toString() { +// boolean status = true; +// StringBuffer strBuff = new StringBuffer(); +// strBuff.append(context.getAdapterGroupName()).append(","); +// strBuff.append(context.getAdapterName()).append(","); +// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); +// strBuff.append(context.getSocketType()).append(","); +// strBuff.append(context.getResponseType()).append(","); +// try { +// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); +// } catch( Exception e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// +// try { +// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); +// } catch( Exception e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// strBuff.append(this.sendCount).append(","); +// strBuff.append(this.recvCount).append(","); +// strBuff.append( status ).append(","); +// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); +// strBuff.append( CommonLib.getCurrentTime( this.lastActivity )); +// +// return strBuff.toString(); +// } +// +// public void setLastActivity() { +// } +// +// public long getFirstActivity() { +// return firstActivity; +// } +// +// public long getLastActivity() { +// return lastActivity; +// } +//} diff --git a/src/com/eactive/eai/adapter/socket/service/AdminTable.java b/src/com/eactive/eai/adapter/socket/service/AdminTable.java new file mode 100644 index 0000000..0199925 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/AdminTable.java @@ -0,0 +1,105 @@ +package com.eactive.eai.adapter.socket.service; + +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; + +import java.util.Vector; + + +/** + * Adapter Name별관리 대상테이블 + */ +public class AdminTable { + + private String adapterGroupName; + private String adapterName; + private ConfigurationContext ctx; + private Vector connections; + private int activeCount; + + public AdminTable(String adapterGroupName, String adapterName, ConfigurationContext context ) { + this.adapterGroupName = adapterGroupName; + this.adapterName = adapterName; + this.ctx = context; + this.connections = new Vector(); + this.activeCount = 0; + } + + public String getAdapterGroupName() { + return adapterGroupName; + } + + public void initialize() { + this.connections.clear(); + this.activeCount = 0; + } + + public void setContext( ConfigurationContext context ) { + this.ctx = context; + } + + public ConfigurationContext getContext() { + return ctx; + } + + public synchronized Object[] getConnections() { + return connections.toArray(); + } + + public synchronized void checkErrorStatus() { + synchronized ( connections ) { + updateStatus( SocketAdapterManager.getInstance().checkActiveStatus( adapterGroupName, adapterName ) ); + } + } + + public synchronized void checkRecoverStatus() { + synchronized ( connections ) { + updateStatus( SocketAdapterManager.getInstance().checkActiveStatus( adapterGroupName, adapterName ) ); + } + } + + // Adapter Group Session을 한번에 등록한다. + public synchronized void addConnection(SocketService connection) { + connections.add( connection ); + + } + + public synchronized void removeConnection(Object connection) { + synchronized ( connections ) { + int size = connections.size(); + for ( int i=0; i < size; i++ ) { + Object x = connections.elementAt( i ); + if ( x == connection ) { + connections.remove( i ); + break; + } + } + } + + if ( connections.size() == 0 ) { + updateStatus( false ); + } + } + + private void updateStatus( boolean on ) { + AdapterVO config = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName); + if ( config != null ) { + if ( config.isStatus() != on ) { + config.setStatus( on ); + } + } + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("\n ▷ AdminTable ["); + sb.append("adapterGroupName=" + adapterGroupName + ", "); + sb.append("adapterName=" + adapterName + ", "); + sb.append("connections=" + connections.size() + ", "); + sb.append("activeCount=" + activeCount); + sb.append("]"); + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/ConnectionManager.java b/src/com/eactive/eai/adapter/socket/service/ConnectionManager.java new file mode 100644 index 0000000..69a00c9 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/ConnectionManager.java @@ -0,0 +1,123 @@ +package com.eactive.eai.adapter.socket.service; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.common.util.Logger; +import java.util.HashMap; +import java.util.LinkedList; + +import java.util.Iterator; +import java.util.TimerTask; + + +/** + * Connection된 모든 Socket에 대한 상태를 관리한다. + * 업무별 리스트를 관리 + */ +public class ConnectionManager extends TimerTask { + + private HashMap> stateTable; + private Logger logger; + private long lastActivity; + + public ConnectionManager(HashMap> state) { + this.stateTable = state; + logger = SocketLogManager.getInstance().getLogger(); + lastActivity = System.currentTimeMillis(); + } + + // 30분간 미사용 Connection에 대한 강제 CLOSE수행 + // Inbound의 Server Socket Type에 한하여 정리작업을 수행한다. + public void run() { + if ( stateTable.size() < 1 ) return; + long timeout = SocketAdapterManager.UNUSED_CONNECTION_TIMEOUT; + + if ( !CommonLib.getDate( System.currentTimeMillis() ).equals( CommonLib.getDate( this.lastActivity ) ) ) { + this.checkActivity(); + } + + if ( timeout < 1 ) return; + + Object[] it = stateTable.values().toArray(); + + for ( int k=0; k < it.length; k++ ) { + try { + @SuppressWarnings("unchecked") + LinkedList groupList = (LinkedList) it[k]; + if ( groupList.size() < 1 ) continue; + Object[] x = groupList.toArray(); + + SocketService connection = (SocketService) x[0]; + if ( connection.getContext().getBoundUsage().equals( ConfigurationContext.INBOUND_SOCKET ) + && connection.getContext().getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) { + for ( int i=0; i < x.length; i++ ) { + connection = (SocketService) x[i]; + if ( connection.idle( timeout ) ) { + StringBuffer connInfo = new StringBuffer(); + + connInfo.append("Local Address="); + try { + connInfo.append( connection.getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(connection.getCurrentSocket().getLocalPort()).append(", "); + } catch( Exception e ) { + connInfo.append( "?:?,"); + } + connInfo.append("Remote Address="); + try { + connInfo.append( connection.getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(connection.getCurrentSocket().getPort()); + } catch( Exception e ) { + connInfo.append( "?:?"); + } + + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA027", new String[]{ Long.toString( timeout/1000 ), connInfo.toString() } )) ; + } + connection.disconnect(); + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA028", new String[]{ connInfo.toString() } )) ; + } + } + } + } + } catch( Exception e ) { + logger.error( CommonLib.getMessage("BECEAIMSA008", new String[]{ e.getMessage() }), e ); + } + } + } + + private void checkActivity() { + Object[] it = stateTable.values().toArray(); + + for ( int k=0; k < it.length; k++ ) { + try { + @SuppressWarnings("unchecked") + LinkedList groupList = (LinkedList) it[k]; + if ( groupList.size() < 1 ) continue; + Object[] x = groupList.toArray(); + + SocketService connection = null; + for ( int i=0; i < x.length; i++ ) { + try { + connection = (SocketService) x[i]; + connection.checkActivity(); + } catch( Exception ie ) {} + } + } catch( Exception e ) {} + } + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append("\n■ ConnectionManager : "); + for(Iterator iter = stateTable.keySet().iterator(); iter.hasNext();) { + Object key = iter.next(); + sb.append("\n ▣ " + key + " : "); + for(Iterator iter2 = (stateTable.get(key)).iterator(); iter2.hasNext();) { + sb.append("\n ● " + iter2.next() + " : "); + } + } + + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/IOboundServer.java b/src/com/eactive/eai/adapter/socket/service/IOboundServer.java new file mode 100644 index 0000000..a6329b7 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/IOboundServer.java @@ -0,0 +1,730 @@ +package com.eactive.eai.adapter.socket.service; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.ArrayList; + +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.common.DiagLogger; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.inbound.ResponseHandler; + +public class IOboundServer extends Thread implements SocketService { + + private ConfigurationContext context; + private SocketChannel socketChannel; + private SocketServer proxy; + + private boolean active; + + private long firstActivity; + private long lastActivity; + + private int currentState; + + // pending message for checking operation + private ByteBuffer pendingMessage; + private ByteBuffer incomingMessage; + private ByteBuffer pollingMessage; + + // Logger + private Logger logger; + + // + private String remoteIPAddress; + private String remotePort; + + AdapterVO adapter; +// String transaction_code; + + private BatchDoc batchMsgDoc; + //---------------------------------------------------------------- + + + public IOboundServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) { + String name = this.getName(); + this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) ); + + this.context = context; + this.socketChannel = socketChannel; + this.proxy = proxy; + + firstActivity = System.currentTimeMillis(); + lastActivity = System.currentTimeMillis(); + + pendingMessage = ByteBuffer.allocate( 4096 ); + pendingMessage.clear(); + + this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL; + + logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() ); + + active = true; + remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress(); + remotePort = this.socketChannel.socket().getPort() +""; + + + } + + public long getFirstActivity() { + return this.firstActivity; + } + + public long getLastActivity() { + return this.lastActivity; + } + + public String getRemotePort() { + return this.remotePort; + } + + public String getRemoteIPAddress() { + return this.remoteIPAddress; + } + + public boolean idle(long timeout) { + long idleTime = System.currentTimeMillis() - this.lastActivity; + return ( idleTime > timeout ); + } + + public boolean isActive() { + return active; + } + + public synchronized void shutdown() { + active = false; + + notify(); + + try { + if ( this.socketChannel == null ){ + logger.info("IOboundServer : socketChannel 이 null 입니다."); + return; + } + Socket socket = this.socketChannel.socket(); + if (socket == null) { + logger.info("IOboundServer : socket 이 null 입니다."); + return; + } + if (socket.isClosed()) { + logger.info("IOboundServer : socket 이 이미 close 되었습니다."); + return; + } + + socket.setSoLinger(true, 100); + if (socketChannel.isConnectionPending()) { + logger.info("IOboundServer : socket channle isConnectionPending OK!!!"); + socketChannel.finishConnect(); + } + socket.shutdownInput(); + socket.shutdownOutput(); + socket.close(); + socketChannel.close(); + + logger.info("IOboundServer : IObound Socket Closed !!"); + + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + } + + public Socket getCurrentSocket() { + return socketChannel.socket(); + } + + public boolean connect() { + return true; + } + + public void disconnect() { + shutdown(); + proxy.quiesceShutdown(this); + interrupt(); + } + + public void setControl(Object control) { + } + + public void notifyMessage() { + } + + public int getCurrentState() { + return this.currentState; + } + + // Writing전에 확인... + public boolean isConnected() throws IOException { + boolean flag = true; + + if ( socketChannel.isConnected() && socketChannel.socket().isBound() ) { + ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 ); + tmpBuffer.clear(); + int i = socketChannel.read( tmpBuffer ); + if ( i > 0 ) { + try { + pendingMessage.put( tmpBuffer.array() ); + } catch ( BufferOverflowException e ) { + throw new IOException("Socket 어플리케이션 프로토콜에러 발생 : " + e.getMessage()); + } + } + if ( i == -1 ) { + flag = false; + } + } else { + flag = false; + } + + return flag; + } + + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + public void checkActivity() { + } + + private boolean isAckProtocol() { + return this.context.isAckProtocol(); + } + + private long getTimeout() { + return ( this.context.getTimeout() * 1000L ); + } + + private int getTraceLevel() { + return context.getTraceLevel(); + } + + public ConfigurationContext getContext() { + return context; + } + + /** + * IOboundServer 는 SocketServer 에서 생성되는 Thread 이다. + * 외부에서 연결요청한 사항을 처리하기 위해 사용되며, 실제 배치처리에서는 실질적인 업무 플로우는 + * JPD에서 처리하므로 여기에서는 소켓자체를 배치용 매니저에 등록해주고, 사용하기 쉽게 해주고, + * 모든 context를 JPD 로 넘겨준다. + */ + public void run() { +// try { +// Thread.sleep(10000); +// } catch( Throwable e ) {} + + SocketAdapterManager.getInstance().addConnection( this ); + //*** 어댑터에 대해 하나의 대외기관 연결정보(BJ05)만이 매핑되어 있어야 하는 것이 보장되어야 한다. + logger.info("[IOboundServer] Group ["+context.getAdapterGroupName()+"] Adapter["+context.getAdapterName()+"]"); + adapter = AdapterManager.getInstance().getAdapterVO(context.getAdapterGroupName(), context.getAdapterName()); + + int readLength = 0; + try { + readLength = adapter.getContext().getLlFieldIndex() + adapter.getContext().getLlFieldLength(); + } catch (Exception e) {} + if ( readLength < 1 ){ + readLength = 9; + } + + firstActivity = System.currentTimeMillis(); + lastActivity = firstActivity; + + String socketInfo = ""; + + incomingMessage = ByteBuffer.allocate( readLength ); + + if ( getTraceLevel() >= DiagLogger.INFO ) { + logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); + } + // active 상태에서 LOOP + while ( active ) { + + try { + // length & message buffer clear + if ( incomingMessage != null ) { + incomingMessage.clear(); + + //logger.debug("incomingMessage-->" + incomingMessage.array().length); + //logger.debug("adapter.getContext().getLlFieldIndex()-->" + adapter.getContext().getLlFieldIndex()); + //logger.debug("adapter.getContext().getLlFieldLength()-->" + adapter.getContext().getLlFieldLength()); + + processReadMessage( incomingMessage.array() );// 20250910 npe + } + if( !active) break; + + lastActivity = System.currentTimeMillis(); + + // (DEBUG 레벨일 경우) 메시지수신 로그 + if ( getTraceLevel() >= DiagLogger.DEBUG ) { + logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())})); + } + try { + if ( adapter.getContext().getLlFieldLength() > 0 ){ + int ll_len = adapter.getContext().getLlFieldLength(); + byte[] ll_fld = new byte[ll_len]; + System.arraycopy(incomingMessage.array(), adapter.getContext().getLlFieldIndex(), ll_fld, 0, adapter.getContext().getLlFieldLength()); + if ( Integer.parseInt(new String(ll_fld)) == 0 ) continue; + // polling 메세지 처리 + if ( adapter.getContext().isUsePollMsg() ){ + + int msglen = Integer.parseInt(new String(ll_fld)); + pollingMessage = ByteBuffer.allocate(msglen); + try { + processReadMessage( pollingMessage.array() ); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + //logger.debug("[IOboundServer][run()]polling Msg-->" + new String(pollingMessage.array())); + String pollmsg = new String(pollingMessage.array()); + if ( pollmsg.startsWith("REQPOLL") || pollmsg.startsWith("HDRREQPOLL")){ + byte[] resPoll = new byte[ll_len+msglen]; + System.arraycopy(incomingMessage.array(), 0, resPoll, 0, ll_len); + System.arraycopy(pollingMessage.array(), 0, resPoll, ll_len, msglen); + if ( resPoll[ll_len+2] == 'Q' ) + resPoll[ll_len+2] = 'S'; + if ( resPoll[ll_len+5] == 'Q' ) + resPoll[ll_len+5] = 'S'; + Socket socket = socketChannel.socket(); + DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); + dout.write(resPoll, 0, resPoll.length); +// logger.debug("[IOboundServer][run()]resPoll Msg-->" + new String(resPoll)); + continue; + } + } + } + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + + doResposeRecieve(); + + // Socket REUSE 모드가 아니라면 Connection Close + if ( !isSocketReuse() ) { + active = false; + closeChannel(); + } + } catch (SocketTimeoutException ex) { + checkRequest(); + long idleTimeOutMin = context.getSessionTimeout(); + if ((idleTimeOutMin > 0) && this.idle(idleTimeOutMin * 60 * 1000)){ + logger.debug( "IOBoundServer(" + this.getName() + "), SessionTimeout :" + context.getSessionTimeout() + + ", timeout :" + context.getTimeout()); + active = false; + } + continue; + } catch( Exception e ) { + String msgEOF = ExceptionUtil.getErrorCode("BECEAIFJM010"); + if ( !e.getMessage().equals(msgEOF)){ + String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); + if ( errMsg.length() > 0 ) { + logger.error( errMsg , e); + + } + } + active = false; + + continue; + } + } // end of active + + // LOOP을 빠져나오면 (active가 아닌 경우), Channel 을 Close 한다. + try { + closeChannel(); + } catch( Throwable e ) {} + + SocketAdapterManager.getInstance().removeConnection( this ); + + logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); + proxy.quiesceShutdown(this); + SocketAdapterManager.getInstance().removeConnection( this ); + + interrupt(); + } + + public SocketChannel getSocketchannel() { + return socketChannel; + } + + public void setSocketchannel(SocketChannel socketchannel) { + this.socketChannel = socketchannel; + } + + public String toString() { + boolean status = true; + StringBuffer strBuff = new StringBuffer(); + strBuff.append(context.getAdapterGroupName()).append(","); + strBuff.append(context.getAdapterName()).append(","); + strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); + strBuff.append(context.getSocketType()).append(","); + strBuff.append(context.getResponseType()).append(","); + try { + strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); + } catch( Throwable e ) { + status = false; + strBuff.append("?:?,"); + } + + try { + strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); + } catch( Throwable e ) { + status = false; + strBuff.append("?:?,"); + } + + strBuff.append( status ).append(","); + strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); + strBuff.append(CommonLib.getCurrentTime( this.lastActivity )); + + return strBuff.toString(); + } + + private void doResposeRecieve(){ + + String strUUID = null; + + //---------------------------------------------------------------- + //BatchMsgDoc 생성 + batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(true); //true:초기화함 + + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SOCKET_SERVER, CommonKeys.SUB_LAYER_SOCKET_SERVER); + + try { + + if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("A")) { + // 응답수신 셋팅 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE); + } else { + // 응답송신 셋팅 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND); + } + logger.info("[IOboundServer] ProcessCode >> " + adapter.getBatchProcessCode()); + ArrayList osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode()); + int i=0; + for (i=0; i [" + batchMsgDoc.getBatchMsg().getHeader().getUserID()); + logger.info("**** PASS WD > [" + batchMsgDoc.getBatchMsg().getHeader().getUserPassword()); + logger.info("**** BLOCK > [" + batchMsgDoc.getBatchMsg().getHeader().getBlockSize()); + logger.info("**** SEQ SIZ > [" + batchMsgDoc.getBatchMsg().getHeader().getSequenceSize()); + logger.info("**** PACKET > [" + batchMsgDoc.getBatchMsg().getHeader().getPacketSize()); + + + //단계 종료시간 설정 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //응답수신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog(batchMsgDoc); + + strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID(); + + // BatchRunningJobManager 에 Running Job 등록 + logger.info("IOboundServer : BatchRunningJobManager 에 응답송수신 작업 등록......"); + // 기관별 로그 + Logger.addInstLog(batchMsgDoc); + + BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc); + logger.info("IOboundServer : FlowController JPD 호출 시작......"); + ResponseHandler handler = new ResponseHandler(); + this.batchMsgDoc = handler.execute(this.batchMsgDoc); + logger.info("IOboundServer : FlowController JPD 호출 완료 !!"); + String endComp = this.batchMsgDoc.getBatchMsg().getPhaseinfo().getPhaseType(); + if ( !"END".equals( endComp ) ) { + logger.info( "FlowController JPD 호출결과 정상 종료가 아님 --> 소켓 연결 종료" ); + socketChannel.close(); + } + + } catch (Exception ex) { + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASI010", new String[] {batchMsgDoc.getBatchMsg().getHeader().getUUID()}); + logger.error(errMsg, ex); //응답수신 Socket Server 배치메시지 생성 및 정보 설정시 오류가 발생하였습니다. [UUID: {1}] + + // DB로그 처리 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchMsgDoc, errMsg); + + } catch (Exception e) { + logger.error("[Socket Server] ★★★★★ 응답수신 Socket Server 예외 처리 중 에러 !! ★★★★★", e); + } + } finally { + // BatchRunningJobManager 에서 Running Job 제거 + logger.info("IOboundServer : BatchRunningJobManager 에서 응답송수신 작업 제거......"); + BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + lastActivity = System.currentTimeMillis(); + } + } + + private void checkRequest(){ + + if ( context.isResponseOnly()) return; + + String processCode = context.getAdapterVO().getBatchProcessCode(); + String institutionCode = context.getAdapterVO().getBatchInstitutionCode(); + SchedulerMessageVO info; + + while ( true ){ + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + + info.setSystemConnCode("this"); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandle(info); + + //BatchMsgDoc 생성 + batchMsgDoc = EAIBatchMsgManager.createBatchMsg(true); //true:초기화함 + + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING); + + //BatchMsgDoc 값 설정 + batchMsgDoc.getBatchMsg().getHeader().setUUID(info.getUUID()); + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode()); + batchMsgDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName()); + batchMsgDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchMsgDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchMsgDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchMsgDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchMsgDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + batchMsgDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName()); +// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(info.getInstitutionType()); + batchMsgDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchMsgDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID()); + batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd()); + batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(context.getHostName()); + batchMsgDoc.getBatchMsg().getHeader().setPort(context.getPortNumber()+""); + batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode()); +// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP"); + batchMsgDoc.getBatchMsg().getHeader().setRequestResponse(info.getRqstRspnsDstcd()); + batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(info.getFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo != null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02"); + + // 레코드 크기 추가 2009.02.03 + String jobCode = batchMsgDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchMsgDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + + // 20120601 추가 -- 시작 + if ( info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) || + info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND ) ){ + String hdrInfoName = info.getHdrInfoName(); + batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + batchMsgDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchMsgDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchMsgDoc.getBatchMsg().getHeader().setFileSize(batchMsgDoc.getBatchMsg().getHeader().getRecLen() * batchMsgDoc.getBatchMsg().getHeader().getTotRecCnt()); + } + // 20120601 추가 -- 여기까지 + + //재처리 플래그 설정.. + if (info.getRecvRetryFlag().equals("1")){ + batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(true); + logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 true로 설정합니다." ); + + }else { + batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(false); + logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 false로 설정합니다." ); + } + + + batchMsgDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID()); + batchMsgDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING); + + try { + LogUtil.updateLogMaster(batchMsgDoc); + } catch (Exception e) { + } + + logger.info("[IOboundServer] ■ BatchRunningJobManager 등록완료 "); + String strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID(); + + // BatchRunningJobManager 에 Running Job 등록 + logger.info("IOboundServer : BatchRunningJobManager 에 응답송수신 작업 등록......"); + BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc); + + try { + //=================================================== + logger.info("IOboundServer : FlowController JPD 호출 시작......"); + ResponseHandler handler = new ResponseHandler(); + this.batchMsgDoc = handler.execute(this.batchMsgDoc); + logger.info("IOboundServer : FlowController JPD 호출 완료 !!"); + String endComp = this.batchMsgDoc.getBatchMsg().getPhaseinfo().getPhaseType(); + if ( !"END".equals( endComp ) ) { + logger.info( "FlowController JPD 호출결과 EEND 소켓 연결 종료" ); + socketChannel.close(); + } + //=================================================== + + } finally { + // BatchRunningJobManager 에서 Running Job 제거 + logger.info("IOboundServer : BatchRunningJobManager 에서 응답송수신 작업 제거......"); + BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + lastActivity = System.currentTimeMillis(); + } + } catch ( Exception e){ + return; + } + } + } + public void processReadMessage( byte[] buffer ) throws Exception { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + boolean isEOF = false; + Socket socket = socketChannel.socket(); + DataInputStream din = new DataInputStream( socket.getInputStream()); + int len = buffer.length; + int timeOut = (int)getTimeout(); + + if ( timeOut < 1000 ) { + timeOut = 1000; + } + if ( timeOut > 60000 ) { + timeOut = 60000; + } + + logger.info( "[IOboundServer][" + context.getAdapterName() + "]데이터 수신 대기 중(타임아웃:" + timeOut + ")"); + socket.setSoTimeout( timeOut ); + + while (readBytes < len) { + try { + readBytes += din.read(buffer, readBytes, len-readBytes); + if (readBytes < 0) { + isEOF = true; + break; + } + + } catch (SocketTimeoutException ex) { + throw ex; + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + active = false; + return; + } + } + + if ( isEOF ) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM010"); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + + } // end of readData + private boolean isSocketReuse() { + return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); + } + private synchronized void closeChannel() throws IOException { + + if(socketChannel != null ) { + socketChannel.socket().close(); + socketChannel.close(); + } + socketChannel = null; + } // + private String getReadingMessage() { + String rMsg = ""; + if ( incomingMessage != null && incomingMessage.position() > 0 ) { + byte[] dMsg = new byte[ incomingMessage.position() ]; + System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length ); + rMsg = CommonLib.getDumpMessage( dMsg ); + } + return rMsg; + } + +} diff --git a/src/com/eactive/eai/adapter/socket/service/InboundClient.java b/src/com/eactive/eai/adapter/socket/service/InboundClient.java new file mode 100644 index 0000000..2920e83 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/InboundClient.java @@ -0,0 +1,903 @@ +package com.eactive.eai.adapter.socket.service; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.ArrayList; +import java.util.Properties; + +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.common.DiagLogger; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.inbound.ResponseHandler; + +public class InboundClient extends Thread implements SocketService { + + protected ConfigurationContext context; + private boolean active; + private SocketChannel channel; + + protected long firstActivity; + protected long lastActivity; + + private boolean retryFlag; + + private ByteBuffer incomingMessage; + private ByteBuffer pollingMessage; + + private Logger logger; + private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); + AdapterVO adapter; + + // 응답 송/수신 각 배치작업을 구별하기 위한 ID + //---------------------------------------------------------------- + //배치 응답송수신 전용, 전체 단계 작업에 대한 BatchMsg 객체 (Socket Coneection 내내 동일함) + //(전제조건) 1. 배치 전체 단계 전문 Flow 에 대해서 동일한 Socket Connection이 사용되어야 함 + // 2. 전체 단계 Flow 종료시 해당 Socket Connection 이 종료되고 Inbound Server 가 종료되어야 함 + private BatchDoc batchMsgDoc; + private byte[] MEGA_IN_MSG = { (byte) 0xff, (byte) 0xfb, (byte) 0x00, (byte) 0xff, + (byte) 0xfd, (byte) 0x00, (byte) 0xff, (byte) 0xfb, + (byte) 0x19, (byte) 0xff, (byte) 0xfd, (byte) 0x19 }; + private byte[] MEGA_OUT_MSG = { (byte) 0xff, (byte) 0xfd, (byte) 0x19 }; + private byte[] MEGA_EOR_MSG = { (byte) 0xff, (byte) 0xef }; + + private boolean mega_init = false; + //---------------------------------------------------------------- + + public InboundClient(ConfigurationContext context) { + + String name = this.getName(); + this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) ); + + this.context = context; + active = true; + retryFlag = true; + + incomingMessage = null; + + logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() ); + + } + + private int getTraceLevel() { + return context.getTraceLevel(); + } + + private long getTimeout() { + return ( this.context.getTimeout() * 1000L ); + } + + private boolean isSocketReuse() { + return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); + } + + /** + * @return Returns the context. + */ + public ConfigurationContext getContext() { + return context; + } + + public void run() { + //*** 어댑터에 대해 하나의 대외기관 연결정보(BJ05)만이 매핑되어 있어야 하는 것이 보장되어야 한다. + logger.info("[InboundClient] Group ["+context.getAdapterGroupName()+"] Adapter["+context.getAdapterName()+"]"); + adapter = AdapterManager.getInstance().getAdapterVO(context.getAdapterGroupName(), context.getAdapterName()); + + mega_init = false; + + int readLength = 0; + try { + readLength = adapter.getContext().getLlFieldIndex() + adapter.getContext().getLlFieldLength(); + } catch (Exception e) {} + if ( readLength < 1 ){ + readLength = 9; + } + + firstActivity = System.currentTimeMillis(); + lastActivity = firstActivity; + + String socketInfo = ""; + + + while ( retryFlag ) { + + active = true; + + // channel 을 열고 + try { + openChannel(); + socketInfo = this.getSocketInfo( this.getCurrentSocket() ); + } catch(Exception e) { + String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } ); + logger.error( errMsg, e ); + + if ( retryFlag ) { + waitRecoverConnection(); + } + continue; + } + + if ( getTraceLevel() >= DiagLogger.INFO ) { + logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); + } + + // active 상태에서 LOOP + while ( active ) { + try { + if ( !mega_init ) + incomingMessage = ByteBuffer.allocate( readLength ); + // length & message buffer clear + if ( incomingMessage != null ) { + incomingMessage.clear(); + + processReadMessage( incomingMessage.array() );// 29259819 npe + } + // 통계데이타 갱신 + this.checkActivity(); + lastActivity = System.currentTimeMillis(); + + // (DEBUG 레벨일 경우) 메시지수신 로그 + if ( getTraceLevel() >= DiagLogger.DEBUG ) { + logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())})); + } + + try { + //logger.info( "[InboundClient][adapter.getContext().getLlFieldLength()]-->" + adapter.getContext().getLlFieldLength() + ")"); + if ( adapter.getContext().getLlFieldLength() > 0 && !mega_init ){ + int ll_len = adapter.getContext().getLlFieldLength(); + byte[] ll_fld = new byte[ll_len]; + System.arraycopy(incomingMessage.array(), adapter.getContext().getLlFieldIndex(), ll_fld, 0, adapter.getContext().getLlFieldLength()); + + if ( byteCompare( ll_fld, MEGA_EOR_MSG )){ + continue; + } + if ( byteCompare( ll_fld, MEGA_IN_MSG )){ + Socket socket = channel.socket(); + DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); + dout.write(MEGA_OUT_MSG, 0, MEGA_OUT_MSG.length); + mega_init = true; + incomingMessage = ByteBuffer.allocate( 2 ); + continue; + } + if ( Integer.parseInt(new String(ll_fld)) == 0 ) continue; + // polling 메세지 처리 + //logger.info( "[InboundClient][adapter.getContext().isUsePollMsg()]-->" + adapter.getContext().isUsePollMsg() + ")"); + if ( adapter.getContext().isUsePollMsg() ){ + + int msglen = Integer.parseInt(new String(ll_fld)); + pollingMessage = ByteBuffer.allocate(msglen); + try { + processReadMessage( pollingMessage.array() ); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + //logger.debug("[IOboundClient][run()]polling Msg-->" + new String(pollingMessage.array())); + String pollmsg = new String(pollingMessage.array()); + if ( pollmsg.startsWith("REQPOLL") || pollmsg.startsWith("HDRREQPOLL")){ + byte[] resPoll = new byte[ll_len+msglen]; + System.arraycopy(incomingMessage.array(), 0, resPoll, 0, ll_len); + System.arraycopy(pollingMessage.array(), 0, resPoll, ll_len, msglen); + if ( resPoll[ll_len+2] == 'Q' ) + resPoll[ll_len+2] = 'S'; + if ( resPoll[ll_len+5] == 'Q' ) + resPoll[ll_len+5] = 'S'; + + Socket socket = channel.socket(); + DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); + dout.write(resPoll, 0, resPoll.length); +// logger.debug("[IOboundClient][run()]resPoll Msg-->" + new String(resPoll)); + continue; + } + } + } + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + + doResposeRecieve(); + + // Socket REUSE 모드가 아니라면 Connection Close + if ( !isSocketReuse() ) { + active = false; + closeChannel(); + } + } catch (SocketTimeoutException ex) { + checkRequest(); + if ( adapter.getContext().getLlFieldLength() == 12){ + try { + if ( channel != null ){ + Socket socket = channel.socket(); + DataOutputStream dout; + dout = new DataOutputStream(socket.getOutputStream()); + dout.write(MEGA_EOR_MSG, 0, MEGA_EOR_MSG.length); + } + continue; + } catch (IOException e) { + waitRecoverConnection(); + continue; + } + } + long idleTimeOutMin = context.getSessionTimeout(); + if ((idleTimeOutMin > 0) && this.idle(idleTimeOutMin * 60 * 1000)){ + logger.debug( "InboundClient(" + this.getName() + "), SessionTimeout :" + context.getSessionTimeout() + + ", timeout :" + context.getTimeout()); + waitRecoverConnection(); + } + continue; + } catch( Exception e ) { + String msgEOF = ExceptionUtil.getErrorCode("BECEAIFJM010"); + if ( !e.getMessage().equals(msgEOF)){ + String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); + if ( errMsg.length() > 0 ) { + logger.error( errMsg , e); + + if ( logger != errLogger ) { + errLogger.error( errMsg, e ); + } + } + } + //active = false; + + waitRecoverConnection(); + continue; + } + }// end of active + }// end of retry + + // LOOP을 빠져나오면 (active가 아닌 경우), Channel 을 Close 한다. + try { + closeChannel(); + } catch( Throwable e ) {} + + SocketAdapterManager.getInstance().removeConnection( this ); + + logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); + + interrupt(); + + } // end of startup ... + + private String getReadingMessage() { + String rMsg = ""; + if ( incomingMessage != null && incomingMessage.position() > 0 ) { + byte[] dMsg = new byte[ incomingMessage.position() ]; + System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length ); + rMsg = CommonLib.getDumpMessage( dMsg ); + } + return rMsg; + } + + protected String getSocketInfo(Socket socket) { + StringBuffer connInfo = new StringBuffer(); + + connInfo.append("Local Address="); + connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", "); + connInfo.append("Remote Address="); + connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort()); + + return connInfo.toString(); + } + + public int getCurrentState() { + return CommonLib.PROCESSING_PROTOCOL; + } + + public boolean isConnected() { + return true; + } + + public void checkActivity() { + } + + public boolean idle(long timeout) { + long idleTime = System.currentTimeMillis() - this.lastActivity; + + return ( idleTime > timeout ); + } + + public void setControl(Object control) { + } + + public void notifyMessage() { + } + + /** + * Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다. + * + */ + public synchronized void waitRecoverConnection() { + mega_init = false; + + try { + if ( !retryFlag ) return; + + try { closeChannel(); } catch(Exception ie) {} + if ( retryFlag && SocketAdapterManager.getInstance().addError( this ) ) { + wait(); + } + } catch ( InterruptedException e ) {} + } + + /** + * Socket Recovery Manager에 의해 recovery되면 Socket Recovery Manager에 의해 통지된다. * + */ + public synchronized void notifyRecoverConnection() { + notify(); + } + public void processReadMessage( byte[] buffer ) throws Exception { + processReadMessage( buffer, -1 ); + } + + public void processReadMessage( byte[] buffer, int rqTime ) throws Exception { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + boolean isEOF = false; + Socket socket = channel.socket(); + DataInputStream din = new DataInputStream( socket.getInputStream()); + int len = buffer.length; + int timeOut = (int)getTimeout(); + + if ( timeOut < 1000 ) { + timeOut = 1000; + } + if ( timeOut > 60000 ) { + timeOut = 60000; + } + if ( rqTime > -1 ){ + timeOut = rqTime; + } + + logger.info( "[InboundClient][" + context.getAdapterName() + "]데이터 수신 대기 중(타임아웃:" + timeOut + ")"); + socket.setSoTimeout( timeOut ); + + while (readBytes < len) { + try { + readBytes += din.read(buffer, readBytes, len-readBytes); + if (readBytes < 0) { + isEOF = true; + break; + } + + } catch (SocketTimeoutException ex) { + throw ex; + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + logger.error("★★★★★ Socket 에서 데이터 수신 시 오류 발생 !! ★★★★★", ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJM011"); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + } + } + + if ( isEOF ) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM010"); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + + } // end of readData + + public synchronized void shutdown() { + + active = false; + retryFlag = false; + + SocketAdapterManager.getInstance().removeError( this ); + try { + notify(); + } catch( Exception e ) {} + + //to gracefully shutdown the thread + try { + closeChannel(); + } catch (Exception e) {} + SocketAdapterManager.getInstance().removeError( this ); + + } + + public boolean isActive() { + return retryFlag; + } + + public Socket getCurrentSocket() { + return channel.socket(); + } + + public boolean connect() { + if ( !retryFlag ) return true; + + try { + openChannel(); + return true; + } catch ( Exception e ) { + return false; + } + } + + public void disconnect() { + } + + private synchronized void openChannel() throws IOException { + + if ( channel == null || !channel.isOpen() ) { + if ( !retryFlag ) return; + + channel = SocketChannel.open(); + if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") ) { + channel.socket().bind( new InetSocketAddress( InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() ) ); + channel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) ); + } else { + channel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) ); + } + + channel.socket().setTcpNoDelay(true); + + if ( isSocketReuse() ) { + channel.socket().setSoLinger(true, 100); + } + + // Connection 시 통계자료 RESET + this.firstActivity = System.currentTimeMillis(); + this.lastActivity = this.firstActivity; + + try { + Thread.sleep( 300L ); + } catch( Exception e ) {} + + if ( !this.isConnected() ) { + throw new IOException("Closed by Server"); + } + + if ( retryFlag ) { + SocketAdapterManager.getInstance().addConnection( this ); + } else { + closeChannel(); + } + } + } + + public String getRemoteIPAddress() { + return null; + } + + private synchronized void closeChannel() throws IOException { + if(channel != null ) { + channel.socket().close(); + channel.close(); + } + channel = null; + } // + + // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, SYNC, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각 + public String toString() { + boolean status = true; + StringBuffer strBuff = new StringBuffer(); + strBuff.append(context.getAdapterGroupName()).append(","); + strBuff.append(context.getAdapterName()).append(","); + strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); + strBuff.append(context.getSocketType()).append(","); + strBuff.append(context.getResponseType()).append(","); + + try { + strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); + } catch( Throwable e ) { + status = false; + strBuff.append("?:?,"); + } + + try { + strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); + } catch( Throwable e ) { + status = false; + strBuff.append("?:?,"); + } + + strBuff.append( status ).append(","); + strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); + strBuff.append(CommonLib.getCurrentTime( this.lastActivity )); + + return strBuff.toString(); + } + + public void setLastActivity() { + } + + public long getFirstActivity() { + return firstActivity; + } + + public long getLastActivity() { + return lastActivity; + } + + private void doResposeRecieve(){ + PropManager manager = PropManager.getInstance(); + Properties prop = manager.getProperties( adapter.getPropGroupName() ); + String rcvFlowRuleCode = prop.getProperty("reponse.rule.code"); + String strUUID = null; + + //---------------------------------------------------------------- + //BatchMsgDoc 생성 + batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(true); //true:초기화함 + + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SOCKET_SERVER, CommonKeys.SUB_LAYER_SOCKET_SERVER); + + try { + if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("A")) { + // 응답수신 셋팅 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE); + } else { + // 응답송신 셋팅 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND); + } + logger.info("[InboundClient] ProcessCode >> " + adapter.getBatchProcessCode()); + ArrayList osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode()); + int i=0; + for (i=0; i 0) { +// for (int i1=0; i1 [" + batchMsgDoc.getBatchMsg().getHeader().getUserID()); + logger.info("**** PASS WD > [" + batchMsgDoc.getBatchMsg().getHeader().getUserPassword()); + logger.info("**** BLOCK > [" + batchMsgDoc.getBatchMsg().getHeader().getBlockSize()); + logger.info("**** SEQ SIZ > [" + batchMsgDoc.getBatchMsg().getHeader().getSequenceSize()); + logger.info("**** PACKET > [" + batchMsgDoc.getBatchMsg().getHeader().getPacketSize()); + + //단계 종료시간 설정 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + // 기관별 로그 + Logger.addInstLog(batchMsgDoc); + + //응답수신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog(batchMsgDoc); + + strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID(); + + // BatchRunningJobManager 에 Running Job 등록 + logger.info("InboundClient : BatchRunningJobManager 에 응답송수신 작업 등록......"); + + BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc); + logger.info("InboundClient : FlowController JPD 호출 시작......"); + ResponseHandler handler = new ResponseHandler(); + this.batchMsgDoc = handler.execute(this.batchMsgDoc); + logger.info("InboundClient : FlowController JPD 호출 완료 !!"); + String endComp = this.batchMsgDoc.getBatchMsg().getPhaseinfo().getPhaseType(); + if ( !"END".equals( endComp ) ) { + logger.info( "FlowController JPD 호출결과 정상 종료가 아님 --> 소켓 연결 종료" ); + waitRecoverConnection(); + } + + } catch (Exception ex) { + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASI010", new String[] {batchMsgDoc.getBatchMsg().getHeader().getUUID()}); + logger.error(errMsg, ex); //응답수신 Socket Server 배치메시지 생성 및 정보 설정시 오류가 발생하였습니다. [UUID: {1}] + + // DB로그 처리 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchMsgDoc, errMsg); + waitRecoverConnection(); + } catch (Exception e) { + logger.error("[Socket Server] ★★★★★ 응답수신 Socket Server 예외 처리 중 에러 !! ★★★★★", e); + } + } finally { + // BatchRunningJobManager 에서 Running Job 제거 + logger.info("InboundClient : BatchRunningJobManager 에서 응답송수신 작업 제거......"); + BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + lastActivity = System.currentTimeMillis(); + } + } + + private void checkRequest(){ + + if ( context.isResponseOnly()) return; + + String processCode = context.getAdapterVO().getBatchProcessCode(); + String institutionCode = context.getAdapterVO().getBatchInstitutionCode(); + SchedulerMessageVO info; + + while ( true ){ + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + + logger.info("[InboundClient] ProcessCode >> " + adapter.getBatchProcessCode()); + ArrayList osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode()); + int i=0; + for (i=0; i= timeout ) + break; + try { + Thread.sleep( 20L ); + } catch( InterruptedException e ) {} + } + + if ( service == null ) + throw new Exception( CommonLib.getMessage("BECEAIASI004", new String[]{ adapterGroupName } )); + + + service.setControl( this ); + service.notifyMessage(); //wait 중인 SessionService 객체에 request 처리 호출 + + //Request 처리가 완료 될 때까지 대기...처리가 완료되면 SessionServer에서 이 클래의 wakeup() 메소드 호출함. + waitReply(); + + if ( isSyncMode() && this.getResponse() == null || this.getResponse().equals("")) { + throw new Exception( CommonLib.getMessage("BECEAIASI010") ); + } + + logger.debug("[ELINK]################ InboundControl.request() 종료. (수행 시간: "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec)"); + + return this.getResponse(); + } + + protected synchronized void waitReply() { + try { + while ( !ready ) { + this.wait(); + } + } catch ( InterruptedException ie ) {} + } + + public synchronized void wakeup() { + this.ready = true; + try { + this.notify(); + } catch( Throwable e ) {} + } + + /** + * @return Returns the lastError. + */ + public Throwable getLastError() { + return lastError; + } + /** + * @param lastError The lastError to set. + */ + public void setLastError(Throwable lastError) { + this.lastError = lastError; + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/InboundServer.java b/src/com/eactive/eai/adapter/socket/service/InboundServer.java new file mode 100644 index 0000000..b82a068 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/InboundServer.java @@ -0,0 +1,559 @@ +package com.eactive.eai.adapter.socket.service; + +import java.io.IOException; +import java.net.Socket; +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; +import java.util.ArrayList; +import java.util.Iterator; + +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.common.DiagLogger; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.inbound.ResponseHandler; + +public class InboundServer extends Thread implements SocketService { + + private ConfigurationContext context; + private SocketChannel socketChannel; + private SocketServer proxy; + private Selector selector; + private boolean active; + + // 상태정보 + private int sendCount; + private int recvCount; + private long firstActivity; + private long lastActivity; + + private int currentState; + + // pending message for checking operation + private ByteBuffer pendingMessage; + // Logger + private Logger logger; + + private String remoteIPAddress; + private String remotePort; + + //---------------------------------------------------------------- + //배치 응답송수신 전용, 전체 단계 작업에 대한 BatchMsg 객체 (Socket Coneection 내내 동일함) + //(전제조건) 1. 배치 전체 단계 전문 Flow 에 대해서 동일한 Socket Connection이 사용되어야 함 + // 2. 전체 단계 Flow 종료시 해당 Socket Connection 이 종료되고 Inbound Server 가 종료되어야 함 + private BatchDoc batchMsgDoc; + //---------------------------------------------------------------- + + + public InboundServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) { + String name = this.getName(); + this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) ); + + this.context = context; + this.socketChannel = socketChannel; + this.proxy = proxy; + + sendCount = 0; + recvCount = 0; + firstActivity = System.currentTimeMillis(); + lastActivity = System.currentTimeMillis(); + + pendingMessage = ByteBuffer.allocate( 4096 ); + pendingMessage.clear(); + + this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL; + + logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() ); + + active = true; + remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress(); + remotePort = this.socketChannel.socket().getPort() +""; + + //---------------------------------------------------------------- + //BatchMsgDoc 생성 + batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(true); //true:초기화함 + + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SOCKET_SERVER, CommonKeys.SUB_LAYER_SOCKET_SERVER); + + try { + + //*** 어댑터에 대해 하나의 대외기관 연결정보(BJ05)만이 매핑되어 있어야 하는 것이 보장되어야 한다. + logger.info("[InboundServer] Group ["+context.getAdapterGroupName()+"] Adapter["+context.getAdapterName()+"]"); + AdapterVO adapter = AdapterManager.getInstance().getAdapterVO(context.getAdapterGroupName(), context.getAdapterName()); + if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("A")) { + // 응답수신 셋팅 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE); + } else { + // 응답송신 셋팅 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND); + } + logger.info("[InboundServer] ProcessCode >> " + adapter.getBatchProcessCode()); + ArrayList osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode()); + int i=0; + for (i=0; i [" + tmpVO.getOsdCode() + "]"); + logger.info("BLK SIZE > [" + tmpVO.getBlkSize() + "]"); + logger.info("SEQ SIZE > [" + tmpVO.getSequenceSize() + "]"); + */ + if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) { + break; + } + } + OutsideVO outside = null; + if (i==osd_array.size()) { + String errMsg = "[InboundServer] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + adapter.getBatchProcessCode()+"] 대외기관["+adapter.getBatchInstitutionCode()+"]"; + batchMsgDoc.getBatchMsg().getBody().setErrorCode(99); + batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(errMsg); + } else { + logger.info("OUSIDE INFO index [" + i + "]"); + outside = (OutsideVO) osd_array.get(i); + } + + // BatchMsg 에 기본값 지정.. + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(adapter.getBatchProcessCode()); + batchMsgDoc.getBatchMsg().getHeader().setProcessName(adapter.getBatchProcessName()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(adapter.getBatchInstitutionCode()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(adapter.getBatchInstitutionName()); +// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(adapter.getBatchInstitutionType()); + batchMsgDoc.getBatchMsg().getBody().setPortNo(adapter.getBatchServerPortNo()); + batchMsgDoc.getBatchMsg().getBody().setTimeoutInterval(Integer.toString(adapter.getBatchInterMsgTimeout())); + batchMsgDoc.getBatchMsg().getHeader().setFlowCode(adapter.getBatchRcvFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(adapter.getBatchSystemConnCode()); + // 새로 추가되는 것들 + batchMsgDoc.getBatchMsg().getHeader().setRuleCode(adapter.getBatchRcvFlowRuleCode()); + RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(adapter.getBatchRcvFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo!=null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02"); + +// // 응답송신기능의 추가를 위해 일부 기능 수정 함. +// if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("C") ) { +// // 응답송신 이면 +// String strPathName = BatchDirUtil.getResSendRealDir(); +// if ( strPathName.charAt(strPathName.length()-1) != '/' ) { +// strPathName = strPathName + '/'; +// } +// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode()); +// StringBuffer sb = new StringBuffer(); +// +// sb.append(btVO.getProcessCode()); +// sb.append("/"); +// sb.append(btVO.getOrganCode()); +// strPathName = strPathName + sb.toString(); +// logger.debug("[응답송신] PATH NAME = [" + strPathName + "]"); +// +// File ff = new File(strPathName); +// if (!ff.exists()) { +// logger.warn("응답송신용 디렉토리 [" + strPathName + "] 이 없습니다."); +// throw new Exception(ExceptionUtil.getErrorCode("BWCEAIASI003")); +// } +// File[] fileList = ff.listFiles(); +// String strFileName = ""; +// long lnFileSize = -1; +// if (fileList.length> 0) { +// for (int i1=0; i1 [" + batchMsgDoc.getBatchMsg().getHeader().getUserID()); + logger.info("**** PASS WD > [" + batchMsgDoc.getBatchMsg().getHeader().getUserPassword()); + logger.info("**** BLOCK > [" + batchMsgDoc.getBatchMsg().getHeader().getBlockSize()); + logger.info("**** SEQ SIZ > [" + batchMsgDoc.getBatchMsg().getHeader().getSequenceSize()); + logger.info("**** PACKET > [" + batchMsgDoc.getBatchMsg().getHeader().getPacketSize()); + + + //단계 종료시간 설정 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //응답수신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog(batchMsgDoc); + + + } catch (Exception ex) { + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASI010", new String[] {batchMsgDoc.getBatchMsg().getHeader().getUUID()}); + logger.error(errMsg, ex); //응답수신 Socket Server 배치메시지 생성 및 정보 설정시 오류가 발생하였습니다. [UUID: {1}] + + // DB로그 처리 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchMsgDoc, errMsg); + + } catch (Exception e) { + logger.error("[Socket Server] ★★★★★ 응답수신 Socket Server 예외 처리 중 에러 !! ★★★★★", e); + } + } + } + + public long getFirstActivity() { + return this.firstActivity; + } + + public long getLastActivity() { + return this.lastActivity; + } + + public String getRemotePort() { + return this.remotePort; + } + + public String getRemoteIPAddress() { + return this.remoteIPAddress; + } + + public boolean idle(long timeout) { + long idleTime = System.currentTimeMillis() - this.lastActivity; + return ( idleTime > timeout ); + } + + public boolean isActive() { + return active; + } + + public synchronized void shutdown() { + active = false; + + notify(); + + try { + Socket socket = this.socketChannel.socket(); + if (socket == null) { + logger.info("InboundServer : socket 이 null 입니다."); + return; + } + if (socket.isClosed()) { + logger.info("InboundServer : socket 이 이미 close 되었습니다."); + return; + } + + socket.setSoLinger(true, 100); + if (socketChannel.isConnectionPending()) { + logger.info("InboundServer : socket channle isConnectionPending OK!!!"); + socketChannel.finishConnect(); + } + socket.shutdownInput(); + socket.shutdownOutput(); + socket.close(); + socketChannel.close(); + + logger.info("InboundServer : Inbound Socket Closed !!"); + logger.info("inbound socket : "+ socket ); + logger.info("inbound socket.isBound() : "+ socket.isBound() ); + logger.info("inbound socket.isClosed() : "+ socket.isClosed() ); + logger.info("inbound socket.isConnected() : "+ socket.isConnected() ); + logger.info("inbound socket.isInputShutdown() : "+ socket.isInputShutdown() ); + logger.info("inbound socket.isOutputShutdown() : "+ socket.isOutputShutdown()); + + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + } + + public Socket getCurrentSocket() { + return socketChannel.socket(); + } + + public boolean connect() { + return true; + } + + public void disconnect() { + shutdown(); + proxy.quiesceShutdown(this); + interrupt(); + } + + public void setControl(Object control) { + } + + public void notifyMessage() { + } + + public int getCurrentState() { + return this.currentState; + } + + // Writing전에 확인... + public boolean isConnected() throws IOException { + boolean flag = true; + + if ( socketChannel.isConnected() && socketChannel.socket().isBound() ) { + ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 ); + tmpBuffer.clear(); + int i = socketChannel.read( tmpBuffer ); + if ( i > 0 ) { + try { + pendingMessage.put( tmpBuffer.array() ); + } catch ( BufferOverflowException e ) { + throw new IOException("Socket 어플리케이션 프로토콜에러 발생 : " + e.getMessage()); + } + } + if ( i == -1 ) { + flag = false; + } + } else { + flag = false; + } + + return flag; + } + + public void setLastActivity() { + lastActivity = System.currentTimeMillis(); + } + + public void checkActivity() { + long currentTime = System.currentTimeMillis(); + if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) { //날자비교 + this.resetCount(); + } + } + + + + private void resetCount() { + this.recvCount = 0; + this.sendCount = 0; + } + + private boolean isAckProtocol() { + return this.context.isAckProtocol(); + } + + private long getTimeout() { + return ( this.context.getTimeout() * 1000L ); + } + + private int getTraceLevel() { + return context.getTraceLevel(); + } + + public ConfigurationContext getContext() { + return context; + } + + /** + * InboundServer 는 SocketServer 에서 생성되는 Thread 이다. + * 외부에서 연결요청한 사항을 처리하기 위해 사용되며, 실제 배치처리에서는 실질적인 업무 플로우는 + * JPD에서 처리하므로 여기에서는 소켓자체를 배치용 매니저에 등록해주고, 사용하기 쉽게 해주고, + * 모든 context를 JPD 로 넘겨준다. + */ + public void run() { + SocketAdapterManager.getInstance().addConnection( this ); + String socketInfo = this.getSocketInfo(this.socketChannel); + + if ( getTraceLevel() >= DiagLogger.INFO ) { + logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); + } + + String strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID(); + + // BatchRunningJobManager 에 Running Job 등록 + logger.info("InboundServer : BatchRunningJobManager 에 응답송수신 작업 등록......"); + BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc); + + + try { + // 기관별 로그 + Logger.addInstLog(batchMsgDoc); + + //=================================================== + logger.info("InboundServer : FlowController JPD 호출 시작......"); + ResponseHandler handler = new ResponseHandler(); + this.batchMsgDoc = handler.execute(this.batchMsgDoc); + logger.info("InboundServer : FlowController JPD 호출 완료 !!"); + //=================================================== + + } finally { + // BatchRunningJobManager 에서 Running Job 제거 + logger.info("InboundServer : BatchRunningJobManager 에서 응답송수신 작업 제거......"); + BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + + shutdown(); + proxy.quiesceShutdown(this); + + // 인바운드 소켓연결이 없어질 때, 처리 + SocketAdapterManager.getInstance().removeConnection( this ); + if ( getTraceLevel() >= DiagLogger.INFO ) { + logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); + } + } + } + + private String getSocketInfo(SocketChannel channel) { + StringBuffer connInfo = new StringBuffer(); + + connInfo.append("Local Address="); + connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", "); + connInfo.append("Remote Address="); + connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort()); + + return connInfo.toString(); + } + + + public int write(ByteBuffer src) throws IOException { + + if (this.selector == null) {// 20250910 uwf + this.selector = Selector.open(); + } + + this.socketChannel.register( this.selector, SelectionKey.OP_WRITE ); + + try { + selector.select( getTimeout() ); + } catch(Exception e) { + throw new IOException("Write Select Error"); + } + + Iterator it = selector.selectedKeys().iterator(); + int writtenBytes = 0; + SelectionKey key = null; + + while ( it.hasNext() ) { + key = it.next(); + it.remove(); + if ( key.isWritable() ) { + writtenBytes = this.socketChannel.write( src ); + } + } + return writtenBytes; + } + + /** + * @return Returns the socketchannel. + */ + public SocketChannel getSocketchannel() { + return socketChannel; + } + /** + * @param socketchannel The socketchannel to set. + */ + public void setSocketchannel(SocketChannel socketchannel) { + this.socketChannel = socketchannel; + } + + // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각 + public String toString() { + boolean status = true; + StringBuffer strBuff = new StringBuffer(); + strBuff.append(context.getAdapterGroupName()).append(","); + strBuff.append(context.getAdapterName()).append(","); + strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); + strBuff.append(context.getSocketType()).append(","); + strBuff.append(context.getResponseType()).append(","); + try { + strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); + } catch( Throwable e ) { + status = false; + strBuff.append("?:?,"); + } + + try { + strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); + } catch( Throwable e ) { + status = false; + strBuff.append("?:?,"); + } + strBuff.append(this.sendCount).append(","); + strBuff.append(this.recvCount).append(","); + strBuff.append( status ).append(","); + strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); + strBuff.append(CommonLib.getCurrentTime( this.lastActivity )); + + return strBuff.toString(); + } + + +// static Object arrayGrow(Object a) { +// Class cl = a.getClass(); +// if ( !cl.isArray() ) return null; +// +// Class compType = a.getClass().getComponentType(); +// int length = Array.getLength(a); +// int newLength = length * 11 / 10 + 10; +// Object newArray = Array.newInstance(compType, newLength); +// System.arraycopy(a, 0, newArray, 0, length); +// return newArray; +// } +} diff --git a/src/com/eactive/eai/adapter/socket/service/NBChannel.java b/src/com/eactive/eai/adapter/socket/service/NBChannel.java new file mode 100644 index 0000000..effc11d --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/NBChannel.java @@ -0,0 +1,209 @@ +package com.eactive.eai.adapter.socket.service; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.common.util.Logger; + +import java.io.IOException; +import java.net.Socket; + +import java.nio.ByteBuffer; +import java.nio.BufferOverflowException; + +import java.nio.channels.ByteChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.Selector; +import java.nio.channels.SelectionKey; + +import java.util.Iterator; + +public class NBChannel implements ByteChannel { + + SocketChannel channel; + Selector selector; + Selector writeSelector; + ByteBuffer pendingMessage; + Logger logger ; + long timeout; + + public NBChannel(SocketChannel channel, long timeout) throws IOException { + + this.channel = channel; + this.selector = Selector.open(); + this.writeSelector = Selector.open(); + this.channel.register( this.selector, SelectionKey.OP_READ ); + this.channel.register( this.writeSelector, SelectionKey.OP_WRITE ); + this.timeout = timeout; + + pendingMessage = ByteBuffer.allocate( 4096 ); + pendingMessage.clear(); + logger = SocketLogManager.getInstance().getLogger(); + } + + public int read(ByteBuffer dst) throws IOException { + if ( dst.capacity() == 0 || !dst.hasRemaining() ) return 0; + int y = 0; + boolean isDone = false; + + if ( pendingMessage.position() > 0 ) { + if ( pendingMessage.position() <= dst.remaining() ) { + y += pendingMessage.position(); + byte[] data = new byte[ pendingMessage.position() ]; + pendingMessage.flip(); + pendingMessage.get( data ); + dst.put( data, 0, data.length ); + pendingMessage.clear(); + } else { + int shiftCount = dst.remaining(); + y += shiftCount; + byte[] data = new byte[ shiftCount ]; + pendingMessage.flip(); + pendingMessage.get( data ); + pendingMessage.position( pendingMessage.limit() ); + + dst.put( data, 0, data.length ); + shiftBuffer( pendingMessage, shiftCount ); + isDone = true; + } + } + + if ( isDone ) return y; + selector.select( timeout ); + y += this.channel.read( dst ); + return y; + } + + private void shiftBuffer(ByteBuffer buffer, int shiftBytes) { + int pos = buffer.position(); + if ( pos <= shiftBytes ) { + buffer.clear(); + return; + } + byte[] tmpBuff = new byte[ pos ]; + buffer.flip(); + buffer.get( tmpBuff ); + + buffer.clear(); + buffer.put( tmpBuff, shiftBytes, tmpBuff.length - shiftBytes ); + } + + public int write(ByteBuffer src) throws IOException { + + try { + writeSelector.select( timeout ); + } catch(Exception e) { + throw new IOException("Write Select Error"); + } + + Iterator it = writeSelector.selectedKeys().iterator(); + int writtenBytes = 0; + SelectionKey key = null; + + while ( it.hasNext() ) { + key = (SelectionKey)it.next(); + it.remove(); + if ( key.isWritable() ) { + writtenBytes = this.channel.write( src ); + } + } + + return writtenBytes; + } + + public boolean isConnected() throws IOException { + + if ( !isOpen() ) { + logger.info( CommonLib.getMessage("BICEAIASO003", new String[]{"", getSocketInfo()} )); + return false; + } + + boolean flag = false; + + if ( this.channel.isConnected() && this.channel.socket().isBound() ) { + ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 ); + tmpBuffer.clear(); + int i = channel.read( tmpBuffer ); + if ( i > 0 ) { + try { + pendingMessage.put( tmpBuffer.array() ); + } catch ( BufferOverflowException e ) { + throw new IOException("Socket 어플리케이션 프로토콜 에러 발생 : " + e.getMessage()); + } + } + flag = true; + if ( i == -1 ) { + flag = false; + } + } else { + flag = false; + } + + return flag; + } + + public void wakeup() { + try { + if ( selector != null && selector.isOpen() ) { + selector.wakeup(); + writeSelector.wakeup(); + } + } catch (Throwable e) {} + } + + public void close() { + if ( this.channel == null || !this.channel.isOpen() ) return; + +// try { +// if ( selector != null && selector.isOpen() ) { +// selector.wakeup(); +// writeSelector.close(); +// } +// this.channel.socket().close(); +// this.channel.close(); +// this.selector.close(); +// this.writeSelector.close(); +// } catch (Throwable e) {} + + try {// 20250910 npe + if (selector != null) { + if (selector.isOpen()) { + selector.wakeup(); + } + this.selector.close(); + } + + if (writeSelector != null) { + writeSelector.close(); + } + + if (this.channel != null) { + if (this.channel.socket() != null) { + this.channel.socket().close(); + } + this.channel.close(); + } + } catch (IOException e) { + e.printStackTrace(); // 최소한 로그는 남기는 것이 좋음 + } + } + + public Socket getSocket() { + return this.channel.socket(); + } + + public boolean isOpen() { + if ( this.channel == null || !this.channel.isOpen() ) return false; + + return this.channel.socket().isConnected(); + } + + private String getSocketInfo() { + StringBuffer connInfo = new StringBuffer(); + + connInfo.append("Local Address="); + connInfo.append( getSocket().getLocalAddress().getHostAddress()).append(":").append(getSocket().getLocalPort()).append(", "); + connInfo.append("Remote Address="); + connInfo.append( getSocket().getInetAddress().getHostAddress()).append(":").append(getSocket().getPort()); + + return connInfo.toString(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/socket/service/OutboundChannel.java b/src/com/eactive/eai/adapter/socket/service/OutboundChannel.java new file mode 100644 index 0000000..4f07869 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/OutboundChannel.java @@ -0,0 +1,75 @@ +package com.eactive.eai.adapter.socket.service; + +import java.util.Iterator; +import java.util.Vector; + +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; + +public class OutboundChannel +{ + private Vector connectionList; + + public OutboundChannel(long sessionTimeout) { + connectionList = new Vector(); + } + + public void addConnection( SocketService connection ) throws Exception { + synchronized ( this.connectionList ) { + SocketService svc = connection; + if ( svc.getContext().isStarted() && svc.isActive() ) { + if ( connectionList.size() == 0 ) { + SocketAdapterManager.getInstance().changeAdapterStatus( connection, true ); + } + this.connectionList.add( connection ); + } + } + } + + public int getPoolSize() { + return connectionList.size(); + } + + public Object getConnection() throws Exception { + synchronized ( this.connectionList ) { + if ( this.connectionList.size() > 0 ) { + try { + SocketService svc = (SocketService) connectionList.remove( 0 ); + if ( svc.getContext().isStarted() && svc.isActive() ) { + return svc; + } + } catch(Exception e) { + e.printStackTrace(); + } + } + } + return null; + } + + public void removeConnection( Object connection ) throws Exception { + synchronized ( this.connectionList ) { + int size = this.connectionList.size(); + for( int i=0; i < size; i++ ) { + Object x = this.connectionList.elementAt( i ); + if ( x == connection ) { + this.connectionList.remove( i ); + break; + } + } + } + } + + public void removeAllConnection() throws Exception { + this.connectionList.clear(); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + for(Iterator iter = connectionList.iterator(); iter.hasNext();) { + Object key = iter.next(); + sb.append("\n ▣ " + key); + } + + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/OutboundChannelManager.java b/src/com/eactive/eai/adapter/socket/service/OutboundChannelManager.java new file mode 100644 index 0000000..5ad5588 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/OutboundChannelManager.java @@ -0,0 +1,104 @@ +package com.eactive.eai.adapter.socket.service; + +import java.util.HashMap; +import java.util.Iterator; + +public class OutboundChannelManager { + + private static OutboundChannelManager instance = new OutboundChannelManager(); + private HashMap pool = new HashMap() ; + + public OutboundChannelManager() { + } + + public static OutboundChannelManager getInstance() { + return instance; + } + + public void stop() { + this.removeAll(); + } + + public void removeAll() { + pool.clear(); + } + + public void start(String adapterGroupName, OutboundChannel channel) { + this.addConnectionGroup(adapterGroupName, channel); + } + + // Adapter Group Connection 을 한번에 등록한다. + public synchronized void addConnectionGroup(String adapterGroupName, OutboundChannel channel) { + OutboundChannel oc = pool.get( adapterGroupName ); + if ( oc == null ) { + synchronized ( pool ) { + oc = pool.get( adapterGroupName ); + if ( oc == null ) { + pool.put( adapterGroupName, channel ); + } + } + } + } + + public void addConnection( String adapterGroupName, SocketService connection ) { + OutboundChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) return; + try { + channel.addConnection( connection ); + } catch( Exception e ) {} + } + + public void stop(String adapterGroupName) { + // adapterGroupName의 Connection stop & clear + OutboundChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) return; + try { + channel.removeAllConnection(); + } catch ( Exception e ) {} + + pool.remove( adapterGroupName ); + } + + public OutboundChannel getChannel( String adapterGroupName ) { + return (OutboundChannel) pool.get( adapterGroupName ); + } + + public boolean hasChannel( String adapterGroupName ) { + return pool.containsKey( adapterGroupName ); + } + + public SocketService getConnection( String adapterGroupName ) { + OutboundChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) return null; + + SocketService connection = null; + try { + connection = (SocketService) channel.getConnection(); + } catch ( Exception e ) { } + + return connection; + } + + public void removeConnection ( String adapterGroupName, Object connection ) { + OutboundChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) return; + try { + channel.removeConnection( connection ); + } catch (Exception e) {} + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append("\n■ OutboundChannelManager : "); + try { + for(Iterator iter = pool.keySet().iterator(); iter.hasNext();) { + String key = iter.next(); + sb.append("\n ▣ " + key + " : " + pool.get(key).getPoolSize()); + } + } catch(Exception e) { + e.printStackTrace(); + } + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/OutboundClient.java b/src/com/eactive/eai/adapter/socket/service/OutboundClient.java new file mode 100644 index 0000000..bb4686d --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/OutboundClient.java @@ -0,0 +1,798 @@ +//package com.eactive.eai.adapter.socket.service; +// +//import java.io.IOException; +//import java.net.InetAddress; +//import java.net.Socket; +//import java.nio.ByteBuffer; +// +////import com.eactive.eai.adapter.socket.common.BoundedLinkedQueue; +//import com.eactive.eai.adapter.socket.common.CommonLib; +//import com.eactive.eai.adapter.socket.common.DiagLogger; +//import com.eactive.eai.adapter.socket.common.SocketAdapterException; +//import com.eactive.eai.adapter.socket.config.ConfigurationContext; +//import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +////import com.eactive.eai.adapter.socket.common.DiagLogger; +//import java.net.InetSocketAddress; +//import java.nio.channels.SocketChannel; +// +//public class OutboundClient extends Thread implements SocketService { +// +// protected ConfigurationContext context; +// protected boolean active; +// protected NBChannel channel; +// protected Exception lastError; +// protected boolean retryFlag; +// protected int sendCount; +// protected int recvCount; +// protected long firstActivity; +// protected long lastActivity; +// protected ByteBuffer incomingMessage; +// protected ByteBuffer outgoingMessage; +// protected ByteBuffer lenBuffer; +// protected int currentState; +// protected Logger logger; +// protected static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); +// protected OutboundControl control; +// +// public OutboundClient(ConfigurationContext context) { +// String name = this.getName(); +// this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) ); +// +// this.context = context; +// active = true; +// retryFlag = true; +// +// sendCount = 0; +// recvCount = 0; +// firstActivity = System.currentTimeMillis(); +// lastActivity = System.currentTimeMillis(); +// +// incomingMessage = null; +// outgoingMessage = null; +// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() ); +// lenBuffer.clear(); +// this.control = null; +// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL; +// logger = SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName()); +// } +// +// protected int getTraceLevel() { +// return context.getTraceLevel(); +// } +// /** +// * @return Returns the context. +// */ +// public ConfigurationContext getContext() { +// return context; +// } +// +// protected boolean isSyncMode() { +// return context.isSyncMode(); +// } +// +// protected boolean isAckProtocol() { +// return context.isAckProtocol(); +// } +// +// protected long getTimeout() { +// return ( this.context.getTimeout() * 1000L ); +// } +// +// protected boolean isSocketReuse() { +// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); +// } +// +// public void run() { +// +// String socketInfo = ""; +// +// while ( active && retryFlag ) { +// try { +// openChannel(); +// if ( !socketInfo.equals( getSocketInfo(this.getCurrentSocket()) ) ) { +// socketInfo = getSocketInfo( this.getCurrentSocket() ); +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO001", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); +// } +// } +// if ( currentState == CommonLib.NEGOTIATING_PROTOCOL ) { +// if ( !negotiateProtocol() ) { +// if ( active ) { +// waitRecoverConnection(); +// } +// continue; +// } else { +// currentState = CommonLib.PROCESSING_PROTOCOL; +// } +// } +// +// onMessage(); +// +// if ( control == null ) { +// continue; +// } +// +// doRequest(); +// +// if ( !isSocketReuse() ) { +// closeChannel(); +// } +// +// } catch (Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// +// if ( this.control != null ) { +// lastError = new SocketAdapterException( errMsg ); +// wakeup(); +// } +// if ( active && retryFlag ) { +// waitRecoverConnection(); +// } +// } +// } +// +// try { +// closeChannel(); +// } catch( Throwable e ) {} +// +// SocketAdapterManager.getInstance().removeConnection( this ); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO002", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); +// } +// +// interrupt(); +// } +// +// protected String getReadingMessage() { +// String rMsg = ""; +// if ( incomingMessage != null && incomingMessage.position() > 0 ) { +// byte[] dMsg = new byte[ incomingMessage.position() ]; +// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length ); +// rMsg = CommonLib.getDumpMessage( dMsg ); +// } +// return rMsg; +// } +// +// protected String getWritingMessage() { +// String rMsg = ""; +// if ( outgoingMessage != null ) { +// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ]; +// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length ); +// rMsg = CommonLib.getDumpMessage( debugMsg ); +// } +// return rMsg; +// } +// +// protected String getSocketInfo(Socket socket) { +// StringBuffer connInfo = new StringBuffer(); +// +// connInfo.append("Local Address="); +// connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", "); +// connInfo.append("Remote Address="); +// connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort()); +// +// return connInfo.toString(); +// } +// +// protected synchronized void onMessage() { +// try { +// if ( this.control == null ) { +// this.wait( 1000L ); +// } +// if ( retryFlag && this.control == null ) { +// checkConnection(); +// } +// this.lastError = null; +// } catch ( InterruptedException ie ) {} +// } +// +// public void wakeup() { +// this.control.setLastError( this.lastError ); +// this.control.wakeup(); +// this.control = null; +// if ( retryFlag ) { +// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this ); +// } +// } +// +// public synchronized void notifyMessage() { +// this.notify(); +// } +// +// public synchronized void setControl(Object control) { +// this.control = (OutboundControl) control; +// this.control.setRespTimeout( getTimeout() ); +// } +// +// +// public int getCurrentState() { +// return this.currentState; +// } +// +// protected void resetCount() { +// this.recvCount = 0; +// this.sendCount = 0; +// } +// +// public boolean isConnected() { +// boolean flag = false; +// try { +// flag = this.channel.isConnected(); +// } catch( Exception e ) {} +// return flag; +// } +// +// public void checkActivity() { +// long currentTime = System.currentTimeMillis(); +// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) { +// this.resetCount(); +// } +// } +// /** +// * NEGOTIATING PROTOCOL WITH REMOTE SERVER, WITH ACK-PROTOCOL +// * 1. SEND '|' +// * 2. RECV 'ACK|NACK ...' +// * 3. RETURN TRUE/FALSE +// */ +// +// protected boolean negotiateProtocol() { +// +// boolean success = false; +// this.checkActivity(); +// lastActivity = System.currentTimeMillis(); +// try { +// if ( isSyncMode() ) { +// processWriteMessage( CommonLib.SYNC_PROTOCOL_MESSAGE ); +// } else { +// processWriteMessage( CommonLib.ASYNC_PROTOCOL_MESSAGE ); +// } +// sendCount++; +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo( getCurrentSocket() ), getWritingMessage()})); +// } +// +// lenBuffer.clear(); +// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) ); +// processReadMessage( incomingMessage ); +// recvCount++; +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), this.getSocketInfo( getCurrentSocket() ), getReadingMessage()})); +// } +// +// if ( CommonLib.compare( incomingMessage.array(), CommonLib.ACK_MESSAGE ) ) { +// success = true; +// } else { +// // 메시지수신 +// logger.error( CommonLib.getMessage("BECEAIASO005", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) ); +// logger.error( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), this.getSocketInfo(getCurrentSocket()), getReadingMessage()})); +// } +// +// } catch ( Exception e ) { +// String errMsg = ""; +// if ( lenBuffer.position() > 0 ) { +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "negotiateProtocol", e.getMessage(), "수신메시지", getReadingMessage() } ); +// } else { +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "negotiateProtocol", e.getMessage(), "송신메시지", getWritingMessage() } ); +// } +// logger.error( errMsg , e); +// } +// lenBuffer.clear(); +// return success; +// } +// +// protected void processWriteAckMessage() throws Exception { +// try { +// processWriteMessage( CommonLib.ACK_MESSAGE ); +// } catch( Exception e ) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteAckMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// throw new Exception("ACK메시지 송신에러 : " + e.getMessage() ); +// } +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(CommonLib.ACK_MESSAGE) })); +// } +// } +// +// protected void processReadAckMessage() throws Exception { +// +// try { +// lenBuffer.clear(); +// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) ); +// processReadMessage( incomingMessage ); +// } catch (Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadAckMessage", e.getMessage(), "송신메시지", getWritingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// lenBuffer.clear(); +// throw new Exception("ACK메시지 수신에러 : " + e.getMessage() ); +// } +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// +// if ( CommonLib.compare( incomingMessage.array(), CommonLib.ACK_MESSAGE ) ) { +// lenBuffer.clear(); +// return; +// } else { +// // 메시지수신 +// logger.error( CommonLib.getMessage("BECEAIASO006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())})); +// if ( logger != errLogger ) { +// errLogger.error( CommonLib.getMessage("BECEAIASO006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// lenBuffer.clear(); +// throw new IOException("송신에 대한 ACK 메시지 수신에러"); +// } +// } +// +// protected void checkConnection() { +// try { +// boolean flag = false; +// if ( this.control != null ) return; +// +// synchronized ( this ) { +// if ( channel == null ) return; +// flag = channel.isConnected(); +// } +// +// if ( active && this.control == null && !flag ) { +// waitRecoverConnection(); +// } +// } catch( Exception e ) { +// if ( active ) { +// waitRecoverConnection(); +// } +// } +// } +// +// +// // RESPONSE MODE의 경우 +// protected void doRequest() throws Exception { +// +// try { +// openChannel(); +// } catch(IOException e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "doRequest의 openChannel", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// lastError = new SocketAdapterException( errMsg ); +// wakeup(); +// if ( active ) { +// waitRecoverConnection(); +// } +// return; +// } +// +// this.checkActivity(); +// lastActivity = System.currentTimeMillis(); +// +// try { +// +// processWriteMessage( this.control.getRequest() ); +// +// sendCount++; +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), getSocketInfo(getCurrentSocket()), getWritingMessage()})); +// } +// +// if ( isAckProtocol() ) { +// processReadAckMessage(); +// } +// +// if ( !isSyncMode() ) { +// wakeup(); +// return; +// } +// +// outgoingMessage.clear(); +// lenBuffer.clear(); +// +// // 동기인 경우, SYNC +// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) ); +// processReadMessage( incomingMessage ); +// +// recvCount++; +// +// this.control.setResponse( incomingMessage.array() ); +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// +// if ( isAckProtocol() ) { +// processWriteAckMessage(); +// } +// +// incomingMessage.clear(); +// lenBuffer.clear(); +// +// wakeup(); +// +// } catch( Exception e) { +// String errMsg = ""; +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "송신메시지", CommonLib.getDumpMessage( this.control.getRequest() ) } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// +// if ( lenBuffer.position() > 0 ) { +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// } +// +// lastError = new SocketAdapterException( errMsg ); +// +// wakeup(); +// +// if ( active ) { +// waitRecoverConnection(); +// } +// } +// } // end of doRequest() +// +// /** +// * Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다. +// * +// */ +// public synchronized void waitRecoverConnection() { +// try { +// if ( !retryFlag ) return; +// this.currentState = CommonLib.NEGOTIATING_PROTOCOL; +// try { closeChannel(); } catch(Exception ie) {} +// if ( retryFlag && SocketAdapterManager.getInstance().addError( this ) ) { +// this.wait(); +// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL; +// } +// } catch ( InterruptedException e ) {} +// } +// +// /** +// * Socket Recovery Manager에 의해 recovery되면 Socket Recovery Manager에 의해 통지된다. +// * +// */ +// public synchronized void notifyRecoverConnection() { +// +// if ( !this.retryFlag ) return; +// +// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL; +// +// this.notify(); +// } +// +// public boolean idle(long timeout) { +// long idleTime = System.currentTimeMillis() - this.lastActivity; +// +// return ( idleTime > timeout ); +// } +// +// /** +// * @param buffer +// * @return +// * @throws Exception +// */ +// protected int readLength( ByteBuffer buffer ) throws Exception { +// int length = 0; +// +// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout(); +// long start = System.currentTimeMillis(); +// long msecs = waitTime; +// +// while ( buffer.position() < buffer.capacity() ) { +// while ( buffer.position() < buffer.capacity() ) { +// length = channel.read( buffer ); +// +// waitTime = msecs - (System.currentTimeMillis() - start); +// +// if ( waitTime <= 0 ) { +// byte[] lmsg = new byte[ buffer.position() ]; +// System.arraycopy( buffer.array(), 0, lmsg, 0, lmsg.length ); +// String errMsg = CommonLib.getMessage("BECEAIASO004", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", "X'" + CommonLib.byte2Hex( lmsg )+ "'" }); +// logger.error( errMsg ); +// +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// throw new Exception( errMsg ); +// } +// +// if ( length < 1 ) break; +// } +// if(length == -1) { +// if ( buffer.position() > 0 ) { +// throw new Exception( CommonLib.getMessage("BECEAIASO002", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) ); +// } else { +// String errMsg = CommonLib.getMessage("BICEAIASO003", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}); +// if(logger.isInfoEnabled()){ +// logger.info( errMsg ); +// } +// throw new Exception( errMsg ); +// } +// } +// +// if ( buffer.position() == buffer.capacity() ) { +// length = checkLengthField( buffer ); +// } +// } +// return length; +// } +// +// +// protected void processReadMessage( ByteBuffer buffer ) throws Exception { +// int i = 0; +// boolean isDone = false; +// buffer.clear(); +// +// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout(); +// long start = System.currentTimeMillis(); +// long msecs = waitTime; +// +// while ( !isDone ) { +// +// while ( buffer.position() < buffer.capacity() ) { +// i = channel.read( buffer ); +// +// waitTime = msecs - (System.currentTimeMillis() - start); +// +// if ( waitTime <= 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", getReadingMessage() }); +// logger.error( errMsg ); +// +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// throw new Exception( CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "", "" }) ); +// } +// +// if ( i < 1 ) break; +// } +// +// if(i == -1) { +// throw new Exception( CommonLib.getMessage("BECEAIASO002", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) ); +// } else if ( buffer.position() == buffer.capacity() ) { +// isDone = true; +// } +// } // end of while +// } // end of readData +// +// protected void processWriteMessage( byte[] data ) throws IOException { +// +// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() ); +// outgoingMessage.clear(); +// outgoingMessage.put( makeLengthField( data.length ) ); +// outgoingMessage.put( data ); +// outgoingMessage.flip(); +// +// long writeStart = System.currentTimeMillis(); +// +// int expectedWrite = outgoingMessage.capacity(); +// int writtenByte = channel.write( outgoingMessage ); +// +// if ( expectedWrite != writtenByte ) { +// ByteBuffer buf = null; +// while ( writtenByte < expectedWrite ) { +// buf = ByteBuffer.allocate( expectedWrite - writtenByte ); +// buf.clear(); +// buf.put( outgoingMessage.array(), writtenByte, buf.capacity() ); +// writtenByte += channel.write( buf ); +// if ( expectedWrite == writtenByte ) return; +// long waitTime = System.currentTimeMillis() - writeStart; +// if ( waitTime >= getTimeout() ) { +// throw new IOException("메시지 송신 타임아웃"); +// } +// } +// } +// } +// +// protected byte[] makeLengthField(int length) { +// byte[] lenField = new byte[ lenBuffer.capacity() ]; +// +// if ( lenField.length == 2 ) { +// lenBuffer.clear(); +// lenBuffer.putShort( (short) (length & 0xFFFF) ); +// lenField = lenBuffer.array(); +// } else if ( lenField.length == 4 ) { +// lenBuffer.clear(); +// lenBuffer.putInt( length ); +// lenField = lenBuffer.array(); +// } else { +// String lenStr = CommonLib.getFormatString( length, lenField.length ); +// lenField = lenStr.getBytes(); +// } +// +// return lenField; +// } +// +// protected int checkLengthField(ByteBuffer buffer) throws SocketAdapterException { +// int length = 0; +// +// if ( buffer.capacity() == 2 ) { +// length = ( buffer.getShort(0) & 0xFFFF ); +// } else if ( buffer.capacity() == 4 ) { +// length = ( buffer.getInt(0) ); +// if ( length < 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO007", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } else { +// String lenStr = new String( buffer.array() ); +// try { +// length = Integer.parseInt( lenStr ); +// } catch ( NumberFormatException e ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO007", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } +// +// return length; +// } +// +// public boolean isActive() { +// return retryFlag; +// } +// +// public synchronized void shutdown() { +// +// active = false; +// retryFlag = false; +// SocketAdapterManager.getInstance().removeError( this ); +// try { +// this.notify(); +// } catch( Exception e ) {} +// +// try { +// if ( this.channel != null ) { +// this.channel.wakeup(); +// } +// } catch ( Throwable e ) {} +// +// try { +// closeChannel(); +// } catch (Exception e) {} +// +// SocketAdapterManager.getInstance().removeError( this ); +// } +// +// public Socket getCurrentSocket() { +// return channel.getSocket(); +// } +// +// public boolean connect() { +// +// try { +// openChannel(); +// return true; +// } catch ( Exception e ) { +// return false; +// } +// } +// +// public void disconnect() { +// shutdown(); +// } +// +// protected synchronized void openChannel() throws IOException { +// +// if ( channel != null ) { +// try { +// if ( !channel.isConnected() ) { +// SocketAdapterManager.getInstance().removeState( this ); +// closeChannel(); +// } +// } catch(Exception e) { +// } +// } +// +// if ( channel == null || !channel.isOpen() ) { +// if (!retryFlag) return; +// +// SocketChannel socketChannel = SocketChannel.open(); +// if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") ) { +// socketChannel.socket().bind( new InetSocketAddress( InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() ) ); +// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) ); +// } else { +// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) ); +// } +// +// socketChannel.socket().setTcpNoDelay(true); +// socketChannel.configureBlocking(false); +// +// if ( isSocketReuse() ) { +// socketChannel.socket().setSoLinger(true, 0); +// } +// +// channel = new NBChannel( socketChannel, getTimeout() ); +// +// // Connection 시 통계자료 RESET +// this.firstActivity = System.currentTimeMillis(); +// this.lastActivity = this.firstActivity; +// this.sendCount = 0; +// this.recvCount = 0; +// +// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL; +// +// try { +// Thread.sleep( 300L ); +// } catch(Exception e ) {} +// +// if ( !this.isConnected() ) { +// throw new IOException("Closed by Server"); +// } +// +// if ( retryFlag ) { +// // +// SocketAdapterManager.getInstance().addConnection( this ); +// } else { +// closeChannel(); +// } +// +// } // Open Selector.... +// } +// +// public String getRemoteIPAddress() { +// return null; +// } +// protected synchronized void closeChannel() throws IOException { +// +// if(channel != null ) { +// channel.close(); +// } +// this.currentState = CommonLib.NEGOTIATING_PROTOCOL; +// +// channel = null; +// } +// +// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각 +// public String toString() { +// boolean status = true; +// StringBuffer strBuff = new StringBuffer(); +// strBuff.append(context.getAdapterGroupName()).append(","); +// strBuff.append(context.getAdapterName()).append(","); +// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); +// strBuff.append(context.getSocketType()).append(","); +// strBuff.append(context.getResponseType()).append(","); +// try { +// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// +// try { +// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// strBuff.append(this.sendCount).append(","); +// strBuff.append(this.recvCount).append(","); +// strBuff.append( status ).append(","); +// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); +// strBuff.append(CommonLib.getCurrentTime( this.lastActivity )); +// +// return strBuff.toString(); +// } +// +// public void setLastActivity() { +// } +// +// public long getFirstActivity() { +// return firstActivity; +// } +// +// public long getLastActivity() { +// return lastActivity; +// } +//} diff --git a/src/com/eactive/eai/adapter/socket/service/OutboundControl.java b/src/com/eactive/eai/adapter/socket/service/OutboundControl.java new file mode 100644 index 0000000..9cace52 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/OutboundControl.java @@ -0,0 +1,194 @@ +package com.eactive.eai.adapter.socket.service; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.common.util.Logger; + +import java.io.Serializable; + +public class OutboundControl implements Serializable { + + private static final long serialVersionUID = 1L; + private String adapterGroupName; + private byte[] response; + private byte[] request; + private Throwable lastError; + private Logger logger; + private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); + private boolean ready; + private long respTimeout; + /** + * @return Returns the code. + */ + public String getAdapterGroupName() { + return adapterGroupName; + } + /** + * @param code The code to set. + */ + public void setAdapterGroupName(String code) { + this.adapterGroupName = code; + } + /** + * @return Returns the request. + */ + public byte[] getRequest() { + return request; + } + /** + * @param request The request to set. + */ + public void setRequest(byte[] request) { + this.request = request; + } + /** + * @return Returns the resposne. + */ + public byte[] getResponse() { + return response; + } + /** + * @param resposne The resposne to set. + */ + public synchronized void setResponse(byte[] response) { + this.response = response; + } + + public OutboundControl() { + logger = SocketLogManager.getInstance().getLogger(); + ready = false; + respTimeout = 0; + } + + public OutboundControl(String adapterGroupName) { + this.adapterGroupName = adapterGroupName; + logger = SocketLogManager.getInstance().getLogger( adapterGroupName ); + } + + public byte[] callService(String adapterGroupName, byte[] message) throws Exception { + + // Connection을 얻어온다... + OutboundChannelManager mgr = OutboundChannelManager.getInstance(); + + SocketService service = null; + + long start = System.currentTimeMillis(); + long waitTime = 0; + long timeout = SocketAdapterManager.getInstance().getTimeout( adapterGroupName ); + + while ( true ) { + service = mgr.getConnection(adapterGroupName); + if ( service != null ) { + //break; + try { + //if ( service.getCurrentState() == CommonLib.PROCESSING_PROTOCOL && service.isConnected() ) { + if ( service.isActive() && service.getCurrentState() == CommonLib.PROCESSING_PROTOCOL ) { + break; + } else if ( service.isActive() ) { + mgr.addConnection( adapterGroupName, service); + } + } catch( Throwable e ) { + continue; + } + } + + waitTime = System.currentTimeMillis() - start; + if ( waitTime >= timeout ) break; + try { + Thread.sleep( 20L ); + } catch( Exception e ) { + break; + } + } + + if ( service == null ) { + String errMsg = CommonLib.getMessage("BECEAIASO008", new String[]{ this.adapterGroupName } ); + + logger.error( errMsg ); + logger.error( CommonLib.getDumpMessage( message ) ); + + if ( logger != errLogger ) { + errLogger.error( errMsg ); + errLogger.error( CommonLib.getDumpMessage( message ) ); + } + throw new Exception( errMsg ); + } + + this.setRequest( message ); + +//bmchae - 이거 버그있음 - lock에 걸림 +//System.out.println("//bmchae - 이거 버그있음 - lock에 걸림"); +//Thread.dumpStack(); + + try { + service.setControl(this); + service.notifyMessage(); + // 응답전문을 기다림... + waitReply(); + } catch( Throwable e ) { +//bmchae +//e.printStackTrace(); + String errMsg = CommonLib.getMessage("BECEAIASO008", new String[]{ this.adapterGroupName } ); + lastError = new Exception( errMsg ); + } + + if ( lastError != null ) { + String errMsg = CommonLib.getMessage("BECEAIASO009", new String[]{ lastError.getMessage() }); + + logger.error( errMsg, lastError ); + + if ( logger != errLogger ) { + errLogger.error( errMsg ); + errLogger.error( CommonLib.getDumpMessage( message ) ); + } + throw new Exception( errMsg ); + } + + return this.response; + } + + protected synchronized void waitReply() { + //synchronized(request) { + long start = System.currentTimeMillis(); + if ( respTimeout == 0 ) + respTimeout = 60000L; + try { + while ( !ready ) { + this.wait( respTimeout ); + break; + } + } catch ( InterruptedException ie ) {} + + if ( respTimeout > 0 && ( System.currentTimeMillis() - start ) >= respTimeout ) { + String errMsg = CommonLib.getMessage("BECEAIASO008", new String[]{ this.adapterGroupName } ); + lastError = new Exception( errMsg ); + } + //} + } + + public void setRespTimeout(long timeout) { + this.respTimeout = timeout; + } + + public synchronized void wakeup() { + //synchronized(request) { + this.ready = true; + try { + this.notify(); + } catch( Throwable e ) {} + //} + } + + /** + * @return Returns the lastError. + */ + public Throwable getLastError() { + return lastError; + } + /** + * @param lastError The lastError to set. + */ + public synchronized void setLastError(Throwable lastError) { + this.lastError = lastError; + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/OutboundServer.java b/src/com/eactive/eai/adapter/socket/service/OutboundServer.java new file mode 100644 index 0000000..4c1f8cb --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/OutboundServer.java @@ -0,0 +1,1028 @@ +//package com.eactive.eai.adapter.socket.service; +// +//import java.io.IOException; +//import java.net.Socket; +//import java.nio.BufferOverflowException; +//import java.nio.ByteBuffer; +//import java.nio.channels.ClosedSelectorException; +//import java.nio.channels.SelectionKey; +//import java.nio.channels.Selector; +//import java.nio.channels.SocketChannel; +//import java.util.Iterator; +// +//import com.eactive.eai.adapter.socket.common.CommonLib; +//import com.eactive.eai.adapter.socket.common.DiagLogger; +//import com.eactive.eai.adapter.socket.common.SocketAdapterException; +//import com.eactive.eai.adapter.socket.config.ConfigurationContext; +//import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public class OutboundServer extends Thread implements SocketService { +// +// private ConfigurationContext context; +// private SocketChannel socketChannel; +// private SocketServer proxy; +// private Selector selector; +// private SelectionKey key; +// private boolean active; +// +// private int sendCount; +// private int recvCount; +// private long firstActivity; +// private long lastActivity; +// +// private ByteBuffer incomingMessage; +// private ByteBuffer outgoingMessage; +// +// private ByteBuffer lenBuffer; +// private ByteBuffer pendingMessage; +// +// private Exception lastError; +// private Logger logger; +// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); +// +// private OutboundControl control; +// private int currentState; +// private boolean shutdownFlag; +// private String remoteIPAddress; +// +// public OutboundServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) { +// String name = this.getName(); +// this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) ); +// +// this.context = context; +// this.socketChannel = socketChannel; +// this.proxy = proxy; +// +// sendCount = 0; +// recvCount = 0; +// firstActivity = System.currentTimeMillis(); +// lastActivity = System.currentTimeMillis(); +// +// incomingMessage = null; +// outgoingMessage = null; +// +// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() ); +// lenBuffer.clear(); +// pendingMessage = ByteBuffer.allocate( 4096 ); +// pendingMessage.clear(); +// +// this.control = null; +// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL; +// +// remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress(); +// active = true; +// shutdownFlag = false; +// logger = SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName()); +// } +// +// private boolean isSyncMode() { +// return this.context.isSyncMode(); +// } +// +// private boolean isAckProtocol() { +// return this.context.isAckProtocol(); +// } +// +// private int getTraceLevel() { +// return context.getTraceLevel(); +// } +// +// private long getTimeout() { +// return ( this.context.getTimeout() * 1000L ); +// } +// +// private boolean isSocketReuse() { +// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); +// } +// +// /** +// * @return Returns the context. +// */ +// public ConfigurationContext getContext() { +// return context; +// } +// +// public void run() { +// SocketAdapterManager.getInstance().addConnection( this ); +// String socketInfo = this.getSocketInfo(this.socketChannel); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO001", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); +// } +// +// while ( active ) { +// try { +// openSelector(); +// +// if ( currentState == CommonLib.NEGOTIATING_PROTOCOL ) { +// if ( !negotiateProtocol() ) { +// active = false; +// continue; +// } else { +// currentState = CommonLib.PROCESSING_PROTOCOL; +// } +// } +// +// onMessage(); +// +// if ( control == null ) continue; +// +// doRequest(); +// +// if ( shutdownFlag ) { +// active = false; +// } +// +// if ( !isSocketReuse() ) { +// active = false; +// } +// +// } catch (Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "openSelector", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// active = false; +// if ( this.control != null ) { +// lastError = new SocketAdapterException( errMsg ); +// wakeup(); +// } +// continue; +// } +// } +// +// try { +// closeSelector(); +// } catch(Throwable e) { } +// +// SocketAdapterManager.getInstance().removeConnection( this ); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO002", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); +// } +// +// proxy.quiesceShutdown(this); +// +// interrupt(); +// +// } +// +// private String getReadingMessage() { +// String rMsg = ""; +// if ( incomingMessage != null && incomingMessage.position() > 0 ) { +// byte[] dMsg = new byte[ incomingMessage.position() ]; +// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length ); +// rMsg = CommonLib.getDumpMessage( dMsg ); +// } +// return rMsg; +// } +// +// private String getWritingMessage() { +// String rMsg = ""; +// if ( outgoingMessage != null ) { +// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ]; +// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length ); +// rMsg = CommonLib.getDumpMessage( debugMsg ); +// } +// return rMsg; +// } +// +// private String getSocketInfo(SocketChannel channel) { +// StringBuffer connInfo = new StringBuffer(); +// +// connInfo.append("Local Address="); +// connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", "); +// connInfo.append("Remote Address="); +// connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort()); +// +// return connInfo.toString(); +// } +// +// private synchronized void onMessage() { +// try { +// if ( this.control == null ) { +// this.wait( 1000L ); +// } +// if ( !shutdownFlag && this.control == null ) { +// checkConnection(); +// } +// this.lastError = null; +// } catch ( InterruptedException ie ) {} +// } +// +// public void wakeup() { +// this.control.setLastError( this.lastError ); +// this.control.wakeup(); +// this.control = null; +// if ( !shutdownFlag && active ) { +// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this ); +// } +// } +// +// public synchronized void notifyMessage() { +// this.notify(); +// } +// +// public synchronized void setControl(Object control) { +// this.control = (OutboundControl) control; +// this.control.setRespTimeout( getTimeout() ); +// } +// +// private void checkConnection() { +// try { +// boolean flag = false; +// if ( this.control != null ) return; +// +// synchronized ( this ) { +// flag = isConnected(); +// } +// if ( this.control == null && !flag ) { +// this.active = false; +// this.control = null; +// } +// } catch( Exception e ) { +// this.active = false; +// this.control = null; +// } +// } +// +// private boolean negotiateProtocol() { +// boolean success = false; +// boolean goon = true; +// long start = System.currentTimeMillis(); +// lenBuffer.clear(); +// +// while( goon ) { +// try { +// int selected = selector.select( 1000L ); +// if( selected == 0 ) { +// long waitTime = System.currentTimeMillis() - start; +// if ( lenBuffer.position() > 0 && waitTime >= getTimeout() ) { +// String errMsg = CommonLib.getMessage("BECEAIASO004", new String[]{context.getAdapterName(), getSocketInfo( this.socketChannel), Long.toString(getTimeout()), "수신", getReadingMessage() }); +// logger.error( errMsg ); +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// goon = false; +// } else { +// goon = isConnected(); +// } +// continue; +// } +// } catch(IOException e) { +// if ( lenBuffer.position() > 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "negotiateProtocol의 select", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// } +// goon = false; +// } catch(ClosedSelectorException e ) { +// goon = false; +// continue; +// } catch(Exception e) {} +// +// if ( selector == null || !selector.isOpen() ) { +// goon = false; +// continue; +// } +// +// Iterator iterator = selector.selectedKeys().iterator(); +// +// while( iterator.hasNext() ) { +// key = iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// if(key.isReadable()) { // is Readable ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // +// try { +// +// start = System.currentTimeMillis(); +// if( processReadMessage() ) { // Read Done +// byte[] message = incomingMessage.array(); +// +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), this.getSocketInfo(this.socketChannel), CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// this.checkActivity(); +// lastActivity = System.currentTimeMillis(); +// recvCount++; +// +// start = System.currentTimeMillis(); +// +// incomingMessage.clear(); +// lenBuffer.clear(); +// +// if ( this.context.getResponseType().equals( new String(message) ) ) { +// makeFormat( CommonLib.ACK_MESSAGE ); +// success = true; +// } else { +// makeFormat( CommonLib.NACK_MESSAGE ); +// logger.error( CommonLib.getMessage("BECEAIASO005", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) ); +// } +// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); +// } +// } catch(Exception e) { +// if ( lenBuffer.position() > 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "negotiateProtocol의 processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// } +// goon = false; +// success = false; +// } finally { +// if(!goon) continue; +// } +// } // end of readable... +// +// if( key.isWritable() ) { // is Writable ? - - - - - - - - - - - - - - - - - - - // +// try { +// if( processWriteMessage() ) { +// +// sendCount++; +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo(this.socketChannel), getWritingMessage()})); +// } +// +// outgoingMessage.clear(); +// lenBuffer.clear(); +// socketChannel.register(selector, SelectionKey.OP_READ); // write end. so read only. +// return success; +// } +// } catch(IOException e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "negotiateProtocol의 processWriteMessage", e.getMessage(), "송신메시지", getWritingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// goon = false; +// success = false; +// } +// } // end of writables... +// } // End of while(iterator.hasNext()) +// } // enf of while - active +// return success; +// } +// +// private void processWriteAckMessage() throws Exception { +// try { +// makeFormat( CommonLib.ACK_MESSAGE ); +// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE ); +// processWriteMessage(); +// sendCount++; +// } catch( Exception e ) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteAckMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// throw new Exception("ACK메시지 송신에러 : " + e.getMessage() ); +// } +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo(this.socketChannel), CommonLib.getDumpMessage(CommonLib.ACK_MESSAGE) })); +// } +// +// } +// +// private void processReadAckMessage() throws Exception { +// +// long start = System.currentTimeMillis(); +// boolean goon = true; +//// boolean isRight = true; +// +// lenBuffer.clear(); +// socketChannel.register(selector, SelectionKey.OP_READ); +// +// while( goon ) { +// try { +// int selected = selector.select( 1000L ); +// if( selected == 0 ) { +// long waitTime = System.currentTimeMillis() - start; +// if ( lenBuffer.position() > 0 && waitTime >= getTimeout() ) { +// String errMsg = CommonLib.getMessage("BECEAIASO004", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), Long.toString(getTimeout()), "수신", getReadingMessage() }); +// logger.error( errMsg ); +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// goon = false; +// } else { +// goon = isConnected(); +// } +// continue; +// } +// } catch(IOException e) { +// goon = false; +// } catch(ClosedSelectorException e ) { +// goon = false; +// continue; +// } catch(Exception e) {} +// +// if ( selector == null || !selector.isOpen() ) { +// goon = false; +// continue; +// } +// +// Iterator iterator = selector.selectedKeys().iterator(); +// +// while( iterator.hasNext() ) { +// key = iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// if(key.isReadable()) { // is Readable ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // +// try { +// +// start = System.currentTimeMillis(); +// +// if( processReadMessage() ) { // Read Done +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), getSocketInfo(this.socketChannel), CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// +// recvCount++; +// +// if ( CommonLib.compare( incomingMessage.array(), CommonLib.ACK_MESSAGE ) ) { +// lenBuffer.clear(); +// return; +// } else { +//// isRight = false; +// goon = false; +// logger.error( CommonLib.getMessage("BECEAIASO006", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.getDumpMessage(incomingMessage.array())})); +// if ( logger != errLogger ) { +// errLogger.error( CommonLib.getMessage("BECEAIASO006", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// } +// } +// } catch(IOException e) { +// goon = false; +// } catch(SocketAdapterException e) { +// goon = false; +// } catch(Exception e) { } +// } // end of readable... +// } // End of while(iterator.hasNext()) +// } // enf of while - active +// +// lenBuffer.clear(); +// +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadAckMessage", "", "송신메시지", getWritingMessage() } ); +// logger.error( errMsg ); +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// throw new IOException("송신에 대한 ACK 메시지 수신에러"); +// +// } +// +// public void doRequest() { +// +// Iterator iterator; +// makeFormat( this.control.getRequest() ); +// +// boolean isDone = false; +// this.checkActivity(); +// +// lastActivity = System.currentTimeMillis(); +// long start = System.currentTimeMillis(); +// while( !isDone ) { +// try { +// if( selector.select( getTimeout() ) == 0) { +// if ( ( start - System.currentTimeMillis() ) <= getTimeout() ) continue; +// +// isDone = true; +// active = false; +// String errMsg = CommonLib.getMessage("BECEAIASO004", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), Long.toString(getTimeout()), "수신", getReadingMessage() }); +// logger.error( errMsg ); +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// +// lastError = new SocketAdapterException( errMsg ); +// wakeup(); +// continue; +// } +// } catch(Exception e) { +// String errMsg = ""; +// if ( lenBuffer.position() > 0 ) { +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "select", e.getMessage(), "수신메시지", getReadingMessage() } ); +// } else { +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "select", e.getMessage(), "송신메시지", getWritingMessage() } ); +// } +// logger.error( errMsg , e); +// +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// +// lastError = new SocketAdapterException( errMsg ); +// +// active = false; +// isDone = true; +// wakeup(); +// continue; +// } +// +// if ( selector == null || !selector.isOpen() ) { +// isDone = true; +// continue; +// } +// +// iterator = selector.selectedKeys().iterator(); +// +// while(iterator.hasNext()) { +// key = iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// +// /** +// * Write the message to the target +// */ +// if( key.isWritable() ) { // is Writable ? - - - - - - - - - - - - - - - - - - - // +// try { +// if( processWriteMessage() ) { +// +// sendCount++; +// +// if ( getTraceLevel() >= DiagLogger.DEBUG) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), getSocketInfo(this.socketChannel), getWritingMessage()})); +// } +// +// if ( isAckProtocol() ) { +// processReadAckMessage(); +// } +// +// if ( !isSyncMode() ) { +// wakeup(); +// return; +// } +// +// outgoingMessage.clear(); +// lenBuffer.clear(); +// +// socketChannel.register(selector, SelectionKey.OP_READ); +// } +// } catch(Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteMessage", e.getMessage(), "송신메시지", getWritingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// +// lastError = new SocketAdapterException( errMsg ); +// +// active = false; +// wakeup(); +// return; +// } +// } // end of writables... +// +// if(key.isReadable()) { // is Readable ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // +// try { +// if( processReadMessage() ) { // Read Done +// +// recvCount++; +// if ( isSyncMode() ) { +// this.control.setResponse( incomingMessage.array() ); +// } +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), getSocketInfo(this.socketChannel), CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// +// if ( isAckProtocol() ) { +// processWriteAckMessage(); +// } +// +// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE ); // write end. so read only. +// isDone = true; +// wakeup(); +// return; +// } +// } catch(Exception e) { +// String errMsg = ""; +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "송신메시지", CommonLib.getDumpMessage( this.control.getRequest() ) } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// +// if ( lenBuffer.position() > 0 ) { +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// } +// +// this.lastError = new SocketAdapterException( errMsg ); +// active = false; +// wakeup(); +// return; +// } +// } // end of readable... +// } // End of while(iterator.hasNext()) +// } // enf of while - isDone +// } +// +// public synchronized void shutdown() { +// //*2005.10.17 +// active = false; +// shutdownFlag = true; +// //this.currentState = CommonLib.NEGOTIATING_PROTOCOL; +// +// try { +// notify(); +// } catch ( Exception e ) {} +// +// try { +// closeSelector(); +// } catch( Exception e ) {} +// +// //*/ +// // interrupt(); +// } +// +// public Socket getCurrentSocket() { +// return socketChannel.socket(); +// } +// +// public boolean connect() { +// return true; +// } +// +// public boolean isActive() { +// return (!shutdownFlag); +// } +// +// public void disconnect() { +// shutdown(); +// proxy.quiesceShutdown(this); +// interrupt(); +// } +// +// public boolean idle(long timeout) { +// long idleTime = System.currentTimeMillis() - this.lastActivity; +// +// return ( idleTime > timeout ); +// } +// +// public String getRemoteIPAddress() { +// return this.remoteIPAddress; +// } +// +// private void openSelector() throws IOException { +// +// if ( selector == null || !selector.isOpen() ) { +// selector = Selector.open(); +// +// // Connection 시 통계자료 RESET +// this.firstActivity = System.currentTimeMillis(); +// this.lastActivity = this.firstActivity; +// this.sendCount = 0; +// this.recvCount = 0; +// +// socketChannel.socket().setTcpNoDelay(true); +// socketChannel.configureBlocking(false); +// socketChannel.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ ); +// } +// } +// +// private void closeSelector() throws IOException { +// if(selector != null) { +// selector.wakeup(); +// +// for(Iterator iterator = selector.keys().iterator(); iterator.hasNext();) +// try { +// key = iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// key.cancel(); +// if(socketChannel != null) { +// Socket socket = socketChannel.socket(); +// if(socket != null) { +// socket.setSoLinger(true, 0); +// try { socket.close(); } catch(Exception e) {} +// } +// socketChannel.close(); +// } +// } catch(IOException ioexception) { } +// +// selector.close(); +// } +// } +// +// private boolean processReadMessage() throws Exception { +// int i = 0; +// boolean flag = false; +// +// if ( pendingMessage.position() > 0 && lenBuffer.hasRemaining() ) { +// if ( pendingMessage.position() <= lenBuffer.remaining() ) { +// byte[] data = new byte[ pendingMessage.position() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// lenBuffer.put( data ); +// pendingMessage.clear(); +// } else { +// byte[] data = new byte[ lenBuffer.remaining() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// lenBuffer.put( data ); +// pendingMessage.position( pendingMessage.limit() ); +// shiftBuffer( pendingMessage, data.length ); +// } +// if ( lenBuffer.position() == lenBuffer.capacity() ) flag = true; +// } +// +// while ( lenBuffer.position() < lenBuffer.capacity() ) { +// i = socketChannel.read( lenBuffer ); +// if ( i <= 0 ) break; +// if ( lenBuffer.position() == lenBuffer.capacity() ) flag = true; +// } +// +// if(i == -1) { +// if ( lenBuffer.position() > 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO002", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) ); +// } else { +// String errMsg = CommonLib.getMessage("BICEAIASO003", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}); +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( errMsg ); +// } +// throw new SocketAdapterException( errMsg ); +// } +// } +// if ( lenBuffer.position() != lenBuffer.capacity() ) return false; +// +// int length = 0; +// +// try { +// if ( flag ) { +// length = checkLengthField( lenBuffer ); +// incomingMessage = ByteBuffer.allocate( length ); +// incomingMessage.clear(); +// } +// } catch(Exception le) { +// throw le; +// } +// +// i = 0; +// +// if ( pendingMessage.position() > 0 && incomingMessage.hasRemaining()) { +// if ( pendingMessage.position() <= incomingMessage.remaining() ) { +// byte[] data = new byte[ pendingMessage.position() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// incomingMessage.put( data ); +// pendingMessage.clear(); +// } else { +// byte[] data = new byte[ incomingMessage.remaining() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// lenBuffer.put( data ); +// pendingMessage.position( pendingMessage.limit() ); +// shiftBuffer( pendingMessage, data.length ); +// } +// if ( incomingMessage.position() == incomingMessage.capacity() ) return true; +// } +// +// while ( incomingMessage.position() < incomingMessage.capacity()) { +// i = socketChannel.read(incomingMessage); +// if ( i <= 0 ) break; +// } +// +// if(i == -1) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO002", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) ); +// } else { +// if ( incomingMessage.position() == incomingMessage.capacity() ) { +// return true; +// } else { +// return false; +// } +// } +// } +// +// private void shiftBuffer(ByteBuffer buffer, int shiftBytes) { +// int pos = buffer.position(); +// if ( pos <= shiftBytes ) { +// buffer.clear(); +// return; +// } +// byte[] tmpBuff = new byte[ pos ]; +// buffer.flip(); +// buffer.get( tmpBuff ); +// +// buffer.clear(); +// buffer.put( tmpBuff, shiftBytes, tmpBuff.length - shiftBytes ); +// } +// +// private boolean processWriteMessage() throws IOException { +// +// outgoingMessage.flip(); +// +// long writeStart = System.currentTimeMillis(); +// int expectedWrite = outgoingMessage.capacity(); +// int writtenByte = socketChannel.write( outgoingMessage ); +// +// if ( expectedWrite != writtenByte ) { +// ByteBuffer buf = null; +// while ( writtenByte < expectedWrite ) { +// buf = ByteBuffer.allocate( expectedWrite - writtenByte ); +// buf.clear(); +// buf.put( outgoingMessage.array(), writtenByte, buf.capacity() ); +// writtenByte += write( buf ); +// if ( expectedWrite == writtenByte ) return true; +// long waitTime = System.currentTimeMillis() - writeStart; +// if ( waitTime >= getTimeout() ) { +// throw new IOException("메시지 송신 타임아웃"); +// } +// } +// } +// return true; +// } +// +// public int write(ByteBuffer src) throws IOException { +// +// this.socketChannel.register( this.selector, SelectionKey.OP_WRITE ); +//// int selected = 0; +// +// try { +//// selected = +// selector.select( getTimeout() ); +// } catch(Exception e) { +// throw new IOException("Write Select Error"); +// } +// +// Iterator it = selector.selectedKeys().iterator(); +// int writtenBytes = 0; +// SelectionKey key = null; +// +// while ( it.hasNext() ) { +// key = (SelectionKey)it.next(); +// it.remove(); +// if ( key.isWritable() ) { +// writtenBytes = this.socketChannel.write( src ); +// } +// } +// return writtenBytes; +// } +// +// // Writing전에 확인... +// public boolean isConnected() throws IOException { +// boolean flag = true; +// +// if ( socketChannel.isConnected() && socketChannel.socket().isBound() ) { +// ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 ); +// tmpBuffer.clear(); +// int i = socketChannel.read( tmpBuffer ); +// if ( i > 0 ) { +// try { +// pendingMessage.put( tmpBuffer.array() ); +// } catch ( BufferOverflowException e ) { +// throw new IOException("Socket 어플리케이션 프로토콜에러 발생 : " + e.getMessage()); +// } +// } +// if ( i == -1 ) { +// flag = false; +// } +// } else { +// flag = false; +// } +// +// return flag; +// } +// +// public int getCurrentState() { +// return this.currentState; +// } +// +// private void resetCount() { +// this.recvCount = 0; +// this.sendCount = 0; +// } +// +// public void checkActivity() { +// long currentTime = System.currentTimeMillis(); +// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) { +// this.resetCount(); +// } +// } +// +// private byte[] makeLengthField(int length) { +// byte[] lenField = new byte[ lenBuffer.capacity() ]; +// +// if ( lenBuffer.capacity() == 2 ) { +// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() ); +// tmpBuffer.clear(); +// tmpBuffer.putShort( (short) (length & 0xFFFF) ); +// lenField = tmpBuffer.array(); +// } else if ( lenBuffer.capacity() == 4 ) { +// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() ); +// tmpBuffer.clear(); +// tmpBuffer.putInt( length ); +// lenField = tmpBuffer.array(); +// } else { +// String lenStr = CommonLib.getFormatString( length, lenBuffer.capacity() ); +// lenField = lenStr.getBytes(); +// } +// +// return lenField; +// } +// +// private int checkLengthField(ByteBuffer buffer) throws SocketAdapterException { +// +// int length = 0; +// +// if ( buffer.capacity() == 2 ) { +// length = ( buffer.getShort(0) & 0xFFFF ); +// } else if ( buffer.capacity() == 4 ) { +// length = ( buffer.getInt(0) ); +// if ( length < 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO007", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } else { +// String lenStr = new String( buffer.array() ); +// try { +// length = Integer.parseInt( lenStr ); +// } catch ( NumberFormatException e ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO007", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } +// +// return length; +// } +// +// private void makeFormat( byte[] data ) { +// +// int i = data.length + lenBuffer.capacity(); +// +// if(outgoingMessage == null) { +// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() ); +// } else { +// if( i != outgoingMessage.capacity() ) +// outgoingMessage = ByteBuffer.allocate( i ); +// } +// outgoingMessage.clear(); +// outgoingMessage.put( makeLengthField( data.length ) ); +// outgoingMessage.put( data ); +// } +// +// /** +// * @return Returns the socketchannel. +// */ +// public SocketChannel getSocketchannel() { +// return socketChannel; +// } +// /** +// * @param socketchannel The socketchannel to set. +// */ +// public void setSocketchannel(SocketChannel socketchannel) { +// this.socketChannel = socketchannel; +// } +// +// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각 +// public String toString() { +// boolean status = true; +// StringBuffer strBuff = new StringBuffer(); +// strBuff.append(context.getAdapterGroupName()).append(","); +// strBuff.append(context.getAdapterName()).append(","); +// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); +// strBuff.append(context.getSocketType()).append(","); +// strBuff.append(context.getResponseType()).append(","); +// +// try { +// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// +// try { +// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// +// strBuff.append(this.sendCount).append(","); +// strBuff.append(this.recvCount).append(","); +// strBuff.append( status ).append(","); +// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); +// strBuff.append(CommonLib.getCurrentTime( this.lastActivity )); +// +// return strBuff.toString(); +// } +// +// public void setLastActivity() { +// } +// +// public long getFirstActivity() { +// return firstActivity; +// } +// +// public long getLastActivity() { +// return lastActivity; +// } +//} diff --git a/src/com/eactive/eai/adapter/socket/service/ReaderClient.java b/src/com/eactive/eai/adapter/socket/service/ReaderClient.java new file mode 100644 index 0000000..4fee0ea --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/ReaderClient.java @@ -0,0 +1,577 @@ +//package com.eactive.eai.adapter.socket.service; +// +//import java.io.IOException; +//import java.net.InetAddress; +//import java.net.Socket; +//import java.nio.ByteBuffer; +// +//import com.eactive.eai.adapter.socket.common.CommonLib; +//import com.eactive.eai.adapter.socket.common.DiagLogger; +//import com.eactive.eai.adapter.socket.common.SocketAdapterException; +//import com.eactive.eai.adapter.socket.config.ConfigurationContext; +//import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//import java.net.InetSocketAddress; +//import java.nio.channels.SocketChannel; +// +//public class ReaderClient extends Thread implements SocketService { +// +// private ConfigurationContext context; +// private boolean active; +// private NBChannel channel; +// +// private int sendCount; +// private int recvCount; +// private long firstActivity; +// private long lastActivity; +// +// private boolean retryFlag; +// +// private ByteBuffer incomingMessage; +// +// private ByteBuffer lenBuffer; +// private Logger logger; +// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); +// +// private WriterClient writer; +// +// public ReaderClient(ConfigurationContext context) { +// +// String name = this.getName(); +// this.setName( context.getAdapterName() + "-CONNECTION-READER" + name.substring( name.lastIndexOf("-")) ); +// +// this.context = context; +// active = true; +// retryFlag = true; +// +// incomingMessage = null; +// +// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() ); +// lenBuffer.clear(); +// +// sendCount = 0; +// recvCount = 0; +// firstActivity = System.currentTimeMillis(); +// lastActivity = firstActivity; +// +// logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() ); +// +// } +// +// public void addSendCount() { +// this.sendCount++; +// } +// +// public void setLastActivity(long lastAccess) { +// this.lastActivity = lastAccess; +// } +// +// public void shutdownWriter() { +// // 2005.10.17 -- +// shutdown(); +// writer = null; +// } +// +// private int getTraceLevel() { +// return context.getTraceLevel(); +// } +// +// private long getTimeout() { +// return ( this.context.getTimeout() * 1000L ); +// } +// +// private boolean isSocketReuse() { +// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); +// } +// +// /** +// * @return Returns the context. +// */ +// public ConfigurationContext getContext() { +// return context; +// } +// +//// private boolean isSyncMode() { +//// return context.isSyncMode(); +//// } +// +// public void run() { +// +// String socketInfo = ""; +// +// while ( retryFlag ) { +// +// active = true; +// +// try { +// openChannel(); +// socketInfo = this.getSocketInfo( this.getCurrentSocket() ); +// } catch(Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// +// waitRecoverConnection(); +// continue; +// } +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); +// } +// +//// int msgLen = 0; +// +// writer = new WriterClient( this.context, this.channel, this ); +// writer.start(); +// +// while ( active ) { +// try { +// lenBuffer.clear(); +// +// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) ); +// processReadMessage( incomingMessage ); +// +// this.checkActivity(); +// +// lastActivity = System.currentTimeMillis(); +// recvCount++; +// +// // 메시지수신 +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// +// incomingMessage.clear(); +// lenBuffer.clear(); +// +// InboundControl control = new InboundControl( context.getAdapterGroupName(), context.getAdapterName(), getTimeout() ); +// control.setRequest( incomingMessage.array() ); +// control.setResponseType( context.getResponseType() ); +// +//// byte[] rtnValue = null; +// +// try { +//// rtnValue = +// control.request(); +// } catch( Exception e ) { +//// rtnValue = +//// e.getMessage().getBytes(); +// +// logger.error( e.getMessage(), e ); +// logger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage( control.getRequest() )})); +// +// if ( logger != errLogger ) { +// errLogger.error( e.getMessage(), e ); +// errLogger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage( control.getRequest() )})); +// } +// } +// +// if ( !isSocketReuse() ) { +// active = false; +// closeChannel(); +// } +// } catch( Exception e ) { +// String errMsg = ""; +// if ( lenBuffer.position() > 0 ) { +// errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// } +// +// if ( errMsg.length() > 0 ) { +// logger.error( errMsg , e); +// +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// } +// +// active = false; +// writer.shutdown(); +// +// waitRecoverConnection(); +// lenBuffer.clear(); +// continue; +// } +// } // end of active +// } // end of retry +// +// try { +// if ( writer != null ) { +// writer.shutdown(); +// } +// } catch( Throwable e ) {} +// +// try { +// closeChannel(); +// } catch( Throwable e ) {} +// +// SocketAdapterManager.getInstance().removeConnection( this ); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); +// } +// +// interrupt(); +// +// } // end of startup ... +// +// private String getReadingMessage() { +// String rMsg = ""; +// if ( incomingMessage != null && incomingMessage.position() > 0 ) { +// byte[] dMsg = new byte[ incomingMessage.position() ]; +// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length ); +// rMsg = CommonLib.getDumpMessage( dMsg ); +// } +// return rMsg; +// } +// +// private String getSocketInfo(Socket socket) { +// StringBuffer connInfo = new StringBuffer(); +// +// connInfo.append("Local Address="); +// connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", "); +// connInfo.append("Remote Address="); +// connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort()); +// +// return connInfo.toString(); +// } +// +// public boolean idle(long timeout) { +// long idleTime = System.currentTimeMillis() - this.lastActivity; +// +// return ( idleTime > timeout ); +// } +// +// public void setControl(Object control) { +// } +// +// public void notifyMessage() { +// } +// +// public int getCurrentState() { +// return CommonLib.PROCESSING_PROTOCOL; +// } +// +// private void resetCount() { +// this.recvCount = 0; +// this.sendCount = 0; +// } +// +// public boolean isConnected() { +// return true; +// } +// +// public String getRemoteIPAddress() { +// return null; +// } +// +// public void checkActivity() { +// long currentTime = System.currentTimeMillis(); +// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) { +// this.resetCount(); +// } +// } +// +// /** +// * Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다. +// * +// */ +// public synchronized void waitRecoverConnection() { +// try { +// if ( !retryFlag ) return; +// +// try { closeChannel(); } catch(Exception ie) {} +// if ( retryFlag && SocketAdapterManager.getInstance().addError( this ) ) { +// wait(); +// } +// } catch ( InterruptedException e ) {} +// } +// +// /** +// * Socket Recovery Manager에 의해 recovery되면 Socket Recovery Manager에 의해 통지된다. * +// */ +// +// public synchronized void notifyRecoverConnection() { +// notify(); +// } +// +// private int readLength( ByteBuffer buffer ) throws Exception { +// int length = 0; +// +// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout(); +// long start = 0; +// long msecs = waitTime; +// +// while ( buffer.position() < buffer.capacity() ) { +// while ( buffer.position() < buffer.capacity() ) { +// length = channel.read( buffer ); +// +// if ( start == 0L && buffer.position() > 0 ) { +// start = System.currentTimeMillis(); +// } else if ( start > 0 ) { +// waitTime = msecs - (System.currentTimeMillis() - start); +// } +// +// if ( waitTime <= 0 ) { +// byte[] lmsg = new byte[ buffer.position() ]; +// System.arraycopy( buffer.array(), 0, lmsg, 0, lmsg.length ); +// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", "X'" + CommonLib.byte2Hex( lmsg )+ "'" }); +// +// logger.error( errMsg ); +// +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// throw new Exception( errMsg ); +// } +// if ( length < 1 ) break; +// } +// //* 2005.10.17 +// //if ( !active ) throw new Exception("어뎁터중지명령에 의해 CLOSED되었습니다."); +// // *정상적인 Normal Shutdown을 위한 확인... +// +// if ( length == 0 && buffer.position() == 0 && !retryFlag ) { +// String errMsg = CommonLib.getMessage("BICEAIASI004", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}); +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( errMsg ); +// } +// throw new Exception( errMsg ); +// } +// +// if(length == -1) { +// if ( buffer.position() > 0 ) { +// throw new Exception( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) ); +// } else { +// String errMsg = CommonLib.getMessage("BICEAIASI004", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}); +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( errMsg ); +// } +// throw new Exception( errMsg ); +// } +// } +// +// if ( buffer.position() == buffer.capacity() ) { +// length = checkLengthField( buffer ); +// } +// +// } +// +// return length; +// } +// +// +// private void processReadMessage( ByteBuffer buffer ) throws Exception { +// int i = 0; +// boolean isDone = false; +// buffer.clear(); +// +// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout(); +// long start = System.currentTimeMillis(); +// long msecs = waitTime; +// +// while ( !isDone ) { +// +// while ( buffer.position() < buffer.capacity() ) { +// i = channel.read( buffer ); +// +// waitTime = msecs - (System.currentTimeMillis() - start); +// +// if ( waitTime <= 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", getReadingMessage() }); +// +// logger.error( errMsg ); +// +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// throw new Exception( CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "", "" }) ); +// } +// +// if ( i < 1 ) break; +// } +// +// if(i == -1) { +// throw new Exception( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) ); +// } else if ( buffer.position() == buffer.capacity() ) { +// isDone = true; +// } +// } // end of while +// } // end of readData +// +// private int checkLengthField(ByteBuffer buffer) throws SocketAdapterException { +// int length = 0; +// +// if ( buffer.capacity() == 2 ) { +// length = ( buffer.getShort(0) & 0xFFFF ); +// } else if ( buffer.capacity() == 4 ) { +// length = ( buffer.getInt(0) ); +// if ( length < 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } else { +// String lenStr = new String( buffer.array() ); +// try { +// length = Integer.parseInt( lenStr ); +// } catch ( NumberFormatException e ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } +// return length; +// +// } +// +// public boolean isActive() { +// return retryFlag; +// } +// +// public synchronized void shutdown() { +// +// active = false; +// retryFlag = false; +// +// try { +// notify(); +// } catch( Exception e ) {} +// +// //* 2005.10.17 +// try { +// this.channel.wakeup(); +// } catch( Throwable e ) {} +// +// /* +// try { +// writer.shutdown(); +// } catch( Exception e ) {} +// */ +// +// // to gracefully shutdown the thread +// try { +// closeChannel(); +// } catch (Exception e) {} +// //interrupt(); +// } +// +// public Socket getCurrentSocket() { +// return channel.getSocket(); +// } +// +// public boolean connect() { +// if ( !retryFlag ) return true; +// +// try { +// openChannel(); +// return true; +// } catch ( Exception e ) { +// return false; +// } +// } +// +// public void disconnect() { +// shutdown(); +// } +// +// private synchronized void openChannel() throws IOException { +// +// if ( channel == null || !channel.isOpen() ) { +// // Sleep Time조정.... HotDeploy시 Multi Connection 현상방지... +// //try { +// // Thread.sleep( 1000L ); +// //} catch( InterruptedException e ) { +// // if ( !retryFlag ) return; +// //} +// if ( !retryFlag ) return; +// +// SocketChannel socketChannel = SocketChannel.open(); +// //if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") && context.getLocalPortNumber() > 1024 ) { +// if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") ) { +// socketChannel.socket().bind( new InetSocketAddress( InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() ) ); +// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) ); +// //socket = new Socket(context.getHostName(), context.getPortNumber(), InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() ); +// } else { +// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) ); +// //socket = new Socket(context.getHostName(), context.getPortNumber()); +// } +// +// socketChannel.socket().setTcpNoDelay(true); +// socketChannel.configureBlocking(false); +// +// if ( isSocketReuse() ) { +// socketChannel.socket().setSoLinger(true, 0); +// } +// +// channel = new NBChannel( socketChannel, getTimeout() ); +// +// // Connection 시 통계자료 RESET +// this.firstActivity = System.currentTimeMillis(); +// this.lastActivity = this.firstActivity; +// this.sendCount = 0; +// this.recvCount = 0; +// +// try { +// Thread.sleep( 300L ); +// } catch( Exception e ) {} +// +// if ( !this.isConnected() ) { +// throw new IOException("Closed by Server"); +// } +// +// if ( retryFlag ) { +// // +// SocketAdapterManager.getInstance().addConnection( this ); +// } else { +// closeChannel(); +// } +// +// } +// } +// +// private synchronized void closeChannel() throws IOException { +// +// if(channel != null ) { +// channel.close(); +// } +// channel = null; +// } // +// +// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, SYNC, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각 +// public String toString() { +// boolean status = true; +// StringBuffer strBuff = new StringBuffer(); +// strBuff.append(context.getAdapterGroupName()).append(","); +// strBuff.append(context.getAdapterName()).append(","); +// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); +// strBuff.append(context.getSocketType()).append(","); +// strBuff.append(context.getResponseType()).append(","); +// try { +// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// +// try { +// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// strBuff.append(this.sendCount).append(","); +// strBuff.append(this.recvCount).append(","); +// strBuff.append( status ).append(","); +// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); +// strBuff.append(CommonLib.getCurrentTime( this.lastActivity )); +// +// return strBuff.toString(); +// } +// +// public void setLastActivity() { +// } +// +// public long getFirstActivity() { +// return firstActivity; +// } +// +// public long getLastActivity() { +// return lastActivity; +// } +//} diff --git a/src/com/eactive/eai/adapter/socket/service/ReaderServer.java b/src/com/eactive/eai/adapter/socket/service/ReaderServer.java new file mode 100644 index 0000000..c4949aa --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/ReaderServer.java @@ -0,0 +1,613 @@ +//package com.eactive.eai.adapter.socket.service; +// +//import java.io.IOException; +//import java.net.Socket; +//import java.nio.BufferOverflowException; +//import java.nio.ByteBuffer; +//import java.nio.channels.ClosedSelectorException; +//import java.nio.channels.SelectionKey; +//import java.nio.channels.Selector; +//import java.nio.channels.SocketChannel; +//import java.util.Iterator; +// +//import com.eactive.eai.adapter.socket.common.CommonLib; +//import com.eactive.eai.adapter.socket.common.DiagLogger; +//import com.eactive.eai.adapter.socket.common.SocketAdapterException; +//import com.eactive.eai.adapter.socket.config.ConfigurationContext; +//import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public class ReaderServer extends Thread implements SocketService { +// +// private ConfigurationContext context; +// private SocketChannel socketChannel; +// private SocketServer proxy; +// private Selector selector; +// private SelectionKey key; +// +// private boolean active; +// +// // 상태정보 +// private int sendCount; +// private int recvCount; +// private long firstActivity; +// private long lastActivity; +// +// // IO BUFFER +// private ByteBuffer incomingMessage; +// private ByteBuffer lenBuffer; +// +// // pending message for checking operation +// private ByteBuffer pendingMessage; +// // Logger +// private Logger logger; +// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); +// private WriterServer writer; +// private boolean shutdownFlag; +// private String remoteIPAddress; +// +// public ReaderServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) { +// String name = this.getName(); +// this.setName( context.getAdapterName() + "-CONNECTION-READER" + name.substring( name.lastIndexOf("-")) ); +// +// this.context = context; +// this.socketChannel = socketChannel; +// this.proxy = proxy; +// this.writer = null; +// +// sendCount = 0; +// recvCount = 0; +// firstActivity = System.currentTimeMillis(); +// lastActivity = System.currentTimeMillis(); +// +// incomingMessage = null; +// +// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() ); +// lenBuffer.clear(); +// +// pendingMessage = ByteBuffer.allocate( 4096 ); +// pendingMessage.clear(); +// +// logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName()); +// +// remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress(); +// active = true; +// shutdownFlag = false; +// } +// +//// private boolean isSyncMode() { +//// return this.context.isSyncMode(); +//// } +//// +//// private boolean isAckProtocol() { +//// return this.context.isAckProtocol(); +//// } +// +// private long getTimeout() { +// return ( this.context.getTimeout() * 1000L ); +// } +// +//// private boolean isSocketReuse() { +//// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); +//// } +// +// private int getTraceLevel() { +// return context.getTraceLevel(); +// } +// /** +// * @return Returns the context. +// */ +// public ConfigurationContext getContext() { +// return context; +// } +// +// public String getRemoteIPAddress() { +// return this.remoteIPAddress; +// } +// +// public void run() { +// SocketAdapterManager.getInstance().addConnection( this ); +// String socketInfo = this.getSocketInfo(this.socketChannel); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); +// } +// +// try { +// openSelector(); +// } catch(IOException e) { +// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "openSelector", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// active = false; +// } +// +// +//// Iterator iterator; +// if ( active ) { +// try { +// writer = new WriterServer( this.context, this.socketChannel, this, this.selector ); +// writer.start(); +// } catch( Exception e ) { } +// } +// +// long start = System.currentTimeMillis(); +// +// while( active ) { +// try { +// int selected = selector.select( 1000L ); +// if( selected == 0 ) { +// long waitTime = System.currentTimeMillis() - start; +// if ( lenBuffer.position() > 0 && waitTime >= getTimeout() ) { +// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), socketInfo, Long.toString(getTimeout()), "수신", getReadingMessage() }); +// logger.error( errMsg ); +// if ( logger != errLogger ) { +// errLogger.error( errMsg ); +// } +// active = false; +// } else if ( lenBuffer.position() > 0 ){ +// active = isConnected(); +// } else if ( shutdownFlag && lenBuffer.position() == 0 ) { +// active = false; +// } +// continue; +// } +// //* 2005.10.17 +// if ( shutdownFlag && lenBuffer.position() == 0 ) { +// active = false; +// continue; +// } +// } catch(IOException e) { +// if ( lenBuffer.position() > 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "select", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// } +// active = false; +// } catch(ClosedSelectorException e ) { +// continue; +// } catch(Exception e) {} +// +// if ( selector == null || !selector.isOpen() ) continue; +// +// Iterator iterator = selector.selectedKeys().iterator(); +// +// while( iterator.hasNext() ) { +// key = iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// if(key.isReadable()) { // is Readable ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // +// try { +// start = System.currentTimeMillis(); +// if( processReadMessage() ) { // Read Done +// byte[] message = incomingMessage.array(); +// +// if ( getTraceLevel() >= DiagLogger.DEBUG ) { +// logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())})); +// } +// this.checkActivity(); +// lastActivity = System.currentTimeMillis(); +// recvCount++; +// +// incomingMessage.clear(); +// lenBuffer.clear(); +// +// InboundControl control = new InboundControl( context.getAdapterGroupName(), context.getAdapterName(), getTimeout() ); +// control.setRequest( message ); +// control.setResponseType( context.getResponseType() ); +// +//// byte[] rtnValue = null; +// +// try { +// control.request(); +// } catch( Exception e ) { +//// rtnValue = e.getMessage().getBytes(); +// logger.error( e.getMessage(), e ); +// logger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo,CommonLib.getDumpMessage( control.getRequest() )})); +// if ( logger != errLogger ) { +// errLogger.error( e.getMessage(), e ); +// errLogger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage( control.getRequest() )})); +// } +// } +// +// start = System.currentTimeMillis(); +// +// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); +// +// if ( shutdownFlag ) active = false; +// } +// } catch(Exception e) { +// if ( lenBuffer.position() > 0 ) { +// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// } +// active = false; +// +// } finally { +// if(!active) continue; +// } +// } // end of readable... +// } // End of while(iterator.hasNext()) +// } // enf of while - active +// +// try { +// try { +// if ( writer != null ) { +// writer.shutdown(); +// } +// } catch( Throwable e ) {} +// closeSelector(); +// } catch(Throwable e) {} +// +// SocketAdapterManager.getInstance().removeConnection( this ); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); +// } +// +// proxy.quiesceShutdown(this); +// +// interrupt(); +// +// } +// +// private String getReadingMessage() { +// String rMsg = ""; +// if ( incomingMessage != null && incomingMessage.position() > 0 ) { +// byte[] dMsg = new byte[ incomingMessage.position() ]; +// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length ); +// rMsg = CommonLib.getDumpMessage( dMsg ); +// } +// return rMsg; +// } +// +// private String getSocketInfo(SocketChannel channel) { +// StringBuffer connInfo = new StringBuffer(); +// +// connInfo.append("Local Address="); +// connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", "); +// connInfo.append("Remote Address="); +// connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort()); +// +// return connInfo.toString(); +// } +// +// public boolean idle(long timeout) { +// long idleTime = System.currentTimeMillis() - this.lastActivity; +// return ( idleTime > timeout ); +// } +// +// public void addSendCount() { +// this.sendCount++; +// } +// +// public void setLastActivity(long lastAccess) { +// this.lastActivity = lastAccess; +// } +// +// public void shutdownWriter() { +// shutdown(); +// writer = null; +// } +// +// public boolean isActive() { +// return shutdownFlag; +// } +// +// public synchronized void shutdown() { +// //* 2005.10.17 +// active = false; +// shutdownFlag = true; +// +// try { +// notify(); +// } catch( Exception e ) {} +// +// try { +// if ( selector != null && selector.isOpen() ) { +// selector.wakeup(); +// } +// } catch (Throwable e) {} +// +// //* to gracefully shutdown the thread +// //* 2005.10.17 +// //try { +// // writer.shutdown(); +// //} catch( Exception e ) {} +// +// try { +// closeSelector(); +// } catch( Exception e ) {} +// //*/ +// //interrupt(); +// } +// +// public Socket getCurrentSocket() { +// return socketChannel.socket(); +// } +// +// public boolean connect() { +// return true; +// } +// +// public void disconnect() { +// shutdown(); +// proxy.quiesceShutdown(this); +// } +// +// private void openSelector() throws IOException { +// +// if ( selector == null || !selector.isOpen() ) { +// selector = Selector.open(); +// // Connection 시 통계자료 RESET +// this.firstActivity = System.currentTimeMillis(); +// this.lastActivity = this.firstActivity; +// this.sendCount = 0; +// this.recvCount = 0; +// +// socketChannel.socket().setTcpNoDelay(true); +// socketChannel.configureBlocking(false); +// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE ); +// } +// +// } +// +// private void closeSelector() throws IOException { +// if(selector != null) { +// selector.wakeup(); +// +// for(Iterator iterator = selector.keys().iterator(); iterator.hasNext();) { +// try { +// key = iterator.next(); +// iterator.remove(); +// socketChannel = (SocketChannel)key.channel(); +// key.cancel(); +// if(socketChannel != null) { +// Socket socket = socketChannel.socket(); +// if(socket != null) { +// socket.setSoLinger(false, 0); +// try { socket.close(); } catch(Exception e) {} +// } +// socketChannel.close(); +// } +// } catch(IOException ioexception) { } +// } +// selector.close(); +// } +// selector = null; +// } +// +// public void setControl(Object control) { +// } +// +// public void notifyMessage() { +// } +// +// +// private boolean processReadMessage() throws Exception { +// +// int i = 0; +// boolean flag = false; +// +// if ( pendingMessage.position() > 0 && lenBuffer.hasRemaining() ) { +// if ( pendingMessage.position() <= lenBuffer.remaining() ) { +// byte[] data = new byte[ pendingMessage.position() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// lenBuffer.put( data ); +// pendingMessage.clear(); +// } else { +// byte[] data = new byte[ lenBuffer.remaining() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// lenBuffer.put( data ); +// pendingMessage.position( pendingMessage.limit() ); +// shiftBuffer( pendingMessage, data.length ); +// } +// if ( lenBuffer.position() == lenBuffer.capacity() ) flag = true; +// } +// +// while ( lenBuffer.position() < lenBuffer.capacity() ) { +// i = socketChannel.read( lenBuffer ); +// if ( i <= 0 ) break; +// if ( lenBuffer.position() == lenBuffer.capacity() ) flag = true; +// } +// +// if(i == -1) { +// if ( lenBuffer.position() > 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) ); +// } else { +// String errMsg = CommonLib.getMessage("BICEAIASI004", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}); +// if(logger.isInfoEnabled()){ +// logger.info( errMsg ); +// } +// throw new SocketAdapterException( errMsg ); +// } +// } +// +// if ( lenBuffer.position() != lenBuffer.capacity() ) return false; +// +// int length = 0; +// +// try { +// if ( flag ) { +// length = checkLengthField( lenBuffer ); +// incomingMessage = ByteBuffer.allocate( length ); +// incomingMessage.clear(); +// } +// } catch(Exception le) { +// throw le; +// } +// +// i = 0; +// +// if ( pendingMessage.position() > 0 && incomingMessage.hasRemaining()) { +// if ( pendingMessage.position() <= incomingMessage.remaining() ) { +// byte[] data = new byte[ pendingMessage.position() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// incomingMessage.put( data ); +// pendingMessage.clear(); +// } else { +// byte[] data = new byte[ incomingMessage.remaining() ]; +// pendingMessage.flip(); +// pendingMessage.get( data ); +// lenBuffer.put( data ); +// pendingMessage.position( pendingMessage.limit() ); +// shiftBuffer( pendingMessage, data.length ); +// } +// if ( incomingMessage.position() == incomingMessage.capacity() ) return true; +// } +// +// while ( incomingMessage.position() < incomingMessage.capacity()) { +// i = socketChannel.read(incomingMessage); +// if ( i <= 0 ) break; +// } +// +// if(i == -1) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) ); +// } else { +// if ( incomingMessage.position() == incomingMessage.capacity() ) { +// return true; +// } else { +// return false; +// } +// } +// } +// +// private void shiftBuffer(ByteBuffer buffer, int shiftBytes) { +// int pos = buffer.position(); +// if ( pos <= shiftBytes ) { +// buffer.clear(); +// return; +// } +// byte[] tmpBuff = new byte[ pos ]; +// buffer.flip(); +// buffer.get( tmpBuff ); +// +// buffer.clear(); +// buffer.put( tmpBuff, shiftBytes, tmpBuff.length - shiftBytes ); +// } +// +// // Writing전에 확인... +// public boolean isConnected() throws IOException { +// boolean flag = true; +// +// if ( socketChannel.isConnected() && socketChannel.socket().isBound() ) { +// ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 ); +// tmpBuffer.clear(); +// int i = socketChannel.read( tmpBuffer ); +// if ( i > 0 ) { +// try { +// pendingMessage.put( tmpBuffer ); +// } catch ( BufferOverflowException e ) { +// throw new IOException("Socket 어플리케이션 프로토콜에러 발생 : " + e.getMessage()); +// } +// } +// if ( i == -1 ) { +// flag = false; +// } +// } else { +// flag = false; +// } +// +// return flag; +// } +// +// public int getCurrentState() { +// return CommonLib.PROCESSING_PROTOCOL; +// } +// +// private void resetCount() { +// this.recvCount = 0; +// this.sendCount = 0; +// } +// +// public void checkActivity() { +// long currentTime = System.currentTimeMillis(); +// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) { +// this.resetCount(); +// } +// } +// +// private int checkLengthField(ByteBuffer buffer) throws SocketAdapterException { +// int length = 0; +// +// if ( buffer.capacity() == 2 ) { +// length = ( buffer.getShort(0) & 0xFFFF ); +// } else if ( buffer.capacity() == 4 ) { +// length = ( buffer.getInt(0) ); +// if ( length < 0 ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } else { +// String lenStr = new String( buffer.array() ); +// try { +// length = Integer.parseInt( lenStr ); +// } catch ( NumberFormatException e ) { +// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) ); +// } +// } +// return length; +// } +// +// /** +// * @return Returns the socketchannel. +// */ +// public SocketChannel getSocketchannel() { +// return socketChannel; +// } +// /** +// * @param socketchannel The socketchannel to set. +// */ +// public void setSocketchannel(SocketChannel socketchannel) { +// this.socketChannel = socketchannel; +// } +// +// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각 +// public String toString() { +// boolean status = true; +// StringBuffer strBuff = new StringBuffer(); +// strBuff.append(context.getAdapterGroupName()).append(","); +// strBuff.append(context.getAdapterName()).append(","); +// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(","); +// strBuff.append(context.getSocketType()).append(","); +// strBuff.append(context.getResponseType()).append(","); +// try { +// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// +// try { +// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(","); +// } catch( Throwable e ) { +// status = false; +// strBuff.append("?:?,"); +// } +// strBuff.append(this.sendCount).append(","); +// strBuff.append(this.recvCount).append(","); +// strBuff.append( status ).append(","); +// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(","); +// strBuff.append(CommonLib.getCurrentTime( this.lastActivity )); +// +// return strBuff.toString(); +// } +// +// public void setLastActivity() { +// } +// +// public long getFirstActivity() { +// return firstActivity; +// } +// +// public long getLastActivity() { +// return lastActivity; +// } +//} diff --git a/src/com/eactive/eai/adapter/socket/service/RecoveryManager.java b/src/com/eactive/eai/adapter/socket/service/RecoveryManager.java new file mode 100644 index 0000000..95875d8 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/RecoveryManager.java @@ -0,0 +1,84 @@ +package com.eactive.eai.adapter.socket.service; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.common.util.Logger; + +import java.util.TimerTask; +import java.util.Iterator; +import java.util.LinkedList; + + +/** + * Client Socket mode로 사용되는 connection 장애 시 일정간격으로 Recovery를 시도한다. + * Only 1 thread가 처리한다. + */ +public class RecoveryManager extends TimerTask { + + private LinkedList errorTable; + private Logger logger = SocketLogManager.getInstance().getLogger(); + + public RecoveryManager(LinkedList errorTable) { + this.errorTable = errorTable; + } + + public void run() { + + if ( errorTable.size() > 0 ) { + if(logger.isInfoEnabled()){ + logger.info( CommonLib.getMessage("BICEAIMSA029", new String[]{ Integer.toString( errorTable.size() )} ) ); + } + retryTheConnect(); + } + } + + public void retryTheConnect() { + + int count = errorTable.size(); + + SocketService aService = null; + for ( int i=0; i < count; i++) { + try { + aService = ( SocketService ) errorTable.removeFirst(); + if ( !aService.isActive() ) continue; + if ( aService.connect() ) { + InboundClient client = ( InboundClient )aService; + client.notifyRecoverConnection(); + + try { + StringBuffer connInfo = new StringBuffer(); + connInfo.append("Local Address="); + connInfo.append( aService.getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(aService.getCurrentSocket().getLocalPort()).append(", "); + connInfo.append("Remote Address="); + connInfo.append( aService.getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(aService.getCurrentSocket().getPort()); + + if(logger.isInfoEnabled()) + logger.info( CommonLib.getMessage("BICEAIMSA030", new String[]{ aService.getContext().getAdapterName(), connInfo.toString() }) ); + } catch (Throwable t) { + logger.error(t.getMessage(),t); + } + } else { + // 에러 복구에 실패하면 로깅하도록 변경. 2009.01.09 정동한 + logger.warn("[RecoveryManager:retryTheConnect]에러 복구 실패[" + aService.getContext().getAdapterName() + "]"); + errorTable.add( aService ); + } + } catch ( Throwable t ) { + //if ( aService != null && aService instanceof SocketService ){ + if ( aService != null){// 20250910 npe + errorTable.add( aService ); + } + continue; + } + } // trying to reconnect in errorTable... + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append("\n■ RecoveryManager : "); + for(Iterator iter = errorTable.iterator(); iter.hasNext();) { + sb.append("\n ▣ " + iter.next() + " : "); + } + + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/SessionChannel.java b/src/com/eactive/eai/adapter/socket/service/SessionChannel.java new file mode 100644 index 0000000..4f17e4d --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/SessionChannel.java @@ -0,0 +1,89 @@ +package com.eactive.eai.adapter.socket.service; + +import java.util.Vector; + +/** + * AdapterGroupName별 SessionChannel를 갖는다. + */ +public class SessionChannel +{ + private int defaultNumOfSessions; + private int maxNumOfSessions; + private Vector activeSessions; + private long sessionTimeout; + + public SessionChannel(int defaultNumOfSessions, int maxNumOfSessions) { + this( defaultNumOfSessions, maxNumOfSessions, 0L ); + } + + public SessionChannel(int defaultNumOfSessions, int maxNumOfSessions, long sessionTimeout) { + this.defaultNumOfSessions = defaultNumOfSessions; + this.maxNumOfSessions = maxNumOfSessions; + this.sessionTimeout = sessionTimeout * 1000; + this.activeSessions = new Vector(); + } + + public int getDefaultNumOfSessions() { + return this.defaultNumOfSessions; + } + + public int getMaxNumOfSessions() { + return this.maxNumOfSessions; + } + + public void setMaxNumOfSessions( int newNumOfSessions ) { + if ( newNumOfSessions < this.maxNumOfSessions ) return; + this.maxNumOfSessions = newNumOfSessions; + } + + public long getSessionTimeout() { + return this.sessionTimeout; + } + + public void setSessionTimeout(long timeout) { + this.sessionTimeout = timeout * 1000; + } + + /** + * SessionService를 parameter로 갖는다. + */ + public void addSession( SessionService session ) throws Exception { + this.addSession( session, true ); + } + + public void addSession( SessionService session, boolean isPermanent ) throws Exception { + synchronized ( this.activeSessions ) { + this.activeSessions.add( session ); + } + } + + public Object getSession() throws Exception { + synchronized ( this.activeSessions ) { + if ( this.activeSessions.size() > 0 ) { + //Object x = this.activeSessions.get( 0 ); + return this.activeSessions.remove( 0 ); + } else { + return null; + } + } + } + + public void removeSession( Object session ) throws Exception { + synchronized ( this.activeSessions ) { + this.activeSessions.remove( session ); + } + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + int active = 0, idle = 0; + active = (this.maxNumOfSessions - this.activeSessions.size()); + //idle = this.activeSessions.size(); + idle = this.maxNumOfSessions - active; + sb.append("SessionChannel [DefaultSessions=").append( this.defaultNumOfSessions ).append(","); + sb.append("MaxSessions=").append( this.maxNumOfSessions ).append(","); + sb.append("ActiveSessions=").append( active ).append(","); + sb.append("IdleSessions=").append( idle ).append("]"); + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/SessionManager.java b/src/com/eactive/eai/adapter/socket/service/SessionManager.java new file mode 100644 index 0000000..0d806dc --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/SessionManager.java @@ -0,0 +1,128 @@ +package com.eactive.eai.adapter.socket.service; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; + +import com.eactive.eai.adapter.socket.common.CommonLib; + +public class SessionManager { + + private static SessionManager instance = new SessionManager(); + private HashMap pool = new HashMap(); +// private Logger logger; + + public SessionManager() { +// logger = SocketLogManager.getInstance().getLogger(); + } + + public static SessionManager getInstance() { + return instance; + } + + public void stop() { + this.removeAll(); + } + + public void removeAll() { + pool.clear(); + } + + public void start(String adapterGroupName, SessionChannel channel) { + this.addSessionGroup(adapterGroupName, channel); + } + + // Adapter Group Session을 한번에 등록한다. + public synchronized void addSessionGroup(String adapterGroupName, SessionChannel channel) { + Object o = pool.get( adapterGroupName ); + if ( o == null ) { + synchronized ( pool ) { + o = pool.get( adapterGroupName ); + if ( o == null ) { + pool.put( adapterGroupName, channel ); + } + } + } + } + + public void addSession(String adapterGroupName, SessionService session) { + SessionChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) return; + try { + channel.addSession( session ); + } catch( Exception e ) {} + } + + public void removeSession(String adapterGroupName, Object session) { + SessionChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) return; + try { + channel.removeSession( session ); + } catch( Exception e ) {} + } + + public void stop(String adapterGroupName) { + // adapterGroupName의 session stop & clear + pool.remove( adapterGroupName ); + } + + public SessionChannel getChannel( String adapterGroupName ) { + return (SessionChannel) pool.get( adapterGroupName ); + } + + public boolean hasChannel( String adapterGroupName ) { + return pool.containsKey( adapterGroupName ); + } + + public SessionService getSession( String adapterGroupName ) { + SessionChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) return null; + + SessionService service = null; + try { + service = (SessionService) channel.getSession(); + } catch ( Exception e ) { } + + return service; + } + + public String getSessionInfo() { + StringBuffer strBuff = new StringBuffer(); + Object[] adapterGroupList = pool.keySet().toArray(); + if ( adapterGroupList == null || adapterGroupList.length < 1 ) { + //strBuff.append("This server don't have any session infomrations"); + strBuff.append( CommonLib.getMessage("BWCEAIMSA006") ); + return strBuff.toString(); + } + Arrays.sort( adapterGroupList ); + for( int i=0; i < adapterGroupList.length; i++ ) { + strBuff.append( this.getSessionInfo( (String)adapterGroupList[i] )).append("\n"); + } + + return strBuff.toString(); + } + + public String getSessionInfo( String adapterGroupName ) { + StringBuffer strBuff = new StringBuffer(); + SessionChannel channel = this.getChannel( adapterGroupName ); + if ( channel == null ) { + //strBuff.append("Session not found for ").append(adapterGroupName).append(" Adapter Group "); + strBuff.append( CommonLib.getMessage("BWCEAIMSA007", new String[]{ adapterGroupName }) ); + return strBuff.toString(); + } + + return strBuff.append(adapterGroupName).append("-").append( channel.toString() ).toString(); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append("\n■ SessionManager : "); + for(Iterator iter = pool.keySet().iterator(); iter.hasNext();) { + Object key = iter.next(); + sb.append("\n ▣ " + key + " : " + pool.get(key)); + } + + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/SessionService.java b/src/com/eactive/eai/adapter/socket/service/SessionService.java new file mode 100644 index 0000000..902307a --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/SessionService.java @@ -0,0 +1,160 @@ +package com.eactive.eai.adapter.socket.service; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.config.RequestDescriptor; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; + +import com.eactive.eai.common.util.Logger; + +public class SessionService extends Thread { + + private String adapterGroupName; + private boolean active; + private boolean permanent; + private Logger logger; + private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); + private InboundControl control; + + private int sendCount; + private int recvCount; + + public SessionService(String adapterGroupName, boolean permanent, int seq) { + this.setName( adapterGroupName + "-SESSION-" + Integer.toString( seq ) ); + + this.adapterGroupName = adapterGroupName; + this.active = true; + this.permanent = permanent; + this.logger = SocketLogManager.getInstance().getLogger( adapterGroupName ); + this.sendCount = 0; + this.recvCount = 0; + } + + /** + * @return Returns the adapterGroupName. + */ + public String getAdapterGroupName() { + return adapterGroupName; + } + + /** + * @param adapterGroupName The adapterGroupName to set. + */ + public void setAdapterGroupName(String adapterGroupName) { + this.adapterGroupName = adapterGroupName; + } + + /** + * @return Returns the permanent. + */ + public boolean isPermanent() { + return permanent; + } + + /** + * @param permanent The permanent to set. + */ + public void setPermanent(boolean permanent) { + this.permanent = permanent; + } + +// private int getTraceLevel() { +// return this.traceLevel; +// } + +// private boolean isSyncMode() { +// return control.isSyncMode(); +// } + + public void run() { + SocketAdapterManager.getInstance().addSession( this ); + if(logger.isDebugEnabled()) + logger.debug( CommonLib.getMessage("BICEAIASI001", new String[]{ adapterGroupName, Thread.currentThread().getName() })); + + while ( active ) { + try { + + onMessage(); + if ( control == null ) { + continue; + } + doRequest(); + + } catch (Exception e) { + if ( control != null ) { + logger.error( CommonLib.getMessage("BECEAIASI005", + new String[]{ e.getMessage(),CommonLib.getDumpMessage(control.getRequest()) } ), e ); + + if ( logger != errLogger ) { + errLogger.error( CommonLib.getMessage("BECEAIASI005", + new String[]{ e.getMessage(),CommonLib.getDumpMessage(control.getRequest()) } ), e ); + } + } + } + } + + SocketAdapterManager.getInstance().removeSession( this ); + + if(logger.isInfoEnabled()) + logger.info( CommonLib.getMessage("BICEAIASI005", new String[]{ adapterGroupName, Thread.currentThread().getName() })); + interrupt(); + } + + private synchronized void onMessage() { + try { + if ( this.control == null ) { + this.wait( 1000 ); + } + } catch ( InterruptedException ie ) {} + } + + public void wakeup() { + try { + this.control.wakeup(); + } catch( Throwable e ) {} + + this.control = null; + SessionManager.getInstance().addSession( this.adapterGroupName, this ); + } + + public synchronized void notifyMessage() { + //recvCount++; + this.notify(); + } + + private void doRequest() { + this.recvCount++; + logger.debug("[ELINK]################ <"+ Thread.currentThread().getName() +"> InboundControl 데이터: 길어서 print skip..."); //"+ new String(control.getRequest())); + RequestDescriptor descriptor = new RequestDescriptor( control ); + //RequestDescriptorTest descriptor = new RequestDescriptorTest( control ); + descriptor.request(); + + wakeup(); + + this.sendCount++; + + } // end of doRequest() + + + public synchronized void shutdown() { + active = false; + + notifyAll(); + + interrupt(); + + } + + public void setControl(InboundControl control) { + this.control = control; + + } + + public String toString() { + StringBuffer strBuff = new StringBuffer(); + + strBuff.append( this.getName() ).append("[ RecvCount = ").append( recvCount ) + .append(" SendCount = ").append( sendCount ).append(" ]"); + + return strBuff.toString(); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/SocketLogManager.java b/src/com/eactive/eai/adapter/socket/service/SocketLogManager.java new file mode 100644 index 0000000..c2d8325 --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/SocketLogManager.java @@ -0,0 +1,28 @@ +package com.eactive.eai.adapter.socket.service; + + +import com.eactive.eai.common.util.Logger; + +public class SocketLogManager { + + private static SocketLogManager instance = new SocketLogManager(); + + //Singleton + private SocketLogManager() {} + public static SocketLogManager getInstance() { return instance; } + + + public Logger getLogger( String adapterGroupName ) { + Logger logger = (Logger) Logger.getLogger("FileLogger{"+ adapterGroupName + "}"); + + return logger; + } + + public Logger getErrLogger() { + return (Logger) Logger.getLogger(Logger.LOGGER_ADAPTER_ERR); + } + + public Logger getLogger() { + return (Logger) Logger.getLogger(Logger.LOGGER_ADAPTER); + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/SocketServer.java b/src/com/eactive/eai/adapter/socket/service/SocketServer.java new file mode 100644 index 0000000..0541c7a --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/SocketServer.java @@ -0,0 +1,454 @@ +package com.eactive.eai.adapter.socket.service; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.adapter.socket.common.DiagLogger; +import com.eactive.eai.adapter.socket.common.SocketAdapterException; +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.Iterator; +import java.util.Vector; + +import java.nio.channels.ClosedSelectorException; +import java.util.HashMap; + + +public class SocketServer extends Thread implements SocketService { + + private ConfigurationContext context; + private Vector threadPool; + private boolean active; + private Selector selector; + private ServerSocketChannel serverSocketChannel; + private ServerSocket serverSocket; + private Logger logger; + private HashMap ipTable; // IP별 Connection 수 제한이 있는 경우 , KEY-RemoteIP, VALUE-Integer + + //소켓 관련 프라퍼티 정보 + public static final String PROP_GROUP_SOCKET = "socket"; + public static final String PROP_BLOCK_IP_LIST = "block.ip.list"; //연결 거부 IP 리스트 + public static final String PROP_BLOCK_SLEEP = "sleep.time"; //close 하기 전에 대기 시간 + + public SocketServer(ConfigurationContext context) { + String name = this.getName(); + this.setName( context.getAdapterName() + "-LISTENER" + name.substring( name.lastIndexOf("-")) ); + + this.context = context; + active = true; + threadPool = new Vector(); + logger = (Logger) SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName() ); + ipTable = new HashMap(); + } + + private int getTraceLevel() { + return context.getTraceLevel(); + } + + public void run() { + // Server Socket을 기동하는 순간 Connection없음을 나타내도록 Adapter Status를 false로 변경한다. + SocketAdapterManager.getInstance().changeAdapterStatus( this, false); + try { + openSelector(); + } catch(IOException e) { + logger.error(CommonLib.getMessage("BECEAIMSA029", new String[] { context.getAdapterName(), context.getHostName() + ":" + context.getPortNumber(), e.getMessage() } ), e); + active = false; + SocketAdapterManager.getInstance().stop( context.getAdapterGroupName(), context.getAdapterName() ); + } + + Iterator it; + SocketChannel channel; + SelectionKey key; + while ( active ) { + try { + // select(miliseconds) : 대기시간 + int i = selector.select(2000L); + if(i == 0) { + if ( threadPool == null || threadPool.size() == 0 ) { + SocketAdapterManager.getInstance().changeAdapterStatus( this, false ); + } + continue; + } + } catch(IOException e) { + active = false; + shutdown(); + break; + } catch( ClosedSelectorException e ) { + } catch( Exception e ) { + continue; + } + + if ( selector == null || !selector.isOpen() ) break; + + it = selector.selectedKeys().iterator(); + + while( it.hasNext() ) { + // 소켓 서버로 연결 요청이 있는 경우. + try { + key = it.next(); + it.remove(); + if ( !key.isValid() ) continue; + ServerSocketChannel server = (ServerSocketChannel)key.channel(); + if ( !server.isOpen() ){ + continue; + } + + channel = server.accept(); + + if(channel == null) continue; + + // L4에서 보내온 세션인 경우 + String remoteIp = channel.socket().getRemoteSocketAddress().toString().substring(1,channel.socket().getRemoteSocketAddress().toString().indexOf(":") ); + String blockIpList = PropManager.getInstance().getProperty(PROP_GROUP_SOCKET, PROP_BLOCK_IP_LIST); + + if (( blockIpList != null) && ( blockIpList.indexOf(remoteIp) > -1 ) ) { + + try { + long delayTime = 1000; + try { + delayTime = Long.parseLong(PropManager.getInstance().getProperty(PROP_GROUP_SOCKET, PROP_BLOCK_SLEEP)); + } catch (Exception e) {} + if ( delayTime > 0 ) + Thread.sleep(delayTime); + channel.socket().close(); + channel.close(); + } catch(IOException ie) {} + continue; + } + + if ( context.getMaxConnection() > 0 && context.getMaxConnection() <= threadPool.size() ) { + try { + for ( int inx = 0; inx < threadPool.size(); inx++){ + SocketService oldService = threadPool.get(inx); + if ( oldService.isActive()){ + logger.warn( CommonLib.getMessage("BECEAIMSA022", new String[]{ context.getAdapterName(), Integer.toString( context.getMaxConnection() ),this.getSocketInfo( oldService.getCurrentSocket() ) } ) ); + oldService.shutdown(); + } + } + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + } + // Client Socket별 (REMOTE IP) Connection 수 제한 있는 경우 + if ( context.getConnLimitPerIp() > 0 ) { + String ip = channel.socket().getInetAddress().getHostAddress(); + Integer connCount = ipTable.get( ip ); + if ( connCount == null ) { + ipTable.put( ip, new Integer( 1 ) ); + } else if ( connCount.intValue() < context.getConnLimitPerIp() ) { + int newCount = connCount.intValue() + 1; + ipTable.put( ip, new Integer( newCount )); + } else { + logger.error( CommonLib.getMessage("BECEAIMSA023", new String[]{ context.getAdapterName(), Integer.toString( context.getConnLimitPerIp() ),this.getSocketInfo( channel ) } ) ); + try { + channel.socket().close(); + channel.close(); + } catch(IOException ie) {} + continue; + } + } + + if ( getTraceLevel() >= DiagLogger.INFO ) { + logger.info( CommonLib.getMessage("BICEAIMSA033", new String[]{ context.getAdapterName(), this.getSocketInfo( channel ) } ) ); + } + + if ( this.context.isSocketReuse() ) { + channel.socket().setSoLinger(true, 100); + } + + // 신규 Connection Process 쓰레드를 생성 후 수행시킨다... + if ( isForInbound() && context.getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) { + InboundServer aProcess = new InboundServer(context, channel, this); + logger.debug("# INBOUND SOCKETSERVER CREATED.[" + this.getName() + "]"); + // + threadPool.addElement( aProcess ); + aProcess.start(); + logger.debug("# INBOUND SOCKETSERVER STARTED.[" + this.getName() + "]"); + synchronized ( threadPool ) { + if ( threadPool.size() == 1 ) { + SocketAdapterManager.getInstance().changeAdapterStatus( this, true ); + } + } + } else if ( isForOutbound() ) { +// OutboundServer aProcess = new OutboundServer(context, channel, this); +// logger.debug("# OUTBOUND SOCKETSERVER CREATED.[" + this.getName() + "]"); +// if ( !OutboundChannelManager.getInstance().hasChannel( context.getAdapterGroupName() )) { +// OutboundChannel connection = new OutboundChannel(context.getSessionTimeout()*1000); +// OutboundChannelManager.getInstance().addConnectionGroup( context.getAdapterGroupName(), connection ); +// } +// threadPool.addElement( aProcess ); +// aProcess.start(); +// logger.debug("# OUTBOUND SOCKETSERVER STARTED.[" + this.getName() + "]"); +// synchronized ( threadPool ) { +// if ( threadPool.size() == 1 ) { +// SocketAdapterManager.getInstance().changeAdapterStatus( this, true ); +// } +// } + } else if ( isForIobound() ) { + IOboundServer aProcess = new IOboundServer(context, channel, this); + logger.debug("# IOBOUND SOCKETSERVER CREATED.[" + this.getName() + "]"); + if ( !OutboundChannelManager.getInstance().hasChannel( context.getAdapterGroupName() )) { + OutboundChannel connection = new OutboundChannel(context.getSessionTimeout()*1000); + OutboundChannelManager.getInstance().addConnectionGroup( context.getAdapterGroupName(), connection ); + } + threadPool.addElement( aProcess ); + aProcess.start(); + logger.debug("# IOBOUND SOCKETSERVER STARTED.[" + this.getName() + "]"); + synchronized ( threadPool ) { + if ( threadPool.size() == 1 ) { + SocketAdapterManager.getInstance().changeAdapterStatus( this, true ); + } + } +// } else { +// AdminServer aProcess = new AdminServer(context, channel, this); +// logger.debug("# ADMIN SOCKETSERVER CREATED.[" + this.getName() + "]"); +// threadPool.addElement( aProcess ); +// aProcess.start(); +// logger.debug("# ADMIN SOCKETSERVER STARTED.[" + this.getName() + "]"); +// synchronized ( threadPool ) { +// if ( threadPool.size() == 1 ) { +// SocketAdapterManager.getInstance().changeAdapterStatus( this, true ); +// } +// } + } + // Process 쓰레드 Started + } catch(Exception e) { + logger.error(CommonLib.getMessage("BECEAIMSA030", new String[] { context.getAdapterName(), e.getMessage() } ), e); + logger.error( e.getMessage(), e); + } + } // End of While - it.hasNext + } // End of While - active + + try { + closeSelector(); + } catch( Throwable e ) {} + + interrupt(); + } // end of startup ... + + public String getRemoteIPAddress() { + return null; + } + + public Socket getCurrentSocket() { + return null; + } + + public boolean idle(long timeout) { + return false; + } + + public boolean connect() { + return true; + } + + public void disconnect() { + } + + + public int getCurrentState() { + return CommonLib.PROCESSING_PROTOCOL; + } + + public boolean isConnected() { + return true; + } + + public void checkActivity() { + } + + public synchronized void shutdown() { + + active = false; + if ( threadPool != null ) { + for ( int i=0; i < threadPool.size(); i++ ) { + try { + SocketService service = (SocketService)threadPool.get(i); + + if ( getTraceLevel() >= DiagLogger.INFO ) { + try { + logger.info( CommonLib.getMessage("BICEAIMSA031", new String[]{ context.getAdapterName(), this.getSocketInfo( service.getCurrentSocket() )} ) ); + } catch( Exception e ) {} + } + service.shutdown(); + } catch( Throwable e ) {logger.error( e.getMessage(), e);} + } + } + + threadPool = null; + try { + closeSelector(); + } catch (Throwable t) {logger.error( t.getMessage(), t);} + + try { + serverSocket.close(); + } catch (Throwable t) {logger.error( t.getMessage(), t);} + + SocketAdapterManager.getInstance().changeAdapterStatus( this, false ); + //*interrupt(); + } + /** + * @return Returns the context. + */ + public ConfigurationContext getContext() { + return context; + } + /** + * @return Returns the active. + */ + public boolean isActive() { + return active; + } + + public void notifyMessage() { + } + + public void setControl(Object control) { + } + + public void setLastActivity() { + } + + private String getSocketInfo(SocketChannel channel) { + StringBuffer connInfo = new StringBuffer(); + + connInfo.append("Local Address="); + connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", "); + connInfo.append("Remote Address="); + connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort()); + + return connInfo.toString(); + } + + private String getSocketInfo(Socket socket) { + StringBuffer connInfo = new StringBuffer(); + + if ( socket != null ) { + connInfo.append("Local Address="); + connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", "); + connInfo.append("Remote Address="); + connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort()); + }else { + connInfo.append("SOCKET IS NULL"); + } + + return connInfo.toString(); + } + + private boolean isForInbound() { + return ( this.context.getBoundUsage().equals( ConfigurationContext.INBOUND_SOCKET )); + } + + private boolean isForIobound() { + return ( this.context.getBoundUsage().equals( ConfigurationContext.IOBOUND_SOCKET )); + } + + private boolean isForOutbound() { + return ( this.context.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET )); + } + + public synchronized void quiesceShutdown(SocketService service) { + if ( threadPool == null ) return; + + for ( int i=0; i < threadPool.size(); i++) { + SocketService aService = (SocketService) threadPool.elementAt( i ); + if ( service != aService ) continue; + //service.shutdown(); + if ( context.getConnLimitPerIp() > 0 ) { + String ip = service.getRemoteIPAddress(); + if ( ip != null ) { + Integer connCount = (Integer)ipTable.get( ip ); + if ( connCount != null ) { + int newCount = connCount.intValue() - 1; + if ( newCount < 0 ) newCount = 0; + + ipTable.put( ip, new Integer( newCount ) ); + } + } + } + + threadPool.remove(i); + break; + } + // Adapter status 변경 + if ( threadPool == null || threadPool.size() == 0 ) { + SocketAdapterManager.getInstance().changeAdapterStatus( this, false ); + } + } + + private void openSelector() throws IOException { + + serverSocketChannel = ServerSocketChannel.open(); + serverSocket = serverSocketChannel.socket(); + selector = Selector.open(); + + if( context.getHostName() == null || context.getHostName().equals("*") || context.getHostName().equals("") || context.getHostName().equals("localhost") + || context.getHostName().equals("0.0.0.0") || context.getHostName().equals("127.0.0.1") ) { + serverSocket.bind(new InetSocketAddress(context.getPortNumber()), 1024); + if ( getTraceLevel() >= DiagLogger.INFO ) { + logger.info( CommonLib.getMessage("BICEAIMSA032", new String[]{ context.getAdapterName(), context.getHostName(), Integer.toString(context.getPortNumber()) }) ); + } + } else { + serverSocket.bind(new InetSocketAddress(context.getHostName(), context.getPortNumber()), 1024); + if ( getTraceLevel() >= DiagLogger.INFO ) { + logger.info( CommonLib.getMessage("BICEAIMSA032", new String[]{ context.getAdapterName(), context.getHostName(), Integer.toString(context.getPortNumber()) }) ); + } + } + + serverSocketChannel.configureBlocking(false); + serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); + + synchronized ( threadPool ) { + if ( threadPool.size() == 0 ) { + SocketAdapterManager.getInstance().changeAdapterStatus( this, false ); + } + } + } + + private void closeSelector() throws IOException { + + if(selector != null) { + for(Iterator iterator = selector.keys().iterator(); iterator.hasNext();) + try { + SelectionKey selectionkey = iterator.next(); + ServerSocketChannel serversocketchannel = (ServerSocketChannel)selectionkey.channel(); + selectionkey.cancel(); + serversocketchannel.socket().close(); + serversocketchannel.close(); + iterator.remove(); + }catch(UnsupportedOperationException e) { + // Do nothing!!! + }catch(IOException e) { + logger.error( e.getMessage(), e); + }catch(Exception e) { + logger.error( e.getMessage(), e); + } + selector.close(); + } + } // end of closeSelector... + + public void disconnect(String localHostname, int localPortNumber) + throws SocketAdapterException { + } + + public void setContext(ConfigurationContext context) { + this.context = context; + } + + public long getFirstActivity() { + return 0; + } + + public long getLastActivity() { + return 0; + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/SocketService.java b/src/com/eactive/eai/adapter/socket/service/SocketService.java new file mode 100644 index 0000000..562ab2d --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/SocketService.java @@ -0,0 +1,44 @@ +package com.eactive.eai.adapter.socket.service; + +import java.io.IOException; +import java.net.Socket; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; + +public interface SocketService { + + /** + * Stop the service + */ + public void shutdown(); + + public Socket getCurrentSocket(); + + public boolean connect(); + + public void disconnect(); + + public ConfigurationContext getContext(); + + public void setControl(Object control); + + public void notifyMessage(); + + public boolean idle(long timeout); + + public int getCurrentState(); + + public boolean isConnected() throws IOException; + + public boolean isActive(); + + public void checkActivity(); + + public String getRemoteIPAddress(); + + public void setLastActivity(); + + public long getFirstActivity(); + + public long getLastActivity(); +} \ No newline at end of file diff --git a/src/com/eactive/eai/adapter/socket/service/WriterClient.java b/src/com/eactive/eai/adapter/socket/service/WriterClient.java new file mode 100644 index 0000000..bcde4ff --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/WriterClient.java @@ -0,0 +1,325 @@ +//package com.eactive.eai.adapter.socket.service; +// +//import java.io.IOException; +//import java.net.Socket; +//import java.nio.ByteBuffer; +// +//import com.eactive.eai.adapter.socket.common.CommonLib; +//import com.eactive.eai.adapter.socket.common.DiagLogger; +//import com.eactive.eai.adapter.socket.common.SocketAdapterException; +//import com.eactive.eai.adapter.socket.config.ConfigurationContext; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public class WriterClient extends Thread implements SocketService { +// +// private ConfigurationContext context; +// private boolean active; +// private NBChannel channel; +// +// private Exception lastError; +// +// private ByteBuffer outgoingMessage; +// private ByteBuffer lenBuffer; +// +// private Logger logger; +// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); +// +// private OutboundControl control; +// private ReaderClient proxy; +// private boolean shutdownFlag; +// +// public WriterClient(ConfigurationContext context, NBChannel channel, ReaderClient proxy ) { +// String name = this.getName(); +// this.setName( context.getAdapterName() + "-CONNECTION-WRITER" + name.substring( name.lastIndexOf("-")) ); +// +// this.context = context; +// active = true; +// +// outgoingMessage = null; +// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() ); +// lenBuffer.clear(); +// +// this.control = null; +// this.proxy = proxy; +// this.channel = channel; +// this.shutdownFlag = false; +// +// logger = SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName()); +// } +// +// public boolean isActive() { +// return active; +// } +// +// private int getTraceLevel() { +// return context.getTraceLevel(); +// } +// /** +// * @return Returns the context. +// */ +// public ConfigurationContext getContext() { +// return context; +// } +// +//// private boolean isSyncMode() { +//// return context.isSyncMode(); +//// } +// +// private long getTimeout() { +// return ( this.context.getTimeout() * 1000L ); +// } +// +// private boolean isSocketReuse() { +// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); +// } +// +// public void run() { +// +// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this); +// String socketInfo = ""; +// +// while ( active ) { +// try { +// openChannel(); +// if ( !socketInfo.equals( getSocketInfo(this.getCurrentSocket()) ) ) { +// socketInfo = getSocketInfo( this.getCurrentSocket() ); +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO001", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); +// } +// } +// +// onMessage(); +// +// if ( control == null ) continue; +// +// doRequest(); +// if ( !isSocketReuse() ) { +// active = false; +// } +// } catch (Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// active = false; +// } +// } +// +// OutboundChannelManager.getInstance().removeConnection(context.getAdapterGroupName(), this); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO002", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); +// } +// +// if ( !shutdownFlag ) { +// proxy.shutdownWriter(); +// } +// +// interrupt(); +// } +// +//// private String getWritingMessage() { +//// String rMsg = ""; +//// if ( outgoingMessage != null ) { +//// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ]; +//// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length ); +//// rMsg = CommonLib.getDumpMessage( debugMsg ); +//// } +//// return rMsg; +//// } +// +// private String getSocketInfo(Socket socket) { +// StringBuffer connInfo = new StringBuffer(); +// +// connInfo.append("Local Address="); +// connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", "); +// connInfo.append("Remote Address="); +// connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort()); +// +// return connInfo.toString(); +// } +// +// private synchronized void onMessage() { +// try { +// this.wait( ); +// this.lastError = null; +// } catch ( InterruptedException ie ) {} +// } +// +// public void wakeup() { +// this.control.setLastError( this.lastError ); +// this.control.wakeup(); +// this.control = null; +// // 사용한 Connection 반납한다. +// if ( active ) { +// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this ); +// } +// } +// +// public synchronized void notifyMessage() { +// this.notify(); +// } +// +// public synchronized void setControl(Object control) { +// this.control = (OutboundControl) control; +// } +// +// // RESPONSE MODE의 경우 +// private void doRequest() { +// +// this.checkActivity(); +// proxy.setLastActivity( System.currentTimeMillis() ); +// +// try { +// +// processWriteMessage( this.control.getRequest() ); +// +// proxy.addSendCount(); +// +// if ( getTraceLevel() >= DiagLogger.DEBUG) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo( getCurrentSocket() ), CommonLib.getDumpMessage(this.control.getRequest())})); +// } +// +// wakeup(); +// +// } catch( Exception e) { +// String errMsg = ""; +// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteMessage", e.getMessage(), "송신메시지", CommonLib.getDumpMessage( this.control.getRequest() ) } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// +// lastError = new SocketAdapterException( errMsg ); +// active = false; +// wakeup(); +// } +// } // end of doRequest() +// +// /** +// * Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다. +// */ +// public boolean idle(long timeout) { +// return false; +// } +// +// public int getCurrentState() { +// return proxy.getCurrentState(); +// } +// +//// private void resetCount() { +//// } +// +// public boolean isConnected() { +// return proxy.isConnected(); +// } +// +// public void checkActivity() { +// proxy.checkActivity(); +// } +// +// private void processWriteMessage( byte[] data ) throws IOException { +// +// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() ); +// outgoingMessage.clear(); +// outgoingMessage.put( makeLengthField( data.length ) ); +// outgoingMessage.put( data ); +// outgoingMessage.flip(); +// +// long writeStart = System.currentTimeMillis(); +// +// int expectedWrite = outgoingMessage.capacity(); +// int writtenByte = channel.write( outgoingMessage ); +// +// if ( expectedWrite != writtenByte ) { +// ByteBuffer buf = null; +// while ( writtenByte < expectedWrite ) { +// buf = ByteBuffer.allocate( expectedWrite - writtenByte ); +// buf.clear(); +// buf.put( outgoingMessage.array(), writtenByte, buf.capacity() ); +// writtenByte += channel.write( buf ); +// if ( expectedWrite == writtenByte ) return; +// long waitTime = System.currentTimeMillis() - writeStart; +// if ( waitTime >= getTimeout() ) { +// throw new IOException("메시지 송신 타임아웃"); +// } +// } +// } +// +// } +// +// private byte[] makeLengthField(int length) { +// byte[] lenField = new byte[ lenBuffer.capacity() ]; +// +// if ( lenField.length == 2 ) { +// lenBuffer.clear(); +// lenBuffer.putShort( (short) (length & 0xFFFF) ); +// lenField = lenBuffer.array(); +// } else if ( lenField.length == 4 ) { +// lenBuffer.clear(); +// lenBuffer.putInt( length ); +// lenField = lenBuffer.array(); +// } else { +// String lenStr = CommonLib.getFormatString( length, lenField.length ); +// lenField = lenStr.getBytes(); +// } +// +// return lenField; +// } +// +// public synchronized void shutdown() { +// +// active = false; +// // 2005.10.17 +// shutdownFlag = true; +// +// try { +// notify(); +// } catch( Exception e ) {} +// +// //* 2005.10.17 +// try { +// this.channel.wakeup(); +// } catch( Throwable e ) {} +// // interrupt(); +// } +// +// public Socket getCurrentSocket() { +// return channel.getSocket(); +// } +// +// public boolean connect() { +// return false; +// } +// +// public void disconnect() { +// } +// +// private synchronized void openChannel() throws IOException { +// +// try { +// if ( channel !=null && !channel.isConnected() ) { +// throw new Exception(""); +// } +// } catch(Exception e) { +// throw new IOException("Connection Closed in openChannel"); +// } +// } +// +// public String getRemoteIPAddress() { +// return null; +// } +// +//// private synchronized void closeChannel() throws IOException { +//// } // end of closeChannel... +// +// public void setLastActivity() { +// } +// +// public long getFirstActivity() { +// return 0; +// } +// +// public long getLastActivity() { +// return 0; +// } +//} diff --git a/src/com/eactive/eai/adapter/socket/service/WriterServer.java b/src/com/eactive/eai/adapter/socket/service/WriterServer.java new file mode 100644 index 0000000..f2e5c2a --- /dev/null +++ b/src/com/eactive/eai/adapter/socket/service/WriterServer.java @@ -0,0 +1,403 @@ +//package com.eactive.eai.adapter.socket.service; +// +//import java.io.IOException; +//import java.net.Socket; +//import java.nio.ByteBuffer; +//import java.nio.channels.SelectionKey; +//import java.nio.channels.Selector; +//import java.nio.channels.SocketChannel; +//import java.util.Iterator; +// +//import com.eactive.eai.adapter.socket.common.CommonLib; +//import com.eactive.eai.adapter.socket.common.DiagLogger; +//import com.eactive.eai.adapter.socket.common.SocketAdapterException; +//import com.eactive.eai.adapter.socket.config.ConfigurationContext; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public class WriterServer extends Thread implements SocketService { +// +// private ConfigurationContext context; +// private SocketChannel socketChannel; +// private ReaderServer proxy; +// +// private boolean active; +// +// private ByteBuffer outgoingMessage; +// +// private ByteBuffer lenBuffer; +// +// private Exception lastError; +// private Logger logger; +// private Selector selector; +// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger(); +// +// private OutboundControl control; +// private boolean shutdownFlag; +// +// public WriterServer(ConfigurationContext context, SocketChannel socketChannel, ReaderServer proxy, Selector selector ) throws IOException { +// String name = this.getName(); +// this.setName( context.getAdapterName() + "-CONNECTION-WRITER" + name.substring( name.lastIndexOf("-")) ); +// +// this.context = context; +// this.socketChannel = socketChannel; +// this.proxy = proxy; +// +// this.selector = selector; +// socketChannel.register( this.selector, SelectionKey.OP_WRITE | SelectionKey.OP_WRITE ); +// +// outgoingMessage = null; +// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() ); +// lenBuffer.clear(); +// +// this.control = null; +// +// active = true; +// shutdownFlag = false; +// logger = SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName()); +// } +// +//// private boolean isSyncMode() { +//// return this.context.isSyncMode(); +//// } +// +// private int getTraceLevel() { +// return context.getTraceLevel(); +// } +// +// private long getTimeout() { +// return ( this.context.getTimeout() * 1000L ); +// } +// +// private boolean isSocketReuse() { +// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG ); +// } +// +// /** +// * @return Returns the context. +// */ +// public ConfigurationContext getContext() { +// return context; +// } +// +// public void run() { +// +// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this); +// String socketInfo = this.getSocketInfo(this.socketChannel); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO001", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) ); +// } +// +// while ( active ) { +// try { +// +// openSelector(); +// +// onMessage(); +// +// if ( control == null ) continue; +// +// doRequest(); +// +// if ( shutdownFlag ) active = false; +// +// if ( !isSocketReuse() ) { +// active = false; +// } +// } catch (Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "openSelector", e.getMessage(), "", "" } ); +// logger.error( errMsg, e ); +// active = false; +// continue; +// } +// } +// +// try { +// closeSelector(); +// } catch(IOException e) { } +// +// OutboundChannelManager.getInstance().removeConnection( context.getAdapterGroupName(), this); +// +// if ( getTraceLevel() >= DiagLogger.INFO ) { +// logger.info( CommonLib.getMessage("BICEAIASO002", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) ); +// } +// +// if ( !shutdownFlag ) { +// proxy.shutdownWriter(); +// } +// interrupt(); +// } +// +// private String getWritingMessage() { +// String rMsg = ""; +// if ( outgoingMessage != null ) { +// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ]; +// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length ); +// rMsg = CommonLib.getDumpMessage( debugMsg ); +// } +// return rMsg; +// } +// +// private String getSocketInfo(SocketChannel channel) { +// StringBuffer connInfo = new StringBuffer(); +// +// connInfo.append("Local Address="); +// connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", "); +// connInfo.append("Remote Address="); +// connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort()); +// +// return connInfo.toString(); +// } +// +// +// private synchronized void onMessage() { +// try { +// this.wait( ); +// this.lastError = null; +// } catch ( InterruptedException ie ) { +// } +// } +// +// public void wakeup() { +// this.control.setLastError( this.lastError ); +// this.control.wakeup(); +// this.control = null; +// if ( active ) { +// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this ); +// } +// } +// +// public synchronized void notifyMessage() { +// this.notify(); +// } +// +// public synchronized void setControl(Object control) { +// this.control = (OutboundControl) control; +// } +// +// public void doRequest() { +// +//// Iterator iterator; +// +// makeFormat( this.control.getRequest() ); +// +// boolean isDone = false; +// +// this.checkActivity(); +// proxy.setLastActivity( System.currentTimeMillis() ); +//// long start = System.currentTimeMillis(); +// +// while( !isDone ) { +// /** +// * Write the message to the target +// */ +// try { +// if( processWriteMessage() ) { +// +// proxy.addSendCount(); +// +// if ( getTraceLevel() >= DiagLogger.DEBUG) { +// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), getSocketInfo(this.socketChannel), getWritingMessage()})); +// } +// wakeup(); +// return; +// } +// } catch(Exception e) { +// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteMessage", e.getMessage(), "송신메시지", getWritingMessage() } ); +// logger.error( errMsg , e); +// if ( logger != errLogger ) { +// errLogger.error( errMsg, e ); +// } +// lastError = new SocketAdapterException( errMsg ); +// +// active = false; +// wakeup(); +// return; +// } +// } // enf of while - isDone +// } +// +// public int getCurrentState() { +// return proxy.getCurrentState(); +// } +// +//// private void resetCount() { +//// } +// +// public boolean isConnected() throws IOException { +// return proxy.isConnected(); +// } +// +// public void checkActivity() { +// proxy.checkActivity(); +// } +// +// public boolean isActive() { +// return active; +// } +// +// public String getRemoteIPAddress() { +// return null; +// } +// +// public synchronized void shutdown() { +// // 2005.10.17 +// active = false; +// shutdownFlag = true; +// +// try { +// notify(); +// } catch( Exception e ) {} +// +// try { +// if ( selector != null && selector.isOpen() ) { +// selector.wakeup(); +// } +// } catch( Throwable e ) {} +// +// } +// +// public Socket getCurrentSocket() { +// return socketChannel.socket(); +// } +// +// public boolean connect() { +// return true; +// } +// +// public void disconnect() { +// shutdown(); +// } +// +// public boolean idle(long timeout) { +// return false; +// } +// +// private void openSelector() throws IOException { +// if ( socketChannel.socket().isConnected() && socketChannel.socket().isBound() ) { +// return; +// } else { +// throw new IOException("Connection Closed in openSelector"); +// } +// } +// +// private void closeSelector() throws IOException { +// // nothing... +// } +// +// +// private boolean processWriteMessage() throws IOException { +// +// outgoingMessage.flip(); +// long writeStart = System.currentTimeMillis(); +// int expectedWrite = outgoingMessage.capacity(); +// int writtenByte = socketChannel.write( outgoingMessage ); +// +// if ( expectedWrite != writtenByte ) { +// ByteBuffer buf = null; +// while ( writtenByte < expectedWrite ) { +// +// buf = ByteBuffer.allocate( expectedWrite - writtenByte ); +// buf.clear(); +// buf.put( outgoingMessage.array(), writtenByte, buf.capacity() ); +// writtenByte += write( buf ); +// +// if ( expectedWrite == writtenByte ) return true; +// long waitTime = System.currentTimeMillis() - writeStart; +// +// if ( waitTime >= getTimeout() ) { +// throw new IOException("메시지 송신 타임아웃"); +// } +// } +// } +// this.socketChannel.register( this.selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ ); +// return true; +// } +// +// public int write(ByteBuffer src) throws IOException { +// +// this.socketChannel.register( this.selector, SelectionKey.OP_WRITE ); +//// int selected = 0; +// +// try { +// //selected = +// selector.select( getTimeout() ); +// } catch(Exception e) { +// throw new IOException("Write Select Error"); +// } +// +// Iterator it = selector.selectedKeys().iterator(); +// int writtenBytes = 0; +// SelectionKey key = null; +// +// while ( it.hasNext() ) { +// key = (SelectionKey)it.next(); +// it.remove(); +// if ( key.isWritable() ) { +// writtenBytes = this.socketChannel.write( src ); +// } +// } +// return writtenBytes; +// } +// +// private byte[] makeLengthField(int length) { +// byte[] lenField = new byte[ lenBuffer.capacity() ]; +// +// if ( lenBuffer.capacity() == 2 ) { +// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() ); +// tmpBuffer.clear(); +// tmpBuffer.putShort( (short) (length & 0xFFFF) ); +// lenField = tmpBuffer.array(); +// } else if ( lenBuffer.capacity() == 4 ) { +// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() ); +// tmpBuffer.clear(); +// tmpBuffer.putInt( length ); +// lenField = tmpBuffer.array(); +// } else { +// String lenStr = CommonLib.getFormatString( length, lenBuffer.capacity() ); +// lenField = lenStr.getBytes(); +// } +// +// return lenField; +// } +// +// private void makeFormat( byte[] data ) { +// +// int i = data.length + lenBuffer.capacity(); +// +// if(outgoingMessage == null) { +// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() ); +// } else { +// if( i != outgoingMessage.capacity() ) +// outgoingMessage = ByteBuffer.allocate( i ); +// } +// outgoingMessage.clear(); +// outgoingMessage.put( makeLengthField( data.length ) ); +// outgoingMessage.put( data ); +// } +// +// /** +// * @return Returns the socketchannel. +// */ +// public SocketChannel getSocketchannel() { +// return socketChannel; +// } +// /** +// * @param socketchannel The socketchannel to set. +// */ +// public void setSocketchannel(SocketChannel socketchannel) { +// this.socketChannel = socketchannel; +// } +// +// public void setLastActivity() { +// } +// +// public long getFirstActivity() { +// return 0; +// } +// +// public long getLastActivity() { +// return 0; +// } +//} diff --git a/src/com/eactive/eai/agent/AgentUtil.java b/src/com/eactive/eai/agent/AgentUtil.java new file mode 100644 index 0000000..ca52986 --- /dev/null +++ b/src/com/eactive/eai/agent/AgentUtil.java @@ -0,0 +1,216 @@ +package com.eactive.eai.agent; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.server.EAIServerDAO; +import com.eactive.eai.common.server.EAIServerVO; +import com.eactive.eai.common.util.Logger; + + +/** +* 1. 기능 : 등록된 EAI Server 에 Command를 broadcast +* 2. 처리 개요 : 등록된 EAI Server 에 Command를 broadcast +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class AgentUtil +{ + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + private static final String WEB_AGENT_SERVLET_URL = "/BAPAppWeb/WebAgent"; + + + //생성자 (private : 객체 생성 불가) + private AgentUtil() {} + + + private static HashMap getAllSvrUrl() throws Exception { + + EAIServerDAO dao = (EAIServerDAO) DAOFactory.newInstance().create(EAIServerDAO.class); + ArrayList serverList = dao.getAllServerList(); + if (serverList == null || serverList.size() == 0) return null; + + HashMap urlLists = new HashMap(); + + for (int i = 0; i getSvrUrl(EAIServerVO vo) throws Exception { + + if (vo == null) return null; + + HashMap urlLists = new HashMap(); + urlLists.put(vo.getName(), vo.toURL(EAIServerVO.HTTP_PROTOCOL) + WEB_AGENT_SERVLET_URL); + logger.debug("[ AgentUtil ] getAllSvrUrl - URL : " + urlLists.get(vo.getName())); + return urlLists; + } + + public static HashMap broadcast(EAIServerVO serverVO, Command command) throws Exception { + return broadcast(getSvrUrl(serverVO), command); + } + + public static HashMap broadcast(Command command) throws Exception { + return broadcast(getAllSvrUrl(), command); + } + + public static HashMap callMainServer(Command command) throws Exception { + return broadcast(getSvrUrl(getMainServerVO()), command); + } + + public static EAIServerVO getServerVO(String serverName) throws Exception { + if (serverName == null || serverName.equals("")) throw new Exception("서버명 파라미터가 null 또는 공백입니다."); + + EAIServerDAO dao = (EAIServerDAO) DAOFactory.newInstance().create(EAIServerDAO.class); + ArrayList serverList = dao.getAllServerList(); + if (serverList == null || serverList.size() == 0) return null; + + for (int i = 0; i < serverList.size(); i++) { + EAIServerVO vo = (EAIServerVO) serverList.get(i); + if (vo.getName().equals(serverName)) return vo; + } + + return null; + } + + public static EAIServerVO getMainServerVO() throws Exception { + + EAIServerDAO dao = (EAIServerDAO) DAOFactory.newInstance().create(EAIServerDAO.class); + ArrayList serverList = dao.getAllServerList(); + + if ( serverList.size() > 0 ) + return serverList.get(0); +// //서버명 중에 xxxxxi11 로 끝나는 서버를 메인서버로 본다. +// for (int i = 0; serverList != null && i < serverList.size(); i++) { +// EAIServerVO vo = serverList.get(i); +//// if (vo.getName().endsWith("i11")) return vo; +// return vo; +// } + throw new Exception("서버정보 테이블(TSEAIBP03) 에 메인서버를 설정하세요."); + } + + /** + * 1. 기능 : 등록된 EAI Server에 Command를 broadcast + * 2. 처리 개요 : 등록된 EAI Server의 URLConnection을 생성하여 Command broadcast하고 + * 전송된 결과값의 HashMap을 생성하여 반환 + * 3. 주의사항 + * + * @param command broadcast할 Command + * @return HashMap broadcast후 전송된 결과값. + * 전송된 데이터가 sucess가 아니면 Exception이 전송된 것임. + * @exception Exception + **/ + public static HashMap broadcast(HashMap servers, Command command) throws Exception { + + HashMap returnValue = new HashMap(); + + logger.debug("[ AgentUtil ] broadcast 시작..."); + if (servers != null) { + + logger.debug("[ AgentUtil ] 대상 서버수 =" + servers.size()); + Iterator it = servers.keySet().iterator(); + while (it.hasNext()) { + String svrName = (String) it.next(); + String url = (String) servers.get(svrName); + URLConnection urlCon = getURLConnection(url); + try { + logger.debug("[ AgentUtil ] COMMAND = " + command); + Object response = sendCommand(urlCon, command); + returnValue.put(svrName, response); + + } catch (Exception e) { + logger.error("[ AgentUtil ] ★★★★★ broadcast 예외 발생 !! ★★★★★", e); + returnValue.put(svrName, e.getMessage()); + } + logger.debug("[ AgentUtil ] 대상 서버 ["+svrName+"] 결과 = ["+ returnValue.get(svrName) +"]"); + } + + } else { + logger.error("[ AgentUtil ] 대상 서버 없음."); + } + logger.debug("[ AgentUtil ] broadcast 완료."); + + return returnValue; + } + + /** + * 1. 기능 : 해당 URLConnection으로 command 전송 처리 결과를 반환 + * 2. 처리 개요 : 해당 URLConnection으로 command 전송하고 처리 결과를 반환 + * 3. 주의사항 + * + * @param urlCon 연결할 URLConnection + * @param command 전송할 Command + * @return String 처리된 결과 + * @exception Exception + **/ + private static Object sendCommand(URLConnection urlCon, Command command) throws Exception { + + ObjectOutputStream oos = null; + ObjectInputStream ois = null; + Object response = ""; + + try { + HashMap hm = new HashMap(); + hm.put("command", command); + + oos = new ObjectOutputStream(urlCon.getOutputStream()); + oos.writeObject((Serializable) hm); + oos.flush(); + logger.debug("[ AgentUtil ] SendCommand - " + urlCon.getURL().toString() +" ["+ command.getClass().getName() + "]"); + + ois = new ObjectInputStream(urlCon.getInputStream()); + response = ois.readObject(); + + } finally { + try { if (oos != null) oos.close(); } catch (Exception ex) {} + try { if (ois != null) ois.close(); } catch (Exception ex) {} + } + + return response; + } + + /** + * 1. 기능 : 지정된 url의 URLConnection 생성 + * 2. 처리 개요 : 지정된 url의 URLConnection 생성 + * 3. 주의사항 + * + * @param url URLConnection을 생성을 위한 url + * @return URLConnection 생성된 URLConnection + * @exception + **/ + private static URLConnection getURLConnection(String url) throws Exception { + + URL u = new URL(url); + HttpURLConnection conn = (HttpURLConnection) u.openConnection(); + + if (conn == null) throw new Exception("HttpURLConnection 을 생성할 수 없습니다. (URL : "+ url +")"); + + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setUseCaches(false); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-type", "application/octet-stream"); + + return conn; + } + +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/adapter/RemoveAdapterGroupCommand.java b/src/com/eactive/eai/agent/adapter/RemoveAdapterGroupCommand.java new file mode 100644 index 0000000..7c32ba8 --- /dev/null +++ b/src/com/eactive/eai/agent/adapter/RemoveAdapterGroupCommand.java @@ -0,0 +1,76 @@ +package com.eactive.eai.agent.adapter; + +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.common.util.Logger; +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 AdapterManager의 정보 변경 +* 2. 처리 개요 : AdapterGroupVO를 manager에서 remove +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemoveAdapterGroupCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : RemoveAdapterGroupCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + **/ + public RemoveAdapterGroupCommand(String name) { + super(name); + } + + /** + * 1. 기능 : AdapterManager에 AdapterGroupVO를 제거 + * 2. 처리 개요 : AdapterGroupVO의 EAISvrInstNm이 DEFAULT_SERVER(ALL) 이거나 LocalServer인 경우 + * AdapterManager에 등록된 해당 AdapterGroupVO를 제거 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + + try { + String adapterGroupName = (String)args; + logger.debug("adapterGroupName : "+adapterGroupName ); + AdapterGroupVO gvo = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName); + + if (gvo != null) { + gvo.stop(); + AdapterManager.getInstance().removeAdapterGroupVO(adapterGroupName); + } + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + + } + +} diff --git a/src/com/eactive/eai/agent/adapter/UpdateAdapterGroupCommand.java b/src/com/eactive/eai/agent/adapter/UpdateAdapterGroupCommand.java new file mode 100644 index 0000000..3c9651f --- /dev/null +++ b/src/com/eactive/eai/agent/adapter/UpdateAdapterGroupCommand.java @@ -0,0 +1,81 @@ +package com.eactive.eai.agent.adapter; + +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.common.util.Logger; +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 AdapterManager의 정보 변경 +* 2. 처리 개요 : AdapterGroupVO의 member variable 값 변경 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see +* @since +*/ +public class UpdateAdapterGroupCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : UpdateAdapterGroupCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + **/ + public UpdateAdapterGroupCommand(String name) { + super(name); + } + + /** + * 1. 기능 : AdapterManager의 AdapterGroupVO를 수정 + * 2. 처리 개요 : AdapterGroupVO의 EAISvrInstNm이 DEFAULT_SERVER(ALL) 이거나 LocalServer인 경우 + * AdapterManager에 등록된 해당 AdapterGroupVO의 데이터 수정 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + + try { + + String adapterGroupName = (String)args; + AdapterGroupVO current = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName); + + if (current != null) { + current.stop(); + AdapterManager.getInstance().removeAdapterGroupVO(adapterGroupName); +// } else { +// logger.info("Manager's AdapterGroupVO is null. -- "+vo.getName()); + } + AdapterGroupVO vo = AdapterManager.getInstance().getAdapterGroupInDB(adapterGroupName); + + if (vo.isUsedFlag()) { + vo.start(); + AdapterManager.getInstance().addAdapterGroupVO(vo); + } + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/adapter/socket/SocketServerCommand.java b/src/com/eactive/eai/agent/adapter/socket/SocketServerCommand.java new file mode 100644 index 0000000..9180bbf --- /dev/null +++ b/src/com/eactive/eai/agent/adapter/socket/SocketServerCommand.java @@ -0,0 +1,158 @@ +package com.eactive.eai.agent.adapter.socket; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 CodeMessageManager의 정보 변경 +* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO추가 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class SocketServerCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + /** + * 1. 기능 : SelectSocketServerCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + **/ + public SocketServerCommand(String name) { + super(name); + } + + /** + * 1. 기능 : ServerSocket 정보를 가지고옮 + * 2. 처리 개요 : ServerSocket 정보를 가지고옮 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + logger.info(this.name + " Agent 가 호출되었습니다."); + + try { + + List> ls = getSocketServerAdapterInfo(); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return ls; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } + + + private List> getSocketServerAdapterInfo() throws Exception { + + try { + //리턴 ArrayList 생성 + List> retList = new ArrayList>(); + + //메모리의 전체 AdapterGroup 객체 조회 + HashMap allAdapterGroupMap = AdapterManager.getInstance().getAllAdapterGroupVO(); + + //AdapterGroup 이 없으면 + if (allAdapterGroupMap == null || allAdapterGroupMap.size() == 0) { + return retList; + } + + //AdapterGroup 명으로 정렬 + Object[] adapterGroupNames = allAdapterGroupMap.keySet().toArray(); + Arrays.sort(adapterGroupNames); + + //=================================================================================== + //AdapterGroup 별 LOOP + for (int i=0; i allAdapterMap = gvo.getAllAdapters(); + + //Adapter 가 없으면 디폴트 값 설정 + if (allAdapterMap == null || allAdapterMap.size() == 0) { + Map map = new HashMap(); + map.put("adptrBzwkGroupName", adapterGroupName); + map.put("bjobBzwkDstcd" , processCode ); + map.put("processName" , processName ); + map.put("organName" , organName ); + map.put("osidInstiDstCd" , organCode ); + map.put("adptrBzwkName" , "No Adapters" ); + map.put("ip" , "" ); + map.put("port" , "" ); + map.put("maxConnectioncount", 0 ); + map.put("curConnectioncount", 0 ); + map.put("status" , "N/A" ); + retList.add(map); + continue; + } + + //Adapter 명으로 정렬 + Object[] adapterNames = allAdapterMap.keySet().toArray(); + Arrays.sort(adapterNames); + + //------------------------------------------------------------------- + //Adapter 별 LOOP + for (int k=0; k map = new HashMap(); + map.put("adptrBzwkGroupName", adapterGroupName ); + map.put("bjobBzwkDstcd" , processCode ); + map.put("processName" , processName ); + map.put("organName" , organName ); + map.put("osidInstiDstCd" , organCode ); + map.put("adptrBzwkName" , adapterName ); + map.put("ip" , avo.getBatchServerIP() ); + map.put("port" , avo.getBatchServerPortNo()); + map.put("maxConnectioncount", maxConnCnt ); + map.put("curConnectioncount", curConnCnt ); + map.put("status" , isActive? "기동중" : "중지" ); + retList.add(map); + } + } + return retList; + + }catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/adapter/socket/SocketServerVO.java b/src/com/eactive/eai/agent/adapter/socket/SocketServerVO.java new file mode 100644 index 0000000..113304e --- /dev/null +++ b/src/com/eactive/eai/agent/adapter/socket/SocketServerVO.java @@ -0,0 +1,99 @@ +package com.eactive.eai.agent.adapter.socket; + +import java.io.Serializable; + +public class SocketServerVO implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + + private String serverName; //서버명 + private String bjobBzwkDstcd; //작업업무구분코드 + private String osidInstiDstCd; //대외기관구분코드 + private String osidInstiName; //대외기관명 + private String adptrBzwkGroupName; //어댑터업무그룹명 + private String adptrBzwkName; //어댑터업무명 + private String ip; //아이피 + private String port; //포트 + private String status; //상태 + private int maxConnectionCount; + private int curConnectionCount; + public String getServerName() { + return serverName; + } + public void setServerName(String serverName) { + this.serverName = serverName; + } + public String getBjobBzwkDstcd() { + return bjobBzwkDstcd; + } + public void setBjobBzwkDstcd(String bjobBzwkDstcd) { + this.bjobBzwkDstcd = bjobBzwkDstcd; + } + public String getOsidInstiDstCd() { + return osidInstiDstCd; + } + public void setOsidInstiDstCd(String osidInstiDstCd) { + this.osidInstiDstCd = osidInstiDstCd; + } + public String getOsidInstiName() { + return osidInstiName; + } + public void setOsidInstiName(String osidInstiName) { + this.osidInstiName = osidInstiName; + } + public String getAdptrBzwkGroupName() { + return adptrBzwkGroupName; + } + public void setAdptrBzwkGroupName(String adptrBzwkGroupName) { + this.adptrBzwkGroupName = adptrBzwkGroupName; + } + public String getAdptrBzwkName() { + return adptrBzwkName; + } + public void setAdptrBzwkName(String adptrBzwkName) { + this.adptrBzwkName = adptrBzwkName; + } + public String getIp() { + return ip; + } + public void setIp(String ip) { + this.ip = ip; + } + public String getPort() { + return port; + } + public void setPort(String port) { + this.port = port; + } + public String getStatus() { + return status; + } + public void setStatus(String status) { + this.status = status; + } + public int getMaxConnectionCount() { + return maxConnectionCount; + } + public void setMaxConnectionCount(int maxConnectionCount) { + this.maxConnectionCount = maxConnectionCount; + } + public int getCurConnectionCount() { + return curConnectionCount; + } + public void setCurConnectionCount(int curConnectionCount) { + this.curConnectionCount = curConnectionCount; + } + @Override + public String toString() { + return "SocketServerVO [serverName=" + serverName + ", bjobBzwkDstcd=" + + bjobBzwkDstcd + ", osidInstiDstCd=" + osidInstiDstCd + + ", osidInstiName=" + osidInstiName + ", adptrBzwkGroupName=" + + adptrBzwkGroupName + ", adptrBzwkName=" + adptrBzwkName + + ", ip=" + ip + ", port=" + port + ", status=" + status + + ", maxConnectionCount=" + maxConnectionCount + + ", curConnectionCount=" + curConnectionCount + "]"; + } + +} diff --git a/src/com/eactive/eai/agent/adapter/socket/SocketSessionCommand.java b/src/com/eactive/eai/agent/adapter/socket/SocketSessionCommand.java new file mode 100644 index 0000000..5ad634d --- /dev/null +++ b/src/com/eactive/eai/agent/adapter/socket/SocketSessionCommand.java @@ -0,0 +1,87 @@ +package com.eactive.eai.agent.adapter.socket; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.util.Logger; + +public class SocketSessionCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public SocketSessionCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + logger.info(this.name + " Agent 가 호출되었습니다."); + + try { + List> alist = getAllRunningSessionVO(); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return alist; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } + + + + private List> getAllRunningSessionVO() throws Exception { + List> retList = new ArrayList>(); + + HashMap allDocs = BatchRunningJobManager.getInstance().getAllRunningDocuments(); + Object[] uuids = allDocs.keySet().toArray(); + + for (int i=0; i map = new HashMap(); + map.put( "serverName" , batchDoc.getBatchMsg().getBody().getWLIServerName()); + map.put( "processName" , batchDoc.getBatchMsg().getHeader().getProcessName()); + map.put( "organName" , batchDoc.getBatchMsg().getHeader().getInstitutionName()); + map.put( "processType" , batchDoc.getBatchMsg().getHeader().getProcessType()); + map.put( "uuid" , batchDoc.getBatchMsg().getHeader().getUUID()); + map.put( "adapterGroupName", service.getContext()==null? "" : service.getContext().getAdapterGroupName()); + map.put( "adapterName" , service.getContext()==null? "" : service.getContext().getAdapterName()); + map.put( "localIpPort" , service.getCurrentSocket() == null || service.getCurrentSocket().getLocalAddress() == null? + "" : + service.getCurrentSocket().getLocalAddress().getHostAddress() + ":" + service.getCurrentSocket().getLocalPort()); + map.put( "remoteIpPort" , service.getCurrentSocket() == null || service.getCurrentSocket().getInetAddress() == null ? + "" : + service.getCurrentSocket().getInetAddress().getHostAddress() + ":" + service.getCurrentSocket().getPort()); + map.put( "startTimeStamp" , timestamp); + map.put( "status" , "연결됨"); + retList.add(map); + } + return retList; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/adapter/socket/SocketSessionVO.java b/src/com/eactive/eai/agent/adapter/socket/SocketSessionVO.java new file mode 100644 index 0000000..740b036 --- /dev/null +++ b/src/com/eactive/eai/agent/adapter/socket/SocketSessionVO.java @@ -0,0 +1,94 @@ +package com.eactive.eai.agent.adapter.socket; + +import java.io.Serializable; + +public class SocketSessionVO implements Serializable//, Comparable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String serverName = ""; //서버인스턴스명 + private String uuid = ""; //UUID + private String processType = ""; //업무유형 + private String processCode = ""; //업무코드 + private String processName = ""; //업무명 + private String organCode = ""; //대외기관코드 + private String organName = ""; //대외기관명 + private String adapterGroupName = ""; //어댑터그룹명 + private String adapterName = ""; //어댑터명 + private String localIp = ""; //로컬IP + private String localPort = ""; //로컬Port + private String remoteIp = ""; //리모트IP + private String remotePort = ""; //리모트Port + private long startTimeStamp = 0; //연결시작시간 + private long endTimeStamp = 0; //연결종료시간 (배치에서는 무의미함) + private String status = ""; //Session Service 상태 + + public void setServerName (String arg) { this.serverName = arg; } + public void setUuid (String arg) { this.uuid = arg; } + public void setProcessType (String arg) { this.processType = arg; } + public void setProcessCode (String arg) { this.processCode = arg; } + public void setProcessName (String arg) { this.processName = arg; } + public void setOrganCode (String arg) { this.organCode = arg; } + public void setOrganName (String arg) { this.organName = arg; } + public void setAdapterGroupName(String arg) { this.adapterGroupName = arg; } + public void setAdapterName (String arg) { this.adapterName = arg; } + public void setLocalIp (String arg) { this.localIp = arg; } + public void setLocalPort (String arg) { this.localPort = arg; } + public void setRemoteIp (String arg) { this.remoteIp = arg; } + public void setRemotePort (String arg) { this.remotePort = arg; } + public void setStartTimeStamp (long arg) { this.startTimeStamp = arg; } + public void setEndTimeStamp (long arg) { this.endTimeStamp = arg; } + public void setStatus (String arg) { this.status = arg; } + + public String getServerName () { return this.serverName ; } + public String getUuid () { return this.uuid ; } + public String getProcessType () { return this.processType ; } + public String getProcessCode () { return this.processCode ; } + public String getProcessName () { return this.processName ; } + public String getOrganCode () { return this.organCode ; } + public String getOrganName () { return this.organName ; } + public String getAdapterGroupName() { return this.adapterGroupName; } + public String getAdapterName () { return this.adapterName ; } + public String getLocalIp () { return this.localIp ; } + public String getLocalPort () { return this.localPort ; } + public String getRemoteIp () { return this.remoteIp ; } + public String getRemotePort () { return this.remotePort ; } + public long getStartTimeStamp () { return this.startTimeStamp ; } + public long getEndTimeStamp () { return this.endTimeStamp ; } + public String getStatus () { return this.status ; } + +// public int compareTo(Object arg0) { +// SocketSessionVO info = (SocketSessionVO) arg0; +// int compare = 0; +// if ((compare = this.getServerName ().compareTo(info.getServerName ())) != 0) return compare; +// if ((compare = this.getAdapterGroupName().compareTo(info.getAdapterGroupName())) != 0) return compare; +// if ((compare = this.getAdapterName ().compareTo(info.getAdapterName ())) != 0) return compare; +// return (int) (this.getStartTimeStamp() - info.getStartTimeStamp()); +// } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("\nSocketSessionVO [ "); + sb.append("serverName=" ).append(serverName ); + sb.append(", uuid=" ).append(uuid ); + sb.append(", processType=" ).append(processType ); + sb.append(", processCode=" ).append(processCode ); + sb.append(", processName=" ).append(processName ); + sb.append(", organCode=" ).append(organCode ); + sb.append(", organName=" ).append(organName ); + sb.append(", adapterGroupName=").append(adapterGroupName); + sb.append(", adapterName=" ).append(adapterName ); + sb.append(", localIp=" ).append(localIp ); + sb.append(", localPort=" ).append(localPort ); + sb.append(", remoteIp=" ).append(remoteIp ); + sb.append(", remotePort=" ).append(remotePort ); + sb.append(", startTimeStamp=" ).append(startTimeStamp ); + sb.append(", endTimeStamp=" ).append(endTimeStamp ); + sb.append(", status=" ).append(status ); + sb.append(" ]"); + + return sb.toString(); + } +} diff --git a/src/com/eactive/eai/agent/adapter/socket/SocketStartStopCommand.java b/src/com/eactive/eai/agent/adapter/socket/SocketStartStopCommand.java new file mode 100644 index 0000000..f14d359 --- /dev/null +++ b/src/com/eactive/eai/agent/adapter/socket/SocketStartStopCommand.java @@ -0,0 +1,127 @@ +package com.eactive.eai.agent.adapter.socket; + +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.util.Logger; + +public class SocketStartStopCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public static final String START_SOCKET_SERVER = "START_SOCKET_SERVER"; + public static final String STOP_SOCKET_SERVER = "STOP_SOCKET_SERVER"; + public static final String START_SOCKET_SESSION = "START_SOCKET_SESSION"; + public static final String STOP_SOCKET_SESSION = "STOP_SOCKET_SESSION"; + + + public SocketStartStopCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + String startStopType = argArray[0]; //기동중지 구분 + String adapterGroupName = argArray[1]; //어댑터그룹명 + String adapterName = argArray[2]; //어댑터명 + String uuid = argArray.length<4? "":argArray[3]; //UUID (세션종료시만 사용) + logger.info("※ 기동/종료구분 : "+ startStopType); + logger.info("※ 어댑터그룹 : "+ adapterGroupName); + logger.info("※ 어댑터 : "+ adapterName); + logger.info("※ UUID : "+ uuid); + + String retValue = ""; + if (startStopType.equals(START_SOCKET_SERVER)) { + retValue = SocketAdapterManager.getInstance().start(adapterGroupName, adapterName); + + } else if (startStopType.equals(STOP_SOCKET_SERVER)) { + retValue = SocketAdapterManager.getInstance().stop(adapterGroupName, adapterName); + + } else if (startStopType.equals(STOP_SOCKET_SESSION)) { + logger.debug("★★★★★★★★★★★★★★★★ SocketStartStopCommand : 사용자에 의한 Socket Session 강제 종료가 요청되었습니다. ★★★★★★★★★★★★★★★★"); + BatchRunningJobManager.getInstance().closeRunningSocket(uuid); + retValue = "Socket Session 강제 종료가 완료 되었습니다."; + + } else { + throw new Exception("Start/Stop 구분 파라미터 오류"); + } + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return retValue; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } + + + +// private void stopSession(String adapterGroupName, String adapterName, String remoteIpPort) throws Exception { +// +// String[] TempIpPort = remoteIpPort.split(":"); +// String remoteIp = TempIpPort[0]; +// String remotePort = TempIpPort[1]; +// +// //소켓서버에 연결된 전체 Session 정보를 메모리에서 조회 +// //(연결된 Session 이 없어도 각 AdapterGroup 별 LinkedList 정보가 존재함) +// HashMap allSessions = SocketAdapterManager.getInstance().getAllSessions(); +// if (allSessions == null || allSessions.size() == 0) throw new Exception("모든 어댑터그룹의 세션 정보가 비어있습니다."); +// +// //AdapterGroup 명 조회 +// Object[] adapterGroupNames = allSessions.keySet().toArray(); +// //Arrays.sort(adapterGroupNames); +// +// //=================================================================================== +// //AdapterGroup 별 LOOP +// for (int i=0; i "+ adapterGroupNames[i]); +// if (!adapterGroupName.equals(adapterGroupNames[i])) continue; +// +// //해당 AdapterGroup의 현재 연결된 Session 정보 조회 +// //(Adapter 별로 분리하지 않고 연결 순서대로 들어가있다) +// LinkedList serviceList = (LinkedList) allSessions.get(adapterGroupNames[i]); +// if (serviceList == null || serviceList.size() == 0) break; +// +// //------------------------------------------------------------------- +// //Adapter 별 LOOP +// for (int k=0; k "+ avo.getName() +" / "+ session.getRemoteIPAddress() +" / "+ session.getRemotePort()); +// +// if (adapterName.equals(avo.getName()) && +// remoteIp.equals(session.getRemoteIPAddress()) && +// remotePort.equals(session.getRemotePort()) ) { +// +// session.disconnect(); +// SocketAdapterManager.getInstance().removeConnection(session); +// return; +// } +// } +// //------------------------------------------------------------------- +// } +// //=================================================================================== +// +// throw new Exception("해당 세션이 이미 종료 되었습니다."); +// } + +} diff --git a/src/com/eactive/eai/agent/code/RemoveCodeMessageCommand.java b/src/com/eactive/eai/agent/code/RemoveCodeMessageCommand.java new file mode 100644 index 0000000..53eec0e --- /dev/null +++ b/src/com/eactive/eai/agent/code/RemoveCodeMessageCommand.java @@ -0,0 +1,62 @@ +package com.eactive.eai.agent.code; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.code.CodeMessageManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 CodeMessageManager의 정보 변경 +* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO제거 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemoveCodeMessageCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveCodeMessageCommand(String name) { + super(name); + } + + /** + * 1. 기능 : CodeMessageManager에 CodeMessageVO제거 + * 2. 처리 개요 : CodeMessageManager에 CodeMessageVO제거 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String msgKey = (String) args; + CodeMessageManager.getInstance().removeMessage(msgKey); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/code/UpdateCodeMessageCommand.java b/src/com/eactive/eai/agent/code/UpdateCodeMessageCommand.java new file mode 100644 index 0000000..b69d923 --- /dev/null +++ b/src/com/eactive/eai/agent/code/UpdateCodeMessageCommand.java @@ -0,0 +1,64 @@ +package com.eactive.eai.agent.code; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.code.CodeMessageManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 CodeMessageManager의 정보 변경 +* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO 데이터 변경 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class UpdateCodeMessageCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateCodeMessageCommand(String name) { + super(name); + } + + /** + * 1. 기능 : CodeMessageManager에 CodeMessageVO 데이터 변경 + * 2. 처리 개요 : CodeMessageManager에 CodeMessageVO 데이터 변경 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if( !(args instanceof java.lang.String) ) { + String rspErrorCode = "RECEAIMCM001"; + String msg = makeException(rspErrorCode, null); + if (logger.isError()) logger.error(msg); + throw new CommandException(msg); + } + + String key = (String) args; + + try{ + CodeMessageManager manager = CodeMessageManager.getInstance(); + manager.reload(key); + }catch (Exception e){ + String rspErrorCode = "RECEAIMCM002"; + String msg = makeException(rspErrorCode, e); + if (logger.isError()) logger.error(msg,e); + throw new CommandException(msg); + } + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + } + +} diff --git a/src/com/eactive/eai/agent/command/Command.java b/src/com/eactive/eai/agent/command/Command.java new file mode 100644 index 0000000..5ed6726 --- /dev/null +++ b/src/com/eactive/eai/agent/command/Command.java @@ -0,0 +1,119 @@ +package com.eactive.eai.agent.command; + +import java.io.Serializable; +import java.util.HashMap; + +/** +* 1. 기능 : Agent에 의해 실행될 Command 를 정의하기 위한 base class +* 2. 처리 개요 : Agent에 의해 실행될 Command 를 정의하기 위한 base class +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +* +*/ +public abstract class Command implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + /** Command object name */ + protected String name; + /** Command Arguments */ + protected Object args; + + private HashMap errorCode ; + + static { + HashMap errorCode = new HashMap(); + errorCode.put("RECEAIMCM001", "Command 이름[{1}] 유효하지 않은 파라메터 타입 - {2}"); + errorCode.put("RECEAIMCM002", "Command 이름[{1}] execute 메소드 실행중 에러가 발생 - {2}"); + } + + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : name을 Class name으로 setting한다. + * 3. 주의사항 + * + **/ + public Command() { + this.name = this.getClass().getName(); + } + + /** + * 1. 기능 : 파리미터의 name을 setting하는 Constructor + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param name Command object name + **/ + public Command(String name) { + this.name = name; + } + + /** + * 1. 기능 : command의 arguments를 setting하는 setter method + * 2. 처리 개요 : command의 arguments를 setting하는 setter method + * 3. 주의사항 + * + * @param args command arguments + **/ + public void setArgs(Object args) { + this.args = args; + } + + + /** + * 1. 기능 : command의 business logic method
+ * 2. 처리 개요 : command의 business logic method
+ * 3. 주의사항 + * + * @exception CommandException + **/ + public abstract Object execute() throws CommandException; + + /** + * 1. 기능 : 에러 Message 생성 + * 2. 처리 개요 : 에러코드와 Exception cause로 에러 메시지 생성 + * 3. 주의사항 + * + * @param rspErrorcode EAI 에러코드 + * @param cause Exception cause + * @return String 에러 메시지 + * @exception CommandException + **/ + protected String makeException(String rspErrorCode, Throwable cause) throws CommandException{ + String[] msgArgs = new String[2]; + msgArgs[0] = name; + if(cause == null){ + msgArgs[1] = args.toString(); + } + else{ + msgArgs[1] = cause.getMessage(); + } + String msg = makeMessage((String)errorCode.get(rspErrorCode),msgArgs) ; + + return msg; + } + + protected static String makeMessage(String msg, String[] args) { + String keyword = null, head = null, tail = null; + int idx = -1; + for(int i=0;i +* 2. 처리 개요 : Command Logic을 실행하다 발생될 User Define 오류를 처리하기 위한 Exception class
+* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +* +*/ +public class CommandException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : Default Constructor + * 3. 주의사항 + * + **/ + public CommandException() { + super("CommandException is occured."); + } + + /** + * 1. 기능 : Exception message를 초기화하는 Constructor + * 2. 처리 개요 : Exception message를 초기화하는 Constructor + * - + * 3. 주의사항 + * + * @param msg Exception message + **/ + public CommandException(String msg) { + super(msg); + } +} diff --git a/src/com/eactive/eai/agent/command/CommonCommand.java b/src/com/eactive/eai/agent/command/CommonCommand.java new file mode 100644 index 0000000..fa20873 --- /dev/null +++ b/src/com/eactive/eai/agent/command/CommonCommand.java @@ -0,0 +1,55 @@ +package com.eactive.eai.agent.command; + +import java.lang.reflect.Constructor; + +/** +* 1. 기능 : 공통 command +* 2. 처리 개요 : +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +* +*/ +public class CommonCommand extends Command { + + private static final long serialVersionUID = 1L; + + + public CommonCommand(String name,Object args) { + this.name = name; + this.args = args; + } + + public CommonCommand(String name) { + this.name = name; + } + + public Object execute() throws CommandException + { + if (name.indexOf(".") >=0 ){ + try { + @SuppressWarnings("rawtypes") + Class cl = Class.forName(this.name); + @SuppressWarnings({ "rawtypes", "unchecked" }) + Constructor constructor = cl.getConstructor(String.class); + Object obj = constructor.newInstance(this.name); + Command c = (Command)obj; + c.setArgs(args); + return c.execute(); + + } catch (Exception e) { + e.printStackTrace(); + String rspErrorCode = "RECEAIMCM002"; + String msg = makeException(rspErrorCode, null); + throw new CommandException(msg); + } + }else{ + String rspErrorCode = "RECEAIMCM001"; + String msg = makeException(rspErrorCode, null); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/flowController/AddBatchTargetCommand.java b/src/com/eactive/eai/agent/flowController/AddBatchTargetCommand.java new file mode 100644 index 0000000..913cd09 --- /dev/null +++ b/src/com/eactive/eai/agent/flowController/AddBatchTargetCommand.java @@ -0,0 +1,83 @@ +package com.eactive.eai.agent.flowController; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerDAO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class AddBatchTargetCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : AddBatchTargetCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public AddBatchTargetCommand(String name) { + super(name); + } + + /** + * 1. 기능 : FlowControllerManager BatchTargetVO 추가 + * 2. 처리 개요 : FlowControllerManager BatchTargetVO 추가 + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + String processCode = argArray[0]; + String organCode = argArray[1]; + // add by kscheon +// String adapterGroupName = argArray[2]; + + FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class); + BatchTargetVO vo = dao.getBatchTargetVO(processCode, organCode); + + FlowControllerManager.getInstance().getTargets().put(processCode + organCode, vo); + +// //20080429 Adapter에 대외기관 코드 추가 - by kscheon - start +// AdapterGroupVO current = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName); +// if (current == null){ +// logger.info(this.name +" Manager's AdapterGroupVO is null. -- "+adapterGroupName); +// +// }else { +// current.setBatchProcessCode(processCode); +// current.setBatchInstitutionCode(organCode); +// } +// //20080429 Adapter에 대외기관 코드 추가 - by kscheon - end + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/flowController/RemoveBatchTargetCommand.java b/src/com/eactive/eai/agent/flowController/RemoveBatchTargetCommand.java new file mode 100644 index 0000000..279906e --- /dev/null +++ b/src/com/eactive/eai/agent/flowController/RemoveBatchTargetCommand.java @@ -0,0 +1,64 @@ +package com.eactive.eai.agent.flowController; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.common.util.Logger; + +public class RemoveBatchTargetCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : RemoveBatchTargetCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @paramw + * @return + * @exception + **/ + public RemoveBatchTargetCommand(String name) { + super(name); + } + + /** + * 1. 기능 : RemoveBatchTargetCommand BatchTargetVO 제거 + * 2. 처리 개요 : RemoveBatchTargetCommand BatchTargetVO 제거 + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + String processCode = argArray[0]; + String organCode = argArray[1]; + + FlowControllerManager.getInstance().getTargets().remove(processCode + organCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/flowController/UpdateBatchTargetCommand.java b/src/com/eactive/eai/agent/flowController/UpdateBatchTargetCommand.java new file mode 100644 index 0000000..dc82151 --- /dev/null +++ b/src/com/eactive/eai/agent/flowController/UpdateBatchTargetCommand.java @@ -0,0 +1,86 @@ +package com.eactive.eai.agent.flowController; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.DemandTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerDAO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class UpdateBatchTargetCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : UpdateBatchTargetCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public UpdateBatchTargetCommand() { + super("UpdateBatchTargetCommand"); + } + + /** + * 1. 기능 : UpdateBatchTargetCommand BatchTargetVO 변경 + * 2. 처리 개요 : UpdateBatchTargetCommand BatchTargetVO 변경 + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + String processCode = argArray[0]; + String organCode = argArray[1]; + String organStatus = (argArray.length > 2)? argArray[2] : ""; + + //Framework 에서 장애(회복)통보 전문 수신시 대외기관 상태를 변경하는 경우 + //테이블 update 가 commit이 안된 상태이므로 메모리의 정보를 직접 변경해야 한다. + if (!organStatus.equals("")) { + logger.debug(" - 대외기관 요구송수신 연결 정보 Memory update ("+ processCode +", "+ organCode +", "+ (organStatus.equals(DemandTargetVO.ORGAN_SOCKET_STATUS_ERROR)? "장애" : "정상") +")"); + DemandTargetVO[] demandTargetList = FlowControllerManager.getInstance().getRemoteHostInfo(processCode, organCode); + for (int i=0; i 대외기관 요구송수신 연결 정보 ☞ (IP: "+ demandTargetList[i].getIpAddress() +", Port: "+ demandTargetList[i].getPortNumber() +", ID: "+ demandTargetList[i].getSocketID() +", PW: "+ demandTargetList[i].getSocketPwd() +", Timeout: "+ demandTargetList[i].getTimeoutInterval() +", OrganStatus: "+ demandTargetList[i].getOrganSocketStatus() +")"); + } + + //관리 UI에서 대외기관 정보를 수정한 경우 + } else { + FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class); + BatchTargetVO vo = dao.getBatchTargetVO(processCode, organCode); + + FlowControllerManager.getInstance().getTargets().put(processCode + organCode, vo); + } + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/flowController/UpdateBatchTargetForRTSCommand.java b/src/com/eactive/eai/agent/flowController/UpdateBatchTargetForRTSCommand.java new file mode 100644 index 0000000..27c0dfb --- /dev/null +++ b/src/com/eactive/eai/agent/flowController/UpdateBatchTargetForRTSCommand.java @@ -0,0 +1,87 @@ +package com.eactive.eai.agent.flowController; + +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerDAO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class UpdateBatchTargetForRTSCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : UpdateBatchTargetForRTSCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public UpdateBatchTargetForRTSCommand() { + super("UpdateBatchTargetForRTSCommand"); + } + + /** + * 1. 기능 : UpdateBatchTargetForRTSCommand BatchTargetVO 변경 + * 2. 처리 개요 : UpdateBatchTargetForRTSCommand BatchTargetVO 변경 + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + String processCode = argArray[0]; + String organCode = argArray[1]; +// add by kscheon + String adapterGroupName = argArray[2]; + + FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class); + BatchTargetVO vo = dao.getBatchTargetVO(processCode, organCode); + + FlowControllerManager.getInstance().getTargets().put(processCode + organCode, vo); + +// 20080429 Adapter에 대외기관 코드 추가 - by kscheon - start + AdapterGroupVO current = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName); + + if (current == null){ + logger.info(this.name +" Manager's AdapterGroupVO is null. -- "+adapterGroupName); + + } else { + current.setBatchProcessCode(processCode); + current.setBatchInstitutionCode(organCode); + } + //20080429 Adapter에 대외기관 코드 추가 - by kscheon - end + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/ftp/RemoteTransferCommand.java b/src/com/eactive/eai/agent/ftp/RemoteTransferCommand.java new file mode 100644 index 0000000..a9c55fc --- /dev/null +++ b/src/com/eactive/eai/agent/ftp/RemoteTransferCommand.java @@ -0,0 +1,52 @@ +package com.eactive.eai.agent.ftp; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.inbound.remote.RemoteTransfer; +import com.eactive.eai.inbound.remote.RemoteTransferLogKeys; +import com.eactive.eai.inbound.remote.RemoteTransferLogManager; +import com.eactive.eai.inbound.remote.RemoteTransferLogVO; + +public class RemoteTransferCommand extends Command +{ + private static final long serialVersionUID = 1L; + + public RemoteTransferCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + String[] param = (String[])args; + String logID = param[0]; + String userId = param[1]; + + try { + logger.debug("[RemoteTransferCommand]logID-->[" + logID + "]"); + RemoteTransferLogVO log = RemoteTransferLogManager.getInstance().getRemoteTransferLog(logID); + RemoteTransfer transfer = new RemoteTransfer(); + if (log.getSendRecvYn().equals(RemoteTransferLogKeys.SEND)){ + transfer.sendFile(log.getBjobBzwkDstcd(), log.getOsidInstiDstcd(), log.getTrsmtFileName(), RemoteTransferLogKeys.START_BY_UI, userId, false); + return transfer.sendFile(log.getBjobBzwkDstcd(), log.getOsidInstiDstcd(), log.getTrsmtFileName(), RemoteTransferLogKeys.START_BY_UI, userId, true); + }else{ + return transfer.recvFile( log.getRmtFileTrsmtPathName() + "/" + log.getTrsmtFileName(), RemoteTransferLogKeys.START_BY_UI, userId); + } + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/holiday/RemoveHolidayCommand.java b/src/com/eactive/eai/agent/holiday/RemoveHolidayCommand.java new file mode 100644 index 0000000..0589e52 --- /dev/null +++ b/src/com/eactive/eai/agent/holiday/RemoveHolidayCommand.java @@ -0,0 +1,68 @@ +package com.eactive.eai.agent.holiday; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager; +import com.eactive.eai.batch.eventscheduler.holiday.HolidayVO; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경 +* 2. 처리 개요 : HolidayManager에 HolidayVO제거 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemoveHolidayCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveHolidayCommand(String name) { + super(name); + } + + /** + * 1. 기능 : HolidayManager에 HolidayVO제거 + * 2. 처리 개요 : HolidayManager에 HolidayVO제거 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + String holidayType = argArray[0]; + String holiday = argArray[1]; + String description = argArray[2]; + + HolidayVO vo = new HolidayVO(holidayType, holiday, description); + HolidayManager manager = HolidayManager.getInstance(); + + manager.removeHoliday(vo); + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/holiday/UpdateHolidayCommand.java b/src/com/eactive/eai/agent/holiday/UpdateHolidayCommand.java new file mode 100644 index 0000000..2608411 --- /dev/null +++ b/src/com/eactive/eai/agent/holiday/UpdateHolidayCommand.java @@ -0,0 +1,71 @@ +package com.eactive.eai.agent.holiday; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager; +import com.eactive.eai.batch.eventscheduler.holiday.HolidayVO; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경 +* 2. 처리 개요 : HolidayManager에 HolidayVO추가 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class UpdateHolidayCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateHolidayCommand(String name) { + super(name); + } + + /** + * 1. 기능 : HolidayManager에 HolidayVO추가 + * 2. 처리 개요 : HolidayManager에 HolidayVO추가 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + String holidayType = argArray[0]; + String holiday = argArray[1]; + String description = argArray[2]; + + + HolidayVO vo = new HolidayVO(holidayType, holiday, description); + + HolidayManager manager = HolidayManager.getInstance(); + manager.setHoliday(vo); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/kikwaninfo/RemoveKikwaninfoCommand.java b/src/com/eactive/eai/agent/kikwaninfo/RemoveKikwaninfoCommand.java new file mode 100644 index 0000000..5ea1c92 --- /dev/null +++ b/src/com/eactive/eai/agent/kikwaninfo/RemoveKikwaninfoCommand.java @@ -0,0 +1,62 @@ +package com.eactive.eai.agent.kikwaninfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경 +* 2. 처리 개요 : HolidayManager에 HolidayVO제거 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemoveKikwaninfoCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveKikwaninfoCommand(String name) { + super(name); + } + + /** + * 1. 기능 : HolidayManager에 HolidayVO제거 + * 2. 처리 개요 : HolidayManager에 HolidayVO제거 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String kikwanCd = (String) args; + KikwanInfoManager manager = KikwanInfoManager.getInstance(); + + manager.removeKikwanInfo(kikwanCd); + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/kikwaninfo/UpdateKikwaninfoCommand.java b/src/com/eactive/eai/agent/kikwaninfo/UpdateKikwaninfoCommand.java new file mode 100644 index 0000000..da2febe --- /dev/null +++ b/src/com/eactive/eai/agent/kikwaninfo/UpdateKikwaninfoCommand.java @@ -0,0 +1,64 @@ +package com.eactive.eai.agent.kikwaninfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경 +* 2. 처리 개요 : HolidayManager에 HolidayVO추가 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class UpdateKikwaninfoCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateKikwaninfoCommand(String name) { + super(name); + } + + /** + * 1. 기능 : HolidayManager에 HolidayVO추가 + * 2. 처리 개요 : HolidayManager에 HolidayVO추가 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String kikwanCd = (String) args; + + KikwanInfoManager manager = KikwanInfoManager.getInstance(); + manager.setKikwanInfo(kikwanCd); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/makeDir/GetScriptListCommand.java b/src/com/eactive/eai/agent/makeDir/GetScriptListCommand.java new file mode 100644 index 0000000..9c96c33 --- /dev/null +++ b/src/com/eactive/eai/agent/makeDir/GetScriptListCommand.java @@ -0,0 +1,73 @@ +//package com.eactive.eai.agent.makeDir; +// +//import java.io.File; +//import java.util.ArrayList; +//import java.util.Collections; +// +//import com.eactive.eai.agent.command.Command; +//import com.eactive.eai.agent.command.CommandException; +//import com.eactive.eai.common.property.PropManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import com.eactive.eai.inbound.remote.NDMTransferByScript; +// +// +//public class GetScriptListCommand extends Command +//{ +// +// /** +// * +// */ +// private static final long serialVersionUID = 1L; +// +// public GetScriptListCommand() { +// super("GetScriptListCommand"); +// } +// +// public Object execute() throws CommandException +// { +// Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT); +// logger.info(this.name + " Agent 가 호출되었습니다."); +// +// ArrayList returnList = new ArrayList(); +// String sendShell = PropManager.getInstance().getProperty(NDMTransferByScript.PROP_GROUP_REMOTE_TRANSFER_NDM, NDMTransferByScript.PROP_NDM_SEND_SCRIPT_PATH); +// if ( sendShell == null ){ +// logger.error(this.name + "PROPERTY가 등록되어 있지 않습니다.[" + NDMTransferByScript.PROP_GROUP_REMOTE_TRANSFER_NDM + "],[" + NDMTransferByScript.PROP_NDM_SEND_SCRIPT_PATH + "]"); +// return null; +// } +// +// File file = new File(sendShell); +// String path = file.getParent(); +// +// file = new File(path); +// +// if ( file.exists() ) { +// File[] tmplist = file.listFiles(); +// ArrayList al = new ArrayList(); +// for ( int inx = 0; inx < tmplist.length; inx++){ +// al.add(tmplist[inx]); +// } +// +// Collections.sort( al ); +// +// int len = al.size(); +// File[] list = new File[len]; +// for ( int inx = 0; inx < len; inx++ ){ +// list[inx]=al.get(inx); +// } +// for ( int inx = 0; inx < list.length; inx++){ +// file = list[inx]; +// if ( file.isFile()){ +// String fileName = file.getPath(); +// if ( fileName.endsWith( ".sh" ) ) +// { +// returnList.add( fileName ); +// } +// } +// } +// } +// return returnList; +// +// } +// +//} diff --git a/src/com/eactive/eai/agent/makeDir/MakeDirOrganCommand.java b/src/com/eactive/eai/agent/makeDir/MakeDirOrganCommand.java new file mode 100644 index 0000000..fa1d99f --- /dev/null +++ b/src/com/eactive/eai/agent/makeDir/MakeDirOrganCommand.java @@ -0,0 +1,49 @@ +package com.eactive.eai.agent.makeDir; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.common.util.Logger; + +public class MakeDirOrganCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public MakeDirOrganCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + + String processCode = argArray[0]; + String organCode = argArray[1]; + + BatchDirUtil.makeDirOrgan(processCode, organCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/makeDir/MakeDirProcessCommand.java b/src/com/eactive/eai/agent/makeDir/MakeDirProcessCommand.java new file mode 100644 index 0000000..3f9f502 --- /dev/null +++ b/src/com/eactive/eai/agent/makeDir/MakeDirProcessCommand.java @@ -0,0 +1,45 @@ +package com.eactive.eai.agent.makeDir; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.common.util.Logger; + +public class MakeDirProcessCommand extends Command +{ + + private static final long serialVersionUID = 1L; + + public MakeDirProcessCommand() { + super("MakeDirProcessCommand"); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + + String processCode = argArray[0]; + + BatchDirUtil.makeDirProcess(processCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/makeDir/RemoveDirOrganCommand.java b/src/com/eactive/eai/agent/makeDir/RemoveDirOrganCommand.java new file mode 100644 index 0000000..e6fad74 --- /dev/null +++ b/src/com/eactive/eai/agent/makeDir/RemoveDirOrganCommand.java @@ -0,0 +1,49 @@ +package com.eactive.eai.agent.makeDir; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.common.util.Logger; + +public class RemoveDirOrganCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveDirOrganCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + + String processCode = argArray[0]; + String organCode = argArray[1]; + + BatchDirUtil.removeDirOrgan(processCode, organCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/makeDir/RemoveDirProcessCommand.java b/src/com/eactive/eai/agent/makeDir/RemoveDirProcessCommand.java new file mode 100644 index 0000000..850f448 --- /dev/null +++ b/src/com/eactive/eai/agent/makeDir/RemoveDirProcessCommand.java @@ -0,0 +1,48 @@ +package com.eactive.eai.agent.makeDir; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.common.util.Logger; + +public class RemoveDirProcessCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveDirProcessCommand() { + super("RemoveDirProcessCommand"); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] argArray = (String[]) args; + + String processCode = argArray[0]; + + BatchDirUtil.removeDirProcess(processCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/osd/RemoveOutsideCommand.java b/src/com/eactive/eai/agent/osd/RemoveOutsideCommand.java new file mode 100644 index 0000000..cad9964 --- /dev/null +++ b/src/com/eactive/eai/agent/osd/RemoveOutsideCommand.java @@ -0,0 +1,69 @@ +package com.eactive.eai.agent.osd; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 OutsideManager의 정보 변경 +* 2. 처리 개요 : OutsideManager에 OutsideVO추가 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemoveOutsideCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveOutsideCommand(String name) { + super(name); + } + + /** + * 1. 기능 : OutsideManager에 OutsideVO추가 + * 2. 처리 개요 : OutsideManager에 OutsideVO추가 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + String[] argArray = (String[]) args; + String batchCode = argArray[0]; + String outCode = argArray[1]; + + try { + + OutsideManager manager = OutsideManager.getInstance(); + + manager.removeOutsideInfo(batchCode, outCode); + manager.removeOutsideLinkInfo(batchCode, outCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/osd/UpdateOutsideCommand.java b/src/com/eactive/eai/agent/osd/UpdateOutsideCommand.java new file mode 100644 index 0000000..1b5dba4 --- /dev/null +++ b/src/com/eactive/eai/agent/osd/UpdateOutsideCommand.java @@ -0,0 +1,68 @@ +package com.eactive.eai.agent.osd; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 OutsideManager의 정보 변경 +* 2. 처리 개요 : OutsideManager에 OutsideVO추가 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class UpdateOutsideCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateOutsideCommand(String name) { + super(name); + } + + /** + * 1. 기능 : OutsideManager의 OutsideVO, OustsideLinkVO변경 + * 2. 처리 개요 : OutsideManager의 OutsideVO, OustsideLinkVO변 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + OutsideManager manager = OutsideManager.getInstance(); + + try { + String[] argArray = (String[]) args; + String processCode = argArray[0]; + String organCode = argArray[1]; + + manager.updateOutsideInfo(processCode, organCode); + manager.updateOutsideLinkInfo(processCode, organCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/property/RemovePropertyCommand.java b/src/com/eactive/eai/agent/property/RemovePropertyCommand.java new file mode 100644 index 0000000..22cbc02 --- /dev/null +++ b/src/com/eactive/eai/agent/property/RemovePropertyCommand.java @@ -0,0 +1,74 @@ +package com.eactive.eai.agent.property; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 PropManager의 정보 변경 +* 2. 처리 개요 : PropManager에서 해당 PropGroupVO 제거 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemovePropertyCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : RemovePropertyCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public RemovePropertyCommand(String name) { + super(name); + } + + /** + * 1. 기능 : PropManager에서 해당 PropGroupVO 제거 + * 2. 처리 개요 : PropGroupVO EAISvrInstNm이 DEFAULT_SERVER(ALL) 이거나 LocalServer인 경우 + * PropManager에서 해당 PropGroupVO 제거 + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + + PropManager.getInstance().removePropGroupVO((String)args); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/property/UpdatePropertyCommand.java b/src/com/eactive/eai/agent/property/UpdatePropertyCommand.java new file mode 100644 index 0000000..10983cb --- /dev/null +++ b/src/com/eactive/eai/agent/property/UpdatePropertyCommand.java @@ -0,0 +1,86 @@ +package com.eactive.eai.agent.property; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.common.property.PropGroupVO; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 PropManager의 정보 변경 +* 2. 처리 개요 : PropManager에서 해당 PropGroupVO 의 데이터 수정 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class UpdatePropertyCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : UpdatePropertyCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public UpdatePropertyCommand(String name) { + super(name); + } + + /** + * 1. 기능 : PropManager에서 해당 PropGroupVO 의 데이터 수정 + * 2. 처리 개요 : PropGroupVO EAISvrInstNm이 DEFAULT_SERVER(ALL) 이거나 LocalServer인 경우 + * PropManager에서 해당 PropGroupVO 의 데이터 수정 + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + + PropGroupVO vo = PropManager.getInstance().getPropGroupVOinDB((String)args); + + logger.info(this.name +": (Agent Argument) PropGroupName=["+vo.getName()+"]"); + + PropManager.getInstance().setPropGroupVO((String)args, vo); + + /** + * FileLogger log.level modify + */ + if(((String)args).startsWith("FileLogger{")){ + com.eactive.eai.common.util.Logger.reloadLogLevel((String)args); + } + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/rule/dirInfo/RefreshAllJobCommand.java b/src/com/eactive/eai/agent/rule/dirInfo/RefreshAllJobCommand.java new file mode 100644 index 0000000..b9f0dcc --- /dev/null +++ b/src/com/eactive/eai/agent/rule/dirInfo/RefreshAllJobCommand.java @@ -0,0 +1,37 @@ +package com.eactive.eai.agent.rule.dirInfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.util.Logger; + +public class RefreshAllJobCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RefreshAllJobCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + try { + DirInfoManager.getInstance().loadAllFileInfo(); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "sucess"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/nodeinfo/RemoveNodeInfoCommand.java b/src/com/eactive/eai/agent/rule/nodeinfo/RemoveNodeInfoCommand.java new file mode 100644 index 0000000..40da84c --- /dev/null +++ b/src/com/eactive/eai/agent/rule/nodeinfo/RemoveNodeInfoCommand.java @@ -0,0 +1,58 @@ +package com.eactive.eai.agent.rule.nodeinfo; + +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoDAO; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class RemoveNodeInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveNodeInfoCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" " + msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + NodeInfoDAO dao = (NodeInfoDAO)DAOFactory.newInstance().create(NodeInfoDAO.class); + HashMap> map = dao.getAllNodeInfo(); + ArrayList al = map.get(strRuleCode); + if (al == null) { + NodeInfoManager.getInstance().removeRuleCodeArray(strRuleCode); + }else{ + NodeInfoManager.getInstance().setRuleCodeArray(strRuleCode, al); + } + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/nodeinfo/UpdateNodeInfoCommand.java b/src/com/eactive/eai/agent/rule/nodeinfo/UpdateNodeInfoCommand.java new file mode 100644 index 0000000..72875a0 --- /dev/null +++ b/src/com/eactive/eai/agent/rule/nodeinfo/UpdateNodeInfoCommand.java @@ -0,0 +1,59 @@ +package com.eactive.eai.agent.rule.nodeinfo; + +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoDAO; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class UpdateNodeInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateNodeInfoCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" " + msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + NodeInfoDAO dao = (NodeInfoDAO)DAOFactory.newInstance().create(NodeInfoDAO.class); + HashMap> map = dao.getAllNodeInfo(); + ArrayList al = map.get(strRuleCode); + if (al == null) { + String errMsg = this.name + ": error >> RuleCode [" + strRuleCode + "] not found in DBMS"; + logger.error(errMsg); + return errMsg; + } + NodeInfoManager.getInstance().setRuleCodeArray(strRuleCode, al); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/phaseinfo/RemovePhaseInfoCommand.java b/src/com/eactive/eai/agent/rule/phaseinfo/RemovePhaseInfoCommand.java new file mode 100644 index 0000000..5a9187a --- /dev/null +++ b/src/com/eactive/eai/agent/rule/phaseinfo/RemovePhaseInfoCommand.java @@ -0,0 +1,46 @@ +package com.eactive.eai.agent.rule.phaseinfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoManager; +import com.eactive.eai.common.util.Logger; + + +public class RemovePhaseInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemovePhaseInfoCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + PhaseInfoManager.getInstance().removeRuleCodeArray(strRuleCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/phaseinfo/UpdatePhaseInfoCommand.java b/src/com/eactive/eai/agent/rule/phaseinfo/UpdatePhaseInfoCommand.java new file mode 100644 index 0000000..067797e --- /dev/null +++ b/src/com/eactive/eai/agent/rule/phaseinfo/UpdatePhaseInfoCommand.java @@ -0,0 +1,59 @@ +package com.eactive.eai.agent.rule.phaseinfo; + +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoDAO; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoManager; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class UpdatePhaseInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdatePhaseInfoCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + PhaseInfoDAO dao = (PhaseInfoDAO)DAOFactory.newInstance().create(PhaseInfoDAO.class); + HashMap> map = dao.getAllPhaseInfos(); + ArrayList al = map.get(strRuleCode); + if (al == null) { + String errMsg = this.name + ": error >> RuleCode [" + strRuleCode + "] not found in DBMS"; + logger.error(errMsg); + return errMsg; + } + PhaseInfoManager.getInstance().setRuleCodeArray(strRuleCode, al); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/ruleinfo/AddRuleInfoCommand.java b/src/com/eactive/eai/agent/rule/ruleinfo/AddRuleInfoCommand.java new file mode 100644 index 0000000..4211d99 --- /dev/null +++ b/src/com/eactive/eai/agent/rule/ruleinfo/AddRuleInfoCommand.java @@ -0,0 +1,58 @@ +package com.eactive.eai.agent.rule.ruleinfo; + +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoDAO; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class AddRuleInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public AddRuleInfoCommand() { + super("AddRuleInfoCommand"); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + RuleInfoDAO dao = (RuleInfoDAO)DAOFactory.newInstance().create(RuleInfoDAO.class); + HashMap map = dao.getAllRuleInfo(); + RuleInfoVO vo = map.get(strRuleCode); + if (vo == null) { + String errMsg = this.name + ": error >> RuleCode [" + strRuleCode + "] not found in DBMS"; + logger.error(errMsg); + return errMsg; + } + RuleInfoManager.getInstance().setRuleCodeArray(strRuleCode, vo); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/ruleinfo/RemoveRuleInfoCommand.java b/src/com/eactive/eai/agent/rule/ruleinfo/RemoveRuleInfoCommand.java new file mode 100644 index 0000000..7871dda --- /dev/null +++ b/src/com/eactive/eai/agent/rule/ruleinfo/RemoveRuleInfoCommand.java @@ -0,0 +1,47 @@ +package com.eactive.eai.agent.rule.ruleinfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.common.util.Logger; + +public class RemoveRuleInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + + public RemoveRuleInfoCommand() { + super("RemoveRuleInfoCommand"); + } + + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + RuleInfoManager.getInstance().removeRuleCodeArray(strRuleCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/ruleinfo/UpdateRuleInfoCommand.java b/src/com/eactive/eai/agent/rule/ruleinfo/UpdateRuleInfoCommand.java new file mode 100644 index 0000000..35a6bbf --- /dev/null +++ b/src/com/eactive/eai/agent/rule/ruleinfo/UpdateRuleInfoCommand.java @@ -0,0 +1,58 @@ +package com.eactive.eai.agent.rule.ruleinfo; + +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoDAO; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class UpdateRuleInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateRuleInfoCommand() { + super("UpdateRuleInfoCommand"); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + RuleInfoDAO dao = (RuleInfoDAO)DAOFactory.newInstance().create(RuleInfoDAO.class); + HashMap map = dao.getAllRuleInfo(); + RuleInfoVO vo = map.get(strRuleCode); + if (vo == null) { + String errMsg = this.name + ": error >> RuleCode [" + strRuleCode + "] not found in DBMS"; + logger.error(errMsg); + return errMsg; + } + RuleInfoManager.getInstance().setRuleCodeArray(strRuleCode, vo); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/telegraminfo/AddTelegramInfoCommand.java b/src/com/eactive/eai/agent/rule/telegraminfo/AddTelegramInfoCommand.java new file mode 100644 index 0000000..e37b9af --- /dev/null +++ b/src/com/eactive/eai/agent/rule/telegraminfo/AddTelegramInfoCommand.java @@ -0,0 +1,60 @@ +package com.eactive.eai.agent.rule.telegraminfo; + +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoDAO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class AddTelegramInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + + public AddTelegramInfoCommand() { + super("AddTelegramInfoCommand"); + } + + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = (String)args; + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + TelegramInfoDAO dao = (TelegramInfoDAO)DAOFactory.newInstance().create(TelegramInfoDAO.class); + HashMap map = dao.getAllTelegramInfos(); + TelegramInfoVO vo = map.get(strRuleCode); + if (vo == null) { + String errMsg = this.name + ": error >> RuleCode [" + strRuleCode + "] not found in DBMS"; + logger.error(errMsg); + throw new CommandException(errMsg); + } + TelegramInfoManager.getInstance().setRuleCodeArray(strRuleCode, vo); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/telegraminfo/RemoveTelegramInfoCommand.java b/src/com/eactive/eai/agent/rule/telegraminfo/RemoveTelegramInfoCommand.java new file mode 100644 index 0000000..0bc0b60 --- /dev/null +++ b/src/com/eactive/eai/agent/rule/telegraminfo/RemoveTelegramInfoCommand.java @@ -0,0 +1,49 @@ +package com.eactive.eai.agent.rule.telegraminfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.common.util.Logger; + +public class RemoveTelegramInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + + + public RemoveTelegramInfoCommand(String name) { + super(name); + } + + + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = ((String)args).trim(); + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + TelegramInfoManager.getInstance().removeRuleCodeArray(strRuleCode); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/rule/telegraminfo/UpdateTelegramInfoCommand.java b/src/com/eactive/eai/agent/rule/telegraminfo/UpdateTelegramInfoCommand.java new file mode 100644 index 0000000..7113a51 --- /dev/null +++ b/src/com/eactive/eai/agent/rule/telegraminfo/UpdateTelegramInfoCommand.java @@ -0,0 +1,59 @@ +package com.eactive.eai.agent.rule.telegraminfo; + +import java.util.HashMap; + + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoDAO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class UpdateTelegramInfoCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateTelegramInfoCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(this.name+" "+ msg); + throw new CommandException(msg); + } + + try { + String strRuleCode = ((String)args).trim(); + logger.info(this.name +": (Agent Argument) RuleCode=["+strRuleCode+"]"); + + TelegramInfoDAO dao = (TelegramInfoDAO)DAOFactory.newInstance().create(TelegramInfoDAO.class); + HashMap map = dao.getAllTelegramInfos(); + TelegramInfoVO vo = map.get(strRuleCode); + if (vo == null) { + String errMsg = this.name + ": error >> RuleCode [" + strRuleCode + "] not found in DBMS"; + logger.error(errMsg); + return errMsg; + } + TelegramInfoManager.getInstance().setRuleCodeArray(strRuleCode, vo); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/schedule/GetScheduleBasisListCommand.java b/src/com/eactive/eai/agent/schedule/GetScheduleBasisListCommand.java new file mode 100644 index 0000000..6e9a91a --- /dev/null +++ b/src/com/eactive/eai/agent/schedule/GetScheduleBasisListCommand.java @@ -0,0 +1,64 @@ +package com.eactive.eai.agent.schedule; + +import java.util.ArrayList; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.scheduler.ScheduleBasisManager; +import com.eactive.eai.common.util.Logger; +/** +* 1. 기능 +* 2. 처리 개요 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see : 관련 기능을 참조 +* @since +*/ + +public class GetScheduleBasisListCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 GetScheduleBasisListCommand 생성자 + * 2. 처리 개요 + * 3. 주의사항 + * + **/ + public GetScheduleBasisListCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + ArrayList holicodes = null; + + String day = (String)args; + if ( day.length() >0){ + holicodes = ScheduleBasisManager.getInstance().getIntervalTypes( day ); + }else{ + return null; + } + String[] arr = new String[holicodes.size()]; + for ( int inx = 0; inx < holicodes.size(); inx++){ + arr[inx] = holicodes.get(inx); + } + return arr; + } + +} diff --git a/src/com/eactive/eai/agent/schedule/RequestRecieveCommand.java b/src/com/eactive/eai/agent/schedule/RequestRecieveCommand.java new file mode 100644 index 0000000..2da3357 --- /dev/null +++ b/src/com/eactive/eai/agent/schedule/RequestRecieveCommand.java @@ -0,0 +1,47 @@ +package com.eactive.eai.agent.schedule; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.common.util.Logger; + +public class RequestRecieveCommand extends Command{ + + /** + * + */ + private static final long serialVersionUID = 1L; + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public RequestRecieveCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + logger.info(this.name +" 이 호출되었습니다."); + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] logKeys = (String[])args; + String scheduleCode = logKeys[0]; + String reqYYYYMMDD = logKeys[1]; + logger.debug("scheduleCode---->" + scheduleCode); + logger.debug("reqYYYYMMDD----->" + reqYYYYMMDD); + SchedulerMessageManager manager = SchedulerMessageManager.getInstance(); + manager.requestRecieveJob(scheduleCode.trim(), reqYYYYMMDD); + + + return "작업큐에 데이터가 추가되었습니다."; + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/sysinfo/RemoveSysinfoCommand.java b/src/com/eactive/eai/agent/sysinfo/RemoveSysinfoCommand.java new file mode 100644 index 0000000..288fec7 --- /dev/null +++ b/src/com/eactive/eai/agent/sysinfo/RemoveSysinfoCommand.java @@ -0,0 +1,62 @@ +package com.eactive.eai.agent.sysinfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.sysInfo.SysInfoManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경 +* 2. 처리 개요 : HolidayManager에 HolidayVO제거 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemoveSysinfoCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public RemoveSysinfoCommand(String name) { + super(name); + } + + /** + * 1. 기능 : HolidayManager에 HolidayVO제거 + * 2. 처리 개요 : HolidayManager에 HolidayVO제거 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String sysCd = (String) args; + SysInfoManager manager = SysInfoManager.getInstance(); + + manager.removeSysInfo(sysCd); + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/sysinfo/UpdateSysinfoCommand.java b/src/com/eactive/eai/agent/sysinfo/UpdateSysinfoCommand.java new file mode 100644 index 0000000..deacbe3 --- /dev/null +++ b/src/com/eactive/eai/agent/sysinfo/UpdateSysinfoCommand.java @@ -0,0 +1,64 @@ +package com.eactive.eai.agent.sysinfo; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.sysInfo.SysInfoManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경 +* 2. 처리 개요 : HolidayManager에 HolidayVO추가 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class UpdateSysinfoCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public UpdateSysinfoCommand(String name) { + super(name); + } + + /** + * 1. 기능 : HolidayManager에 HolidayVO추가 + * 2. 처리 개요 : HolidayManager에 HolidayVO추가 + * 3. 주의사항 + * + * @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우 + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String sysCd = (String) args; + + SysInfoManager manager = SysInfoManager.getInstance(); + manager.setSysInfo(sysCd); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception e) { + String msg = makeException("BECEAICAG002", e); + logger.error(msg, e); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/telegram/RemoveTelegramCommand.java b/src/com/eactive/eai/agent/telegram/RemoveTelegramCommand.java new file mode 100644 index 0000000..74a81f2 --- /dev/null +++ b/src/com/eactive/eai/agent/telegram/RemoveTelegramCommand.java @@ -0,0 +1,86 @@ +package com.eactive.eai.agent.telegram; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 전문을 삭제 +* 2. 처리 개요 : TelegramManager를 이용하여 입력된 전문 Key에 해당하는 HashMap의 객체를 삭제 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class RemoveTelegramCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : AddFlowRuleCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public RemoveTelegramCommand(String name) { + super(name); + } + + /** + * 1. 기능 : FlowRule 추가 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + TelegramManager telegramManager = TelegramManager.getInstance(); + + try + { + // 입력값(parameter가 없으면 에러를 발생한다. + if(args == null) throw new Exception("[RemoveFlowPhaseCommand] 입력 파라미터가 없습니다."); + + // 파라미터 확인 + if( !(args instanceof String) ) { + String rspErrorCode = "BECEAICAG001"; + String msg = makeException(rspErrorCode, null); + logger.error(msg); + throw new CommandException(msg); + } + + String telegramKey = StringUtil.nvlTrim((String)args); + + + // TelegramManager를 이용하여 새로운 Rule을 등록한다. + boolean result = telegramManager.removeTelegram(telegramKey); + + logger.debug("RemoveTelegram 이용한 전문 삭제 결과 : " + result); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/telegram/UpdateTelegramCommand.java b/src/com/eactive/eai/agent/telegram/UpdateTelegramCommand.java new file mode 100644 index 0000000..6aec153 --- /dev/null +++ b/src/com/eactive/eai/agent/telegram/UpdateTelegramCommand.java @@ -0,0 +1,87 @@ +package com.eactive.eai.agent.telegram; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.batch.telegram.TelegramVO; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 전문을 삭제 +* 2. 처리 개요 : TelegramManager를 이용하여 입력된 전문 Key에 해당하는 HashMap의 객체를 삭제 +* 3. 주의사항 +* +* @author +* @version v 1.0.0 +* @see 관련 기능을 참조 +* @since +*/ +public class UpdateTelegramCommand extends Command +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : AddFlowRuleCommand 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public UpdateTelegramCommand(String name) { + super(name); + } + + /** + * 1. 기능 : FlowRule 추가 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + * @return + * @exception CommandException + **/ + public Object execute() throws CommandException + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.info(this.name + " Agent 가 호출되었습니다."); + + TelegramManager telegramManager = TelegramManager.getInstance(); + + try + { + // 입력값(parameter가 없으면 에러를 발생한다. + if(args == null) throw new Exception("[UpdateTelegramCommand] 입력 파라미터가 없습니다."); + + // 파라미터 확인 + if( !(args instanceof String) ) { + String rspErrorCode = "BECEAICAG001"; + String msg = makeException(rspErrorCode, null); + logger.error(msg); + throw new CommandException(msg); + } + + String telegramKey = StringUtil.nvlTrim((String)args); + + + // TelegramManager를 이용하여 새로운 Rule을 등록한다. + TelegramVO result = telegramManager.updateTelegram(telegramKey); + + logger.debug("UpdateTelegramCommand 이용한 전문 수정 결과 : " + result.toString()); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + return "success"; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } +} diff --git a/src/com/eactive/eai/agent/transaction/AdditionReportCommand.java b/src/com/eactive/eai/agent/transaction/AdditionReportCommand.java new file mode 100644 index 0000000..f4a15cc --- /dev/null +++ b/src/com/eactive/eai/agent/transaction/AdditionReportCommand.java @@ -0,0 +1,46 @@ +package com.eactive.eai.agent.transaction; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.common.util.Logger; + +public class AdditionReportCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public AdditionReportCommand() { + super("AdditionReportCommand"); + } + + public Object execute() throws CommandException + { + logger.info(this.name + " Agent 가 호출되었습니다."); + + if ( args == null || !(args instanceof String) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String sendData = ((String)args).substring(4); + logger.debug(this.name + "- 받은 데이터 : \n["+sendData+"]"); + + String result = com.eactive.eai.batch.bokex.BOKEXAddTelegramManager.getInstance().doTelegram(sendData); + logger.debug(this.name + "- 되돌려 주는 데이터 : \n["+result+"]"); + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + + return "0000" + result; + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + + } + +} diff --git a/src/com/eactive/eai/agent/transaction/BatchJobPriorityCommand.java b/src/com/eactive/eai/agent/transaction/BatchJobPriorityCommand.java new file mode 100644 index 0000000..add6476 --- /dev/null +++ b/src/com/eactive/eai/agent/transaction/BatchJobPriorityCommand.java @@ -0,0 +1,87 @@ +package com.eactive.eai.agent.transaction; + +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityManager; +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityVO; +import com.eactive.eai.common.util.Logger; + +public class BatchJobPriorityCommand extends Command +{ + private static final long serialVersionUID = 1L; + + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + HashMap> resultMap = null; + + public BatchJobPriorityCommand() { + super("BatchJobPriorityCommand"); + } + + public Object execute() throws CommandException + { + logger.info(this.name + " Agent 가 호출되었습니다."); + + try{ + if( args instanceof String[]){//메모리 업데이트 + try{ + String[] params = (String[])args; + + ArrayList alist = null; + + if (params != null && params.length >= 4){ + HashMap> jobmap = BatchJobPriorityManager.getInstance().getPriorityDatas(); + + alist = jobmap.get(params[0]); + + if (alist != null && alist.size()>0){ + for (int i =0; iparamMap = (HashMap)args; + + String bjobDmndMsgID = (String)paramMap.get("bjobDmndMsgID"); + + BatchDoc batchDoc = BatchRunningJobManager.getInstance().getRunningDocument(bjobDmndMsgID); + + if (batchDoc == null){ + return bjobDmndMsgID+"에 해당하는 Batch Job이 없습니다."; + } + + batchDoc.setUserCancel(true); + ChannelSftp channelSftp = batchDoc.getSftpChannel(); + Object ioStream = batchDoc.getIOStream(); + if (channelSftp == null && ioStream == null){ + return "실행중인 sFTP 송수신이 없습니다."; + } + + if(channelSftp != null)channelSftp.quit(); + if(ioStream != null){ + if(ioStream instanceof InputStream)((InputStream)ioStream).close(); + else if(ioStream instanceof OutputStream)((OutputStream)ioStream).close(); + } + + } catch (Exception ex) { + String msg = makeException("RECEAIMCM002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + + return "전송종료를 요청했습니다."; + } + +} diff --git a/src/com/eactive/eai/agent/transaction/ProcessingFileStatusCommand.java b/src/com/eactive/eai/agent/transaction/ProcessingFileStatusCommand.java new file mode 100644 index 0000000..eaf9fa8 --- /dev/null +++ b/src/com/eactive/eai/agent/transaction/ProcessingFileStatusCommand.java @@ -0,0 +1,69 @@ +package com.eactive.eai.agent.transaction; + +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.util.Logger; + +public class ProcessingFileStatusCommand extends Command +{ + /** + * + */ + private static final long serialVersionUID = 1L; + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public ProcessingFileStatusCommand() { + super("ProcessingFileStatusCommand"); + } + + public Object execute() throws CommandException + { + logger.info(this.name + " Agent 가 호출되었습니다."); + + try { + ArrayList alist = getProcessingBatchJodStatus(); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + logger.info("###### 이 서버에서 진행중인 작업 건 수 (메모리서 조회) : "+ alist.size()); + return alist; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } + + private ArrayList getProcessingBatchJodStatus() throws Exception { + ArrayList retList = new ArrayList(); + + HashMap allDocs = BatchRunningJobManager.getInstance().getAllRunningDocuments(); + Object[] uuids = allDocs.keySet().toArray(); + + for (int i=0; i> alist = getProcessingBatchJodStatus(); + + logger.info(this.name + " Agent 가 성공적으로 완료되었습니다."); + logger.info("###### 이 서버에서 진행중인 작업 건 수 (메모리서 조회) : "+ alist.size()); + return alist; + + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } + + + + private List> getProcessingBatchJodStatus() throws Exception { + List> retList = new ArrayList>(); + + HashMap allDocs = BatchRunningJobManager.getInstance().getAllRunningDocuments(); + Object[] uuids = allDocs.keySet().toArray(); + + for (int i=0; i map = new HashMap(); + map.put( "Uuid" , batchDoc.getBatchMsg().getHeader().getUUID()); + map.put( "SubUuid" , batchDoc.getBatchMsg().getBody().getSubUUID()); + map.put( "ProcessCode" , batchDoc.getBatchMsg().getHeader().getProcessCode()); + map.put( "ProcessName" , batchDoc.getBatchMsg().getHeader().getProcessName()); + map.put( "OrganCode" , batchDoc.getBatchMsg().getHeader().getInstitutionCode()); + map.put( "OrganName" , batchDoc.getBatchMsg().getHeader().getInstitutionName()); + map.put( "ProcessType" , batchDoc.getBatchMsg().getHeader().getProcessType()); + map.put( "BatchStartTime" , batchDoc.getBatchMsg().getHeader().getBatchStartTime()); + map.put( "PhaseStartTime" , batchDoc.getBatchMsg().getBody().getPhaseStartTime()); + map.put( "FileName" , batchDoc.getBatchMsg().getHeader().getFileName()); + map.put( "TotalFileSize" , batchDoc.getBatchMsg().getHeader().getFileSize()); + map.put( "CurrFileSize" , batchDoc.getBatchMsg().getBody().getCurFileSize()); + int rate = (int)(100 * batchDoc.getBatchMsg().getBody().getCurFileSize() / batchDoc.getBatchMsg().getHeader().getFileSize()); + if ( rate > 0 && rate <= 100 ){ + map.put( "Rate" , rate); + }else{ + map.put( "Rate" , "-"); + } + retList.add(map); + } + return retList; + } + +} diff --git a/src/com/eactive/eai/agent/transaction/ReSendRSDataCommand.java b/src/com/eactive/eai/agent/transaction/ReSendRSDataCommand.java new file mode 100644 index 0000000..82f7211 --- /dev/null +++ b/src/com/eactive/eai/agent/transaction/ReSendRSDataCommand.java @@ -0,0 +1,124 @@ +package com.eactive.eai.agent.transaction; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.scheduler.JobFileTransferVO; +import com.eactive.eai.batch.scheduler.JobMasterLogVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.UUIDGenerator; + +public class ReSendRSDataCommand extends Command{ + + /** + * + */ + private static final long serialVersionUID = 1L; + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public ReSendRSDataCommand(String name) { + super(name); + } + + public Object execute() throws CommandException + { + logger.info(this.name +" 이 호출되었습니다."); + if ( args == null || !(args instanceof String[]) ) { + String msg = makeException("BECEAICAG001", null); + logger.error(msg); + throw new CommandException(msg); + } + + try { + String[] logKeys = (String[])args; + String argUUID = logKeys[0]; + String argSubUUID = logKeys[1]; + String argSndrcvFileName = logKeys[2]; + + SchedulerMessageManager manager = SchedulerMessageManager.getInstance(); + JobMasterLogVO vo = manager.getJobLogByKey(argUUID, argSubUUID); + JobFileTransferVO fvo = manager.getFileLogList(argUUID, argSubUUID, argSndrcvFileName); + + if (fvo == null ){ + logger.warn("fail.. 전송할 파일명이 설정되어 있지 않습니다. 파일명이 설정된 단계까지 실행되었는지 확인 필요합니다."); + return "fail.. 전송할 파일명이 설정되어 있지 않습니다. 파일명이 설정된 단계까지 실행되었는지 확인 필요합니다."; + }else { + SchedulerMessageVO scheduleInfo = SchedulerMessageManager.getInstance().getScheduleInfo(fvo.getBjobTranDstcdName(), vo.getProcessCode(), vo.getOrganCode()); + String strEndTime = scheduleInfo.getEndTime(); + String strStartTime = CalendarUtil.getCurrentTimeNoDash().substring(8,12); + + int endTime = Integer.parseInt(strEndTime); + int startTime = Integer.parseInt(strStartTime); + + if (startTime > endTime){ + strEndTime = "2359"; //하루의 마지막 시간으로 설정 + } + + String newUuid = UUIDGenerator.getUUID(); + + scheduleInfo.setUUID (argUUID);//로깅을 위해 새로운 uuid 할당한다. + scheduleInfo.setSubUUID (newUuid); + scheduleInfo.setFilePath (fvo.getFilePath()); + scheduleInfo.setFileName (fvo.getFileName()); + scheduleInfo.setRenamedFileName(fvo.getRenamedFileName()); + scheduleInfo.setHdrInfoName (fvo.getHdrInfoName()); + + scheduleInfo.setStartTime(DatetimeUtil.getCurrentDate() + strStartTime + "00" + "000" ); + scheduleInfo.setEndTime (DatetimeUtil.getCurrentDate() + strEndTime + "00" + "000" ); + + BatchDoc newBatchDoc = EAIBatchMsgManager.createBatchMsg(true); + newBatchDoc.getBatchMsg().getHeader().setBatchStartTime(CalendarUtil.getCurrentTimeNoDash()); + newBatchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + + //JOB QUEUE 테이블에 등록 + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(scheduleInfo); + logger.info("[요구송신 재전송을 위을 위해 배치 JOB QUEUE 테이블 INSERT 건수: "+ resultCnt); + + //DB로그를 위해서 조회정보를 batchDoc에 세팅 + newBatchDoc.getBatchMsg().getHeader().setUUID(argUUID); + newBatchDoc.getBatchMsg().getBody().setSubUUID(newUuid); + + newBatchDoc.getBatchMsg().getHeader().setScheduleSTime(scheduleInfo.getStartTime()); //전송 시작 시각 + newBatchDoc.getBatchMsg().getHeader().setScheduleETime(scheduleInfo.getEndTime()); + newBatchDoc.getBatchMsg().getHeader().setLayerCode(CommonKeys.LAYER_SCHEDULER); + newBatchDoc.getBatchMsg().getHeader().setProcessCode(vo.getProcessCode()); + newBatchDoc.getBatchMsg().getHeader().setFileName(fvo.getFileName()); + newBatchDoc.getBatchMsg().getHeader().setRenamedFileName(fvo.getRenamedFileName()); + newBatchDoc.getBatchMsg().getHeader().setHdrInfoName(fvo.getHdrInfoName()); + newBatchDoc.getBatchMsg().getHeader().setScheduleCode(vo.getScheduleCode()); + newBatchDoc.getBatchMsg().getHeader().setProcessType(vo.getProcessType()); + newBatchDoc.getBatchMsg().getHeader().setInstitutionCode(vo.getOrganCode()); + newBatchDoc.getBatchMsg().getHeader().setUserID(vo.getMsgSenderId()); + newBatchDoc.getBatchMsg().getHeader().setUserName(vo.getMsgSenderName()); + newBatchDoc.getBatchMsg().getHeader().setSystemConnCode(vo.getSystemConnCode()); + newBatchDoc.getBatchMsg().getHeader().setRemoteIP(vo.getRemoteServerIp()); + newBatchDoc.getBatchMsg().getHeader().setRuleCode(vo.getRuleCode()); + + + newBatchDoc.getBatchMsg().getBody().setWLIServerName(vo.getWeblogicName()); + newBatchDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); + newBatchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + newBatchDoc.getBatchMsg().getBody().setErrorCode(0); + newBatchDoc.getBatchMsg().getBody().setErrorMsg(""); + newBatchDoc.getBatchMsg().getBody().setRetryCount(scheduleInfo.getRecvFailCnt()); + + //요구송신 재처리에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (newBatchDoc); + } + + return "재전송을 위한 작업큐에 데이터가 추가되었습니다."; + } catch (Exception ex) { + String msg = makeException("BECEAICAG002", ex); + logger.error(msg, ex); + throw new CommandException(msg); + } + } + +} diff --git a/src/com/eactive/eai/agent/web/BatchJobPriorityMan.java b/src/com/eactive/eai/agent/web/BatchJobPriorityMan.java new file mode 100644 index 0000000..0f26ffa --- /dev/null +++ b/src/com/eactive/eai/agent/web/BatchJobPriorityMan.java @@ -0,0 +1,79 @@ +package com.eactive.eai.agent.web; + +import java.util.ArrayList; +import java.util.HashMap; + +import javax.servlet.RequestDispatcher; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityManager; +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityVO; +import com.eactive.eai.common.util.Logger; + +public class BatchJobPriorityMan extends HttpServlet +{ + + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * 1. 기능 : 요청으로 전달된 Command 실행 + * 2. 처리 개요 : 요청으로 전달된 Command 실행하고 실행된 결과를 ObjectOutStream을 통해 전송 + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + try { + logger.info("[BatchJobPriorityMan] Servlet starting ......."); + + String scr_name = request.getParameter("scr_name"); + + if ("UPDATE".equals(scr_name)){ + String key = request.getParameter("key"); + int index = Integer.parseInt(request.getParameter("index")); + + String m_bizCode[] = request.getParameterValues("bizCode"); + String m_dataCount[] = request.getParameterValues("dataCount"); + String m_isexe[] = request.getParameterValues("isexe"); + + BatchJobPriorityManager jobpmanager = BatchJobPriorityManager.getInstance(); + HashMap> jobmap = jobpmanager.getPriorityDatas(); + + ArrayList alist = jobmap.get(key); + + if (alist != null && alist.size()>0){ + for (int i =0; i batchNames = new ArrayList(); + for (int i=0; i organList = OutsideManager.getInstance().getOutsideInfo((String)batchCodes[i]); + if (organList.size()>0) { + OutsideVO osdvo = (OutsideVO)organList.get(0); + BatchTargetVO bvo = FlowControllerManager.getInstance().getBatchTargetInfo(osdvo.getBatchCode(), osdvo.getOsdCode()); + if (bvo == null) { + batchNames.add(""); + } else { + batchNames.add(bvo.getProcessName()); + } + } else { + batchNames.add(""); + } + } + response.getWriter().println("<%@ taglib uri='/WEB-INF/tld/c.tld' prefix='c'%>"); + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(""); + if (strBatch.equalsIgnoreCase("all")) { + for (int i=0; i< batchCodes.length; i++) { + String strBatchCode = (String)batchCodes[i]; + String strBatchName = (String)batchNames.get(i); + + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(" "); + PrintBatchSubDirectory(response, strOutside, strBatchName, strBatchCode); + } + + } else { + for (int i=0; i< batchCodes.length; i++) { + String strBatchCode = (String)batchCodes[i]; + String strBatchName = (String)batchNames.get(i); + if (strBatch.equalsIgnoreCase(strBatchCode)) { + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(" "); + PrintBatchSubDirectory(response, strOutside, strBatchName, strBatchCode); + break; + } + } + } + + response.getWriter().println("
"); + response.getWriter().println(" BATCH CODE "); + response.getWriter().println(" "); + response.getWriter().println( strBatchCode ); + response.getWriter().println(" "); + response.getWriter().println(" BATCH NAME "); + response.getWriter().println(" " ); + response.getWriter().println( strBatchName ); + response.getWriter().println("
"); + response.getWriter().println(" BATCH CODE "); + response.getWriter().println(" "); + response.getWriter().println( strBatchCode ); + response.getWriter().println(" "); + response.getWriter().println(" BATCH NAME "); + response.getWriter().println(" " ); + response.getWriter().println( strBatchName ); + response.getWriter().println("
"); + response.getWriter().println(""); + response.getWriter().println(sb.toString()); + } catch (Exception ex) { + logger.error( ex.getMessage(), ex); + response.setStatus(500); + try { + response.getWriter().println(ex.getMessage()); + throw ex; + } catch (Exception e) { + } + } + } + + private void PrintBatchSubDirectory(HttpServletResponse response, String strOsdCondition, String strBatchName, String strBatchCode) throws Exception + { + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(strBatchCode); + for (int i=0; i"); + response.getWriter().println(""); + response.getWriter().println(" 배치업무 "); + response.getWriter().println(" "); + response.getWriter().println( strBatchName+"["+strBatchCode+"]" ); + response.getWriter().println(" "); + response.getWriter().println(""); + response.getWriter().println(" 대외기관 "); + response.getWriter().println(" " ); + response.getWriter().println( osdvo.getOsdName()+"["+osdvo.getOsdCode()+"]" ); + response.getWriter().println(" "); + response.getWriter().println(" "); + PrintOsdSubDirectory(response, strBatchCode, osdvo.getOsdCode()); + } else { + if (strOsdCondition.equalsIgnoreCase(osdvo.getOsdCode())) { + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(" 배치업무 "); + response.getWriter().println(" "); + response.getWriter().println( strBatchName+"["+strBatchCode+"]" ); + response.getWriter().println(" "); + response.getWriter().println(""); + response.getWriter().println(" 대외기관 "); + response.getWriter().println(" " ); + response.getWriter().println( osdvo.getOsdName()+"["+osdvo.getOsdCode()+"]" ); + response.getWriter().println(" "); + response.getWriter().println(" "); + PrintOsdSubDirectory(response, strBatchCode, osdvo.getOsdCode()); + } + } + } + } + + private void PrintOsdSubDirectory(HttpServletResponse response, String strBatCd, String strOsdCd) throws Exception + { + StringBuffer sb = new StringBuffer(); + + sb.append(strBatCd); + sb.append("/"); + sb.append(strOsdCd); + + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println("요구송신용 디렉토리"); + response.getWriter().println(" "); + + PrintCheckResult(response, BatchDirUtil.getRequestArchDir()+"/"+sb.toString()); + PrintCheckResult(response, BatchDirUtil.getRequestErrorDir()+"/"+sb.toString()); +// PrintCheckResult(response, BatchDirUtil.getRequestRealDir()+"/"+sb.toString()); +// PrintCheckResult(response, BatchDirUtil.getRequestRootDir()+"/"+sb.toString()); + + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println("요구/응답수신용 디렉토리"); + response.getWriter().println(" "); + + PrintCheckResult(response, BatchDirUtil.getResponseArchDir()+"/"+sb.toString()); + PrintCheckResult(response, BatchDirUtil.getResponseErrorDir()+"/"+sb.toString()); + PrintCheckResult(response, BatchDirUtil.getResponseRealDir()+"/"+sb.toString()); + PrintCheckResult(response, BatchDirUtil.getResponseRootDir()+"/"+sb.toString()); + +// if (strGroupCondition.equals("") || strGroupCondition.equals("all")) { +// sb = new StringBuffer(); +// sb.append(strBatNm +"_"+ strBatCd); +// sb.append("/"); +// sb.append(strOsdNm +"_"+ strOsdCd); +// +// response.getWriter().println(""); +// response.getWriter().println(""); +// response.getWriter().println("응답송신용 디렉토리"); +// response.getWriter().println(" "); +// +// PrintCheckResult(response, BatchDirUtil.getResSendArchDir()+"/"+sb.toString()); +// PrintCheckResult(response, BatchDirUtil.getResSendRealDir()+"/"+sb.toString()); +// } + } + + private void PrintCheckResult(HttpServletResponse response, String strDir) throws Exception + { + File f = new File(strDir); + + response.getWriter().println(""); + response.getWriter().println(""); + response.getWriter().println(strDir); + response.getWriter().println(""); + + if (f.exists()) { + response.getWriter().println("EXIST"); + } else { + response.getWriter().println("NOT EXIST"); + } + response.getWriter().println(""); + response.getWriter().println(""); + } +} diff --git a/src/com/eactive/eai/agent/web/CheckLine.java b/src/com/eactive/eai/agent/web/CheckLine.java new file mode 100644 index 0000000..5b77d9e --- /dev/null +++ b/src/com/eactive/eai/agent/web/CheckLine.java @@ -0,0 +1,379 @@ +package com.eactive.eai.agent.web; + +import java.io.IOException; +import java.net.Socket; +import java.net.UnknownHostException; +import java.util.ArrayList; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.adapter.socket.outbound.OutboundSocketClient; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideLinkVO; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.UUIDGenerator; +import com.eactive.eai.inbound.ResponseHandler; + +/** + * 회선상태 체크 Agent + */ +public class CheckLine extends HttpServlet +{ + /** + * + */ + private static final long serialVersionUID = 1L; + public static final int ERROR_NO_ERROR = 0; + //BatchRunningJobManager 에서 UUID에 해당하는 소켓인스탄스를 찾을 수 없다. + public static final int ERROR_NO_SOCKET = 1; + public static final int ERROR_NO_PROCDATA = 2; + public static final int ERROR_NO_NEXTSTAGE = 3; + public static final int ERROR_TELEGRAM_COMPILE = 4; + public static final int ERROR_RECV_PRE_LENGTH = 5; + public static final int ERROR_RECV_ERROR = 6; + public static final int ERROR_TIMEOUT_OVER = 7; + public static final int ERROR_RECV_SHORT_LENGTH = 8; + public static final int ERROR_LENGTH_PARSE = 9; + public static final int ERROR_UNEXPECTED_TELEGRAM = 10; + public static final int ERROR_NO_CLASS_DEFINITION = 11; + public static final int ERROR_NO_TELEGRAM_ID = 12; + public static final int ERROR_WRITE_ERROR = 13; + public static final int ERROR_SEND_VALIDATION = 14; + public static final int ERROR_RECV_VALIDATION = 15; + public static final int ERROR_POST_EXECUTION = 16; + public static final int ERROR_EXECUTION = 17; + public static final int ERROR_ERR_TELEGRAM_META = 18; + public static final int ERROR_INFORMAL_ACTION = 19; + public static final int ERROR_READ_FILE = 20; + // 플로우 컴포넌트에서 송수신 중 비정형필드에 대한 처리데이터 길이를 구할 수 없다. + public static final int ERROR_INFORMAL_FIELD_LENGTH= 21; + // 소켓연결 중 소켓 포트정보가 없다. + public static final int ERROR_NO_SOCKET_PORT = 22; + // Outbound 소켓연결 중 연결 실패 + public static final int ERROR_FAIL_TO_CONNECT = 23; + + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + String errorMsg = ""; + private final String ruleID = "CH001"; + + /** + * 1. 기능 : 요청으로 전달된 Command 실행 + * 2. 처리 개요 : 요청으로 전달된 Command 실행하고 실행된 결과를 ObjectOutStream을 통해 전송 + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + try { + logger.info("[CheckLine] Servlet starting ......."); + String strProcessCodeCode = request.getParameter("processCode"); + String strOrganCode = request.getParameter("organCode"); + String strBizCode = request.getParameter("bizCode"); + String strIP = request.getParameter("organIP"); + String strPort = request.getParameter("organPort"); + int nPort = -1; + try { + nPort = Integer.parseInt(strPort); + } catch (Exception ex) { + nPort = -1; + } + response.setContentType("text/html;charset=euc-kr"); + + if (strOrganCode==null||strOrganCode.length()==0|| + strIP==null||strIP.length()==0||nPort==-1) { + logger.info("[CheckLine] ▷▷▷ URL format error !!!! "); + response.getWriter().println("[ERROR] URL FORMAT ERROR
"); + response.getWriter().println("-->URL PATTERN
"); + response.getWriter().println("
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/CheckLine?organCode=IL03&bizCode=0000300&organIP=172.17.61.71&organPort=41021   ▷▷▷회선체크 URL 형식
" ); + } else { + //BatchMsgDoc 생성 + BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(true); //true:초기화함 + + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER); + + batchMsgDoc = setBatchMessage(batchMsgDoc, strProcessCodeCode, strOrganCode, strBizCode, strIP, strPort) ; + if (batchMsgDoc == null) { + logger.info("[CheckLine] : BatchMsg is NULL!! >>" + this.errorMsg); + response.getWriter().println("[ERROR] " + this.errorMsg); + return; + } + + // OutboundSocketHandle처럼 소켓을 만들어서 BatchRunningJobManager 등록 해준다. + Socket socket=null; + + try { + socket=new Socket(strIP, nPort); + } catch (UnknownHostException e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIASC001", new String[] {strIP, Integer.toString(nPort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다. + } catch(IOException e){ + StringBuffer sb = new StringBuffer(); + sb.append("[ERROR] IP[" + strIP +"]"); + sb.append("PORT[" + strPort + "] socket connection error"); + sb.append("[" + e.getLocalizedMessage() + "]"); + response.getWriter().println(sb.toString()); +// String errMsg = + ExceptionUtil.getErrorCode(e, "BECEAIASC002", new String[] {strIP, Integer.toString(nPort)}); + + logger.error( e.getMessage(), e); + return; + } + + String strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID(); + OutboundSocketClient socketClient = new OutboundSocketClient(socket); + BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, socketClient, batchMsgDoc); + + logger.info("[CheckLine] : FlowController JPD call & start "); + String startTime = CalendarUtil.getCurrentTimeNoDash(); + batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime(startTime); + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(startTime); + LogUtil.setStartLog(batchMsgDoc); + ResponseHandler handler = new ResponseHandler(); + batchMsgDoc = handler.execute(batchMsgDoc); + logger.info("[CheckLine] : FlowController JPD call & end "); + + // BatchRunningJobManager 에서 제거한다. + BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + try { + socket.close(); + } catch (UnknownHostException e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIASC001", new String[] {strIP, Integer.toString(nPort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다. + } catch(IOException e){ + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIASC002", new String[] {strIP, Integer.toString(nPort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), I/O Exception이 발생했습니다. + } + + // 결과를 확인한다. + int nErrorCode = batchMsgDoc.getBatchMsg().getBody().getErrorCode(); + if (nErrorCode == ERROR_NO_ERROR) { + // 성공 ... + String strResponseCode = batchMsgDoc.getBatchMsg().getBody().getLastResCode(); + if (strResponseCode.equalsIgnoreCase("000")) { + StringBuffer sb = new StringBuffer(); + sb.append("[SUCCESS] IP[" + strIP +"]"); + sb.append("PORT[" + strPort + "] connection test ok!!!"); + response.getWriter().println(sb.toString()); + } else { + StringBuffer sb = new StringBuffer(); + sb.append("[ERROR] IP[" + strIP +"]"); + sb.append("PORT[" + strPort + "] Receive Error response Code"); + sb.append("[" + strResponseCode + "]"); + response.getWriter().println(sb.toString()); + } + } else { + // 실패 ... + StringBuffer sb = new StringBuffer(); + sb.append("[ERROR]"); + sb.append("ERROR CODE [" + nErrorCode + "]" + this.getErrorMsg(nErrorCode)); + response.getWriter().println(sb.toString()); + } + } + } catch (Exception ex) { + logger.error( ex.getMessage(), ex); + response.setStatus(500); + try { + response.getWriter().println(ex.getMessage()); + throw ex; + } catch (Exception e) { + // IGNORE + } + } + } + + public BatchDoc setBatchMessage(BatchDoc batchMsgDoc, String strBatchCode, String strOsdCode, String strBizCode, String strTargetIP, String strTargetPort) + { + //---------------------------------------------------------------------------------------- + ArrayList osd_array = OutsideManager.getInstance().getOutsideInfo(strBatchCode); + if (osd_array == null) { + this.errorMsg = "Not found outside institution information list of Batch Job Code["+strBatchCode+"]"; + logger.debug(this.errorMsg); + return null; + } + int i = 0; + for (i=0; i link_Array = OutsideManager.getInstance().getOutsideLinkInfo(strOsdCode); + if (link_Array == null) { + this.errorMsg = "Not found outside link list(TSEAIBJ05) of institution code in OutsideManager ["+strOsdCode+"]"; + logger.debug(this.errorMsg); + return null; + } + int idx = 0; + OutsideLinkVO linkVO = null; + for (idx = 0; idx< link_Array.size(); idx++) { + linkVO = (OutsideLinkVO) link_Array.get(idx); + if (linkVO.getLinkIP().equalsIgnoreCase(strTargetIP) && linkVO.getLinkPort().trim().equalsIgnoreCase(strTargetPort)) { + break; + } + } + if (idx == link_Array.size()) { + this.errorMsg = "Not found outside link information by mapping IP["+strTargetIP+"] Port["+strTargetPort+"]"; + logger.debug(this.errorMsg); + return null; + } + String uuid = UUIDGenerator.getUUID(); + batchMsgDoc.getBatchMsg().getHeader().setUUID(uuid); + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(ovo.getBatchCode()); + batchMsgDoc.getBatchMsg().getHeader().setProcessName(ovo.getBatchName()); + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_REQUEST_SEND); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(ovo.getOsdCode()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(ovo.getOsdName()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(""); + batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(""); + batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(""); + batchMsgDoc.getBatchMsg().getHeader().setFilePath(""); + batchMsgDoc.getBatchMsg().getHeader().setFileName(""); + batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(""); + batchMsgDoc.getBatchMsg().getHeader().setJobCode(""); + batchMsgDoc.getBatchMsg().getHeader().setBizCode(strBizCode); + batchMsgDoc.getBatchMsg().getHeader().setFlowCode(this.ruleID); + batchMsgDoc.getBatchMsg().getHeader().setRuleCode(this.ruleID); + // RULE 정보 조회 + RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(this.ruleID); + batchMsgDoc.getBatchMsg().getHeader().setRuleDesc(vo.getDesc()); + batchMsgDoc.getBatchMsg().getHeader().setLayerCode(CommonKeys.LAYER_FLOW_CONTROLLER); + batchMsgDoc.getBatchMsg().getHeader().setTRXID(""); + batchMsgDoc.getBatchMsg().getHeader().setRequestResponse(""); + batchMsgDoc.getBatchMsg().getHeader().setSendRecv(""); + batchMsgDoc.getBatchMsg().getHeader().setUserName(""); +// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP"); + batchMsgDoc.getBatchMsg().getHeader().setUserID(linkVO.getUserID()); // 실제 링크가 할당되면 알수 있다. + batchMsgDoc.getBatchMsg().getHeader().setUserPassword(linkVO.getPwd()); // 실제 링크가 할당되면 알수 있다. + batchMsgDoc.getBatchMsg().getHeader().setBlockSize(ovo.getBlkSize()); + batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(ovo.getSequenceSize()); + batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(linkVO.getLinkIP()); // 실제 링크가 할당되면 알수 있다. + batchMsgDoc.getBatchMsg().getHeader().setPort(linkVO.getLinkPort()); // 실제 링크가 할당되면 알수 있다. + batchMsgDoc.getBatchMsg().getHeader().setBatchStartTime(CalendarUtil.getCurrentTimeNoDash()); + + batchMsgDoc.getBatchMsg().getBody().setSubUUID(uuid); + batchMsgDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_FLOW_PHASE_CK); + batchMsgDoc.getBatchMsg().getBody().setWLIServerName(System.getProperty("weblogic.Name")); + + batchMsgDoc.getBatchMsg().getBody().setActionTag(""); + batchMsgDoc.getBatchMsg().getBody().setRecallTag(""); + + batchMsgDoc.getBatchMsg().getBody().setBlockNum(0); // 현 운영 블럭넘버 + batchMsgDoc.getBatchMsg().getBody().setSeqNum(0); // 현 운영 시퀀스 넘버 + + batchMsgDoc.getBatchMsg().getBody().setLastPhaseCode(""); + batchMsgDoc.getBatchMsg().getBody().setNextPhaseCode(""); + batchMsgDoc.getBatchMsg().getBody().setLastPhaseStartTime(""); + batchMsgDoc.getBatchMsg().getBody().setLastPhaseEndTime(""); + batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime(""); + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(""); + batchMsgDoc.getBatchMsg().getBody().setLastPhaseType(""); + batchMsgDoc.getBatchMsg().getBody().setPhaseType(""); + batchMsgDoc.getBatchMsg().getBody().setNextPhaseType(""); + batchMsgDoc.getBatchMsg().getBody().setNodeCount(0); + batchMsgDoc.getBatchMsg().getBody().setPortNo(""); + batchMsgDoc.getBatchMsg().getBody().setSndMsgCode(""); + batchMsgDoc.getBatchMsg().getBody().setRcvMsgCode(""); + batchMsgDoc.getBatchMsg().getBody().setTimeoutInterval(""); + batchMsgDoc.getBatchMsg().getBody().setRetryCount(0); + + batchMsgDoc.getBatchMsg().getPhaseinfo().setRuleCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseType (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setFlowClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (-1); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue (""); + + //스케쥴러 Processing 단계 시작시간 설정 + batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + return batchMsgDoc; + } + + public String getErrorMsg(int nErrorCode) { + switch (nErrorCode) { + case ERROR_NO_ERROR: + return "NO_ERROR"; + case ERROR_NO_SOCKET : + return "NO SOCKET"; + case ERROR_NO_PROCDATA : + return "NO PROCDATA"; + case ERROR_NO_NEXTSTAGE : + return "NO NEXT STAGE"; + case ERROR_TELEGRAM_COMPILE : + return "TELEGRAM COMPILE"; + case ERROR_RECV_PRE_LENGTH : + return "RECV PRE LENGTH"; + case ERROR_RECV_ERROR : + return "RECV ERROR"; + case ERROR_TIMEOUT_OVER : + return "TIMEOUT OVER"; + case ERROR_RECV_SHORT_LENGTH : + return "RECV SHORT LENGTH"; + case ERROR_LENGTH_PARSE : + return "LENGTH PARSE ERROR"; + case ERROR_UNEXPECTED_TELEGRAM : + return "UNEXPECTED TEELGRAM"; + case ERROR_NO_CLASS_DEFINITION : + return "NO CLASS DEFINITION"; + case ERROR_NO_TELEGRAM_ID : + return "NO TELEGRAM ID"; + case ERROR_WRITE_ERROR : + return "WRITE ERROR"; + case ERROR_SEND_VALIDATION : + return "SEND VALIDATION ERROR"; + case ERROR_RECV_VALIDATION : + return "RECV VALIDATION ERROR"; + case ERROR_POST_EXECUTION : + return "doPostExecution ERROR"; + case ERROR_EXECUTION : + return "doExecute ERROR"; + case ERROR_ERR_TELEGRAM_META : + return "ERROR TELEGRAM META DATA"; + case ERROR_INFORMAL_ACTION : + return "ERROR IN INFORMAL FIELD ACTION"; + case ERROR_READ_FILE : + return "READ FILE ERROR"; + case ERROR_INFORMAL_FIELD_LENGTH : // 플로우 컴포넌트에서 송수신 중 비정형필드에 대한 처리데이터 길이를 구할 수 없다. + return "ERROR IN INFORMAL FIELD LENGTH"; + case ERROR_NO_SOCKET_PORT : // 소켓연결 중 소켓 포트정보가 없다. + return "SOCKET PORT ERROR"; + case ERROR_FAIL_TO_CONNECT : // Outbound 소켓연결 중 연결 실패 + return "SOCKET CONNECT ERROR"; + default: + return "UNKNOWN ERROR CODE["+nErrorCode+"]"; + } + } +} diff --git a/src/com/eactive/eai/agent/web/CheckServerSocket.java b/src/com/eactive/eai/agent/web/CheckServerSocket.java new file mode 100644 index 0000000..6e876e6 --- /dev/null +++ b/src/com/eactive/eai/agent/web/CheckServerSocket.java @@ -0,0 +1,103 @@ +package com.eactive.eai.agent.web; + +import java.util.ArrayList; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.adapter.AdapterDAO; +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.util.Logger; + +public class CheckServerSocket extends HttpServlet +{ + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + /** + * 1. 기능 : 요청으로 전달된 Command 실행 + * 2. 처리 개요 : 요청으로 전달된 Command 실행하고 실행된 결과를 ObjectOutStream을 통해 전송 + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + try { + boolean bAllOK = true; + logger.info("[CheckServerSocket] Servlet starting ......."); + response.setContentType("text/html;charset=euc-kr"); + + StringBuffer sb = new StringBuffer(); + + ArrayList groups = null; + AdapterDAO dao = null; + try { + dao = (AdapterDAO)DAOFactory.newInstance().create(AdapterDAO.class); + groups = dao.getAllAdapterGroups(); + } catch(DAOException e) { + response.getWriter().println("[ERROR] AdapterDAO.getAllDapterGroups 조회시 장애 발생 ... "); + return; + } + logger.info("[CheckServerSocket] Queried AdapterGroup count = " + groups.size()); + AdapterGroupVO gvo = null; +// AdapterVO avo = null; + for(int i=0;i all = null; + try { + all = dao.getAllAdapters(gvo.getName()); + for(int j=0;j> "+vo.getName()+"]"); + sb.append("[ HOST : " + vo.getBatchServerIP() + " PORT : " + vo.getBatchServerPortNo() + " ]"); + + SocketService ss = SocketAdapterManager.getInstance().getSocketService(vo.getAdapterGroupName(), vo.getName()); + if (ss == null) { + sb.append("[ SOCKET SERVICE : NOT EXISTS !!! ]"); + bAllOK = false; + } else { + if (ss.isActive()) { + sb.append("[ SOCKET SERVICE : ACTIVE !!! ]"); + } else { + sb.append("[ SOCKET SERVICE : IN ACTIVE !!!]"); + bAllOK = false; + } + } + sb.append("
\n"); + } + + } catch(DAOException e) { + response.getWriter().println("[ERROR] AdapterDAO.getAllDapterGroups 조회시 장애 발생 ... "); + return; + } + } + if (bAllOK) { + response.getWriter().println("[SUCCESS]
"); + } else { + response.getWriter().println("[ERROR]
"); + } + response.getWriter().println(sb.toString()); + } catch (Exception ex) { + logger.error( ex.getMessage(), ex); + response.setStatus(500); + try { + response.getWriter().println(ex.getMessage()); + throw ex; + } catch (Exception e) { + // IGNORE + } + } + } +} diff --git a/src/com/eactive/eai/agent/web/DBRefreshAgent.java b/src/com/eactive/eai/agent/web/DBRefreshAgent.java new file mode 100644 index 0000000..8094aac --- /dev/null +++ b/src/com/eactive/eai/agent/web/DBRefreshAgent.java @@ -0,0 +1,321 @@ +package com.eactive.eai.agent.web; + +import java.util.ArrayList; +import java.util.HashMap; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.adapter.AdapterManager; +import com.eactive.eai.batch.code.CodeMessageManager; +import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoManager; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + + +/** + * LifeCycle에 의해 로드된 데이터를 원격에서 Refresh 하기 위해 제공하는 서블릿 + * + * WebBrowser 를 통해 호출가능하도록 WEB.XML 에 URL 등록함. + */ +public class DBRefreshAgent extends HttpServlet +{ + /** + * + */ + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * 1. 기능 : 요청으로 전달된 Command 실행 + * 2. 처리 개요 : 요청으로 전달된 Command 실행하고 실행된 결과를 ObjectOutStream을 통해 전송 + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void doPost(HttpServletRequest request, HttpServletResponse response) { + try { + logger.info("[DBRefreshAgent] Servlet starting ......."); + + String strTarget = request.getParameter("Target"); + if (strTarget == null) strTarget = ""; + + response.setContentType("text/html;charset=euc-kr"); + if (strTarget.equalsIgnoreCase("ALL")) { + // 일단 당분간 테스트를 위해 여기서 REFRESH 하자 + logger.info("[DBResfreshAgent] ▷▷▷ PhaseInfoManager data reload "); + PhaseInfoManager.getInstance().stop(); + PhaseInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR02 table reloaded !!!

"); + + logger.info("[DBResfreshAgent] ▷▷▷ NodeInfoManager data reload "); + NodeInfoManager.getInstance().stop(); + NodeInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR03 table reloaded !!!

"); + + logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload "); + RuleInfoManager.getInstance().stop(); + RuleInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR04 table reloaded !!!

"); + + logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload "); + TelegramInfoManager.getInstance().stop(); + TelegramInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR05 table reloaded !!!

"); + + logger.info("[DBRefreshAgentAgent] 대외기관 정보 리로딩 한다."); + OutsideManager.getInstance().stop(); + OutsideManager.getInstance().start(); + AdapterManager.getInstance().stop(); + AdapterManager.getInstance().start(); + FlowControllerManager.getInstance().stop(); + FlowControllerManager.getInstance().start(); + response.getWriter().println("TSEAIBJ06, TSEAIBJ05 Reloading OK !!!
"); + + logger.info("[DBRefreshAgentAgent] 업무분류 코드 및 서브 디렉토리 정보 ."); + DirInfoManager.getInstance().stop(); + DirInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBJ01 Reloading OK !!!
"); + + logger.info("[DBRefreshAgentAgent] Property Table Reloading ."); + PropManager.getInstance().stop(); + PropManager.getInstance().start(); + response.getWriter().println("TSEAIBP01, TSEAIBP02 (Property table) Reloading OK !!!
"); + + logger.info("[DBRefreshAgentAgent] CodeMessage Table Reloading ."); + CodeMessageManager.getInstance().stop(); + CodeMessageManager.getInstance().start(); + response.getWriter().println("TSEAIBP05 CodeMessage table Reloading OK !!!
"); + + logger.info("[DBRefreshAgentAgent] Telegram Table Reloading ."); + TelegramManager.getInstance().stop(); + TelegramManager.getInstance().start(); + response.getWriter().println("TSEAIBM02 Telegram table Reloading OK !!!
"); + + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 정보 [TSEAIBR04]
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayRuleInfo(response); + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 구성 노드 (STAGE) [TSEAIBR03] 정보
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayNodeInfo(response); + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 구성노드 변환 규칙 [TSEAIBR02]
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayPhaseInfo(response); + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 노드(단계)별 처리 담당 클래스 리스트 [TSEAIBR05]
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayTelegramInfo(response); + response.getWriter().println("================================================================================================
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBR02")) { + logger.info("[DBResfreshAgent] ▷▷▷ PhaseInfoManager data reload "); + PhaseInfoManager.getInstance().stop(); + PhaseInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR02 table reloaded !!!

"); + + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 구성노드 변환 규칙
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayPhaseInfo(response); + response.getWriter().println("================================================================================================
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBR03")) { + logger.info("[DBResfreshAgent] ▷▷▷ NodeInfoManager data reload "); + NodeInfoManager.getInstance().stop(); + NodeInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR03 table reloaded !!!

"); + + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 구성 노드 (STAGE) 정보
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayNodeInfo(response); + response.getWriter().println("================================================================================================
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBR04")) { + logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload "); + RuleInfoManager.getInstance().stop(); + RuleInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR04 table reloaded !!!

"); + + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 정보
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayRuleInfo(response); + response.getWriter().println("================================================================================================
"); + + } + else if (strTarget.equalsIgnoreCase("TSEAIBR05")) { + logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload "); + TelegramInfoManager.getInstance().stop(); + TelegramInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBR05 table reloaded !!!

"); + + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 노드(단계)별 처리 담당 클래스 리스트
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayTelegramInfo(response); + response.getWriter().println("================================================================================================
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBJ06")) { + logger.info("[DBRefreshAgentAgent] 대외기관 정보 리로딩 한다."); + OutsideManager.getInstance().stop(); + OutsideManager.getInstance().start(); + AdapterManager.getInstance().stop(); + //socket이 realead되기를 기다리기 위해 2초 sleep + Thread.sleep(2*1000); + + AdapterManager.getInstance().start(); + FlowControllerManager.getInstance().stop(); + FlowControllerManager.getInstance().start(); + response.getWriter().println("TSEAIBJ06, TSEAIBJ05 Reloading OK !!!
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBJ01")) { + logger.info("[DBRefreshAgentAgent] 업무분류 코드 및 서브 디렉토리 정보 ."); + DirInfoManager.getInstance().stop(); + DirInfoManager.getInstance().start(); + response.getWriter().println("TSEAIBJ01 Reloading OK !!!
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBP01")) { + logger.info("[DBRefreshAgentAgent] Property Table Reloading ."); + PropManager.getInstance().stop(); + PropManager.getInstance().start(); + response.getWriter().println("TSEAIBP01, TSEAIBP02 (Property table) Reloading OK !!!
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBP05")) { + logger.info("[DBRefreshAgentAgent] CodeMessage Table Reloading ."); + CodeMessageManager.getInstance().stop(); + CodeMessageManager.getInstance().start(); + response.getWriter().println("TSEAIBP05 CodeMessage table Reloading OK !!!
"); + } + else if (strTarget.equalsIgnoreCase("TSEAIBM02")) { + logger.info("[DBRefreshAgentAgent] Telegram Table Reloading ."); + TelegramManager.getInstance().stop(); + TelegramManager.getInstance().start(); + response.getWriter().println("TSEAIBM02 Telegram table Reloading OK !!!
"); + } + else if (strTarget.equalsIgnoreCase("VIEW")) { + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 정보 [TSEAIBR04]
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayRuleInfo(response); + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 구성 노드 (STAGE) [TSEAIBR03] 정보
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayNodeInfo(response); + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 구성노드 변환 규칙 [TSEAIBR02]
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayPhaseInfo(response); + response.getWriter().println("================================================================================================
"); + response.getWriter().println("▷▷▷ 룰 노드(단계)별 처리 담당 클래스 리스트 [TSEAIBR05]
"); + response.getWriter().println("-------------------------------------------------------------------------------------------------
"); + this.displayTelegramInfo(response); + response.getWriter().println("================================================================================================
"); + }else if (strTarget.equalsIgnoreCase("TSEAIBE02")) { + logger.info("[DBRefreshAgentAgent] EventScheduler Holiday Table Reloading ."); + HolidayManager.getInstance().stop(); + HolidayManager.getInstance().start(); + response.getWriter().println("TSEAIBE02 EventScheduler Holiday table Reloading OK !!!
"); + } else { + logger.info("[DBResfreshAgent] ▷▷▷ unknown target !!!! >>"+strTarget+"<<
"); + response.getWriter().println("Unknown Target. No process done !!! ▷▷▷ CHECK YOUR URL ▷▷▷
"); + response.getWriter().println("▷▷▷ URL PATTERN ▷▷▷
"); + response.getWriter().println("▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=ALL ▷▷▷룰관련 모든 매니저 DB 리로딩
" ); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=VIEW ▷▷▷룰관련 모든 매니저 DB Display
" ); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR02 ▷▷▷PHASE 변환룰 정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR03 ▷▷▷PHASE 정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR04 ▷▷▷RULE 정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR05 ▷▷▷텔레그램 매핑정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBJ06 ▷▷▷대외기관정보 (TSEAIBJ06, TSEAIBJ05 둘다 리프레쉬)
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBJ01 ▷▷▷파일이름기반 거래분류 테이블
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBP01 ▷▷▷프라퍼티테이블 정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBP05 ▷▷▷코드메세지 테이블 정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBM02 ▷▷▷Telegram 테이블 정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBE02 ▷▷▷이벤트 스케줄러 휴일관리 테이블 정보
"); + response.getWriter().println("http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBE03 ▷▷▷이벤트 스케줄러 테이블 정보
"); + } + } catch (Exception ex) { + logger.error( ex.getMessage(), ex); + response.setStatus(500); + try { + response.getWriter().println(ex.getMessage()); + throw ex; + } catch (Exception e) { + // IGNORE + } + } + } + + public void displayPhaseInfo(HttpServletResponse response) { + try { + HashMap> hm = PhaseInfoManager.getInstance().getAllData(); + Object[] objs = hm.keySet().toArray(); + for (int i=0; i al = hm.get(rulecode); + response.getWriter().println("RULE ["+rulecode+"] phase(stage) change rule record count >> " + al.size() + "
"); + } + } catch(Exception ex) { + } + } + + public void displayNodeInfo(HttpServletResponse response) { + try { + HashMap> hm = NodeInfoManager.getInstance().getAllData(); + Object[] objs = hm.keySet().toArray(); + for (int i=0; i al = hm.get(rulecode); + response.getWriter().println("RULE ["+rulecode+"] distinct node(stage) count >> " + al.size()+ "
"); + } + } catch(Exception ex) { + } + } + + public void displayRuleInfo(HttpServletResponse response) { + try { + HashMap hm = RuleInfoManager.getInstance().getAllData(); + Object[] objs = hm.keySet().toArray(); + for (int i=0; i>> " + vo.getDesc()+ "
"); + } + } catch(Exception ex) { + } + } + + public void displayTelegramInfo(HttpServletResponse response) { + try { + HashMap hm = TelegramInfoManager.getInstance().getAllData(); + Object[] objs = hm.keySet().toArray(); + for (int i=0; i"); + } + } catch(Exception ex) { + } + } + +} diff --git a/src/com/eactive/eai/agent/web/FepFileReceive.java b/src/com/eactive/eai/agent/web/FepFileReceive.java new file mode 100644 index 0000000..c411502 --- /dev/null +++ b/src/com/eactive/eai/agent/web/FepFileReceive.java @@ -0,0 +1,185 @@ +package com.eactive.eai.agent.web; + +import static com.eactive.eai.agent.web.FepFileSupport.ENCODING; +import static com.eactive.eai.agent.web.FepFileSupport.FAIL; +import static com.eactive.eai.agent.web.FepFileSupport.SUCCESS; +import static com.eactive.eai.agent.web.FepFileSupport.getResMsg; + +import java.io.PrintWriter; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class FepFileReceive extends HttpServlet{ + + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * 1. 기능 : Eai Bat Call + * 2. 처리 개요 : 요청 메세지를 받아서 처리 후 메세지 리턴. + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + try { + logger.info("Servlet starting ......."); + + String msg = request.getParameter("msg"); + logger.debug("msg["+msg+"]"); + response.setCharacterEncoding(ENCODING); + PrintWriter writer = response.getWriter(); + + if ( msg == null || msg.getBytes().length < 110 ){ + writer.print(getResMsg(FAIL, "파라메터값(msg)이 전달되지 않았습니다. length = " + ((msg == null) ? 0 : msg.getBytes().length))); + return; + } + if ( !msg.endsWith("@@") ){ + writer.print(getResMsg(FAIL, "종료문자열이 \"@@\" 이어야 합니다.")); + return; + } + getFileEventInfo(msg); + writer.print(getResMsg(SUCCESS, "수신 요청했습니다.")); + + } catch (Exception ex) { + logger.debug(ex.getMessage(), ex); + try { + response.getWriter().print(getResMsg(FAIL, "E:" + ex.getMessage())); + throw ex; + } catch (Exception e) { + } + } + } + + /** + * 요구 수신을 처리한다. + * @param message 요청 받은 메시지 + * @throws Exception + */ + private void getFileEventInfo(String message) throws Exception + { + // 수신한 파일 정보 + logger.info("[Recv File Event] ========================================================================="); + logger.info("[Recv File Event] ▶▶▶▶▶▶▶▶▶▶ Local 수신요청 FILE EVENT 발생 !! ◀◀◀◀◀◀◀◀◀◀"); + logger.info("[Recv File Event] ※ 요청 메시지 : [" + message +"]"); + logger.info("[Recv File Event] ========================================================================="); + + String processCode = message.substring(0, 5); + String institutionCode = message.substring(5, 9); + + logger.info("processCode = " + processCode); + logger.info("institutionCode = " + institutionCode); + + //거래구분 코드 설정 + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(processCode, institutionCode); + if ( organInfo == null ){ + throw new Exception("미등록 업무구분/기관코드:" + processCode + "/" + institutionCode); + } + + String institutionName = organInfo.getOsdName(); + String processName = organInfo.getBatchName(); + String bizCode = message.substring(9, 19).trim(); + String fileName = message.substring(19, message.length() - 2).trim(); + + logger.info("[Recv File Event] -------------------------------------------------------------------------"); + logger.info("[Recv File Event] ■ File Event 파싱 정보"); + logger.info("[Recv File Event] - 업무구분명 : [" + processName +"] (업무구분코드: "+ processCode +")"); + logger.info("[Recv File Event] - 대외기관명 : [" + institutionName +"] (대외기관코드: "+ institutionCode +")"); + logger.info("[Recv File Event] - 거래구분코드: [" + bizCode +"]"); + logger.info("[Recv File Event] - 수신파일명 : [" + fileName +"]"); + logger.info("[Recv File Event] -------------------------------------------------------------------------"); + + String remotePath = null; + if (fileName.contains("/")) { + int position = fileName.lastIndexOf("/"); + remotePath = fileName.substring(0, position); + fileName = fileName.substring(position + 1); + } + + /* + * FileEvent가 SchedulerProcess로 전달할 기본 EAIBatchMsg를 생성한다. + * FileEventListener가 입력가능한 값들은 EAIBatchMsg의 항목 중 다음과 같다. + * - UUID + * - Layer 구분 코드 (한시적) + * - ProcessCode: 수신한 서브디렉토리와 동일 + * - FileName : 송수신 원 파일명 + * - FilePath : 파일이 실재 존재하는 디렉토리 + * - RenamedFileName : 저장후 이름이 변경된 파일명 + */ + // BatchMsgDoc 생성 + BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(false); //UUID 생성, false:초기화안함 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_FILE_EVENT, CommonKeys.SUB_LAYER_FILE_EVENT); // layer, flowPahse, 시작시간 설정 + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(processCode); // 업무코드 + batchMsgDoc.getBatchMsg().getHeader().setProcessName(processName); // 업무명 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_REQUEST_RECEIVE); // 업무유형 (요구송신 설정) + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(institutionCode); // 대외기관코드 + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(institutionName); // 대외기관명 + batchMsgDoc.getBatchMsg().getHeader().setFileName(fileName); // 원 파일명 + batchMsgDoc.getBatchMsg().getHeader().setBizCode(bizCode); // 거래구분코드 + batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(message); // 체크파일 이름 + SchedulerMessageVO info = SchedulerMessageManager.getInstance().getRecvScheduleInfo(bizCode, processCode, institutionCode); + if ( info == null ){ + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC016", new String[] {processCode, institutionCode, bizCode}); + throw new Exception(errMsg); //해당 정보에 대한 스케쥴 정보가 존재하지 않습니다. (업무코드: {1}, 대외기관코드: {2}, 거래구분코드: {3}) + } + + info.setFileName(fileName); + //1. 요구수신 스케쥴러 단계 DB로그를 위한 BatchMsg 객체 생성 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); // layer, flowPahse, 시작시간 설정 + + //2. 요구수신 디렉토리 설정 (수신_Real/업무구분/대외기관/..) + //요구수신 기준 디렉토리 --> 배치업무유형코드(ProcessCode) 와 대외기관코드 (InstitutionCode) 로 계산. + String strPathName = BatchDirUtil.getResponseRealDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + + StringBuffer sb = new StringBuffer(); + sb.append(processCode); + sb.append("/"); + sb.append(institutionCode); + strPathName = strPathName + sb.toString(); + info.setFilePath(strPathName); + + //3. UUID 설정 및 스케쥴 송수신 시각 설정 + info.setUUID (batchMsgDoc.getBatchMsg().getHeader().getUUID()); + info.setSubUUID (batchMsgDoc.getBatchMsg().getBody().getSubUUID()); + info.setStartTime(DatetimeUtil.getCurrentDate() + "000000000"); + info.setEndTime (DatetimeUtil.getCurrentDate() + "235900000"); + info.setHdrInfoName(message); + + //4. Job_Queue 테이블에 등록 + logger.info("[요구수신 스케쥴러] ========================================================================="); + logger.info("[요구수신 스케쥴러] ■ 요구수신 스케쥴 정보를 Job_Queue 테이블에 추가......"); + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(info); + logger.info("[요구수신 스케쥴러] ==> 배치 Job_Queue 테이블 INSERT 건수: "+ resultCnt); + logger.info("[요구수신 스케쥴러] ========================================================================="); + + // 단계 종료시간을 추가한다. + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + // 요구송신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (batchMsgDoc); + logger.info("[Recv File Event] ※ Event 파일명 : [" + fileName +"]"); + + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/web/FepFileSend.java b/src/com/eactive/eai/agent/web/FepFileSend.java new file mode 100644 index 0000000..e2cc977 --- /dev/null +++ b/src/com/eactive/eai/agent/web/FepFileSend.java @@ -0,0 +1,225 @@ +package com.eactive.eai.agent.web; + +import static com.eactive.eai.agent.web.FepFileSupport.ENCODING; +import static com.eactive.eai.agent.web.FepFileSupport.FAIL; +import static com.eactive.eai.agent.web.FepFileSupport.SUCCESS; +import static com.eactive.eai.agent.web.FepFileSupport.getResMsg; + +import java.io.File; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class FepFileSend extends HttpServlet { + + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + + /** + * 1. 기능 : Eai Bat Call + * 2. 처리 개요 : 요청 메세지를 받아서 처리 후 메세지 리턴. + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + try { + logger.info("Servlet starting ......."); + + String msg = request.getParameter("msg"); + logger.debug("msg["+msg+"]"); + response.setCharacterEncoding(ENCODING); + + if ( msg == null || msg.getBytes().length <= 100 ){ + response.getWriter().print(getResMsg(FAIL, "파라메터값(msg)이 전달되지 않았습니다. length = " + ((msg == null) ? 0 : msg.getBytes().length))); + return; + } + if ( !msg.endsWith("@@") ){ + response.getWriter().print(getResMsg(FAIL, "종료문자열이 \"@@\" 이어야 합니다.")); + return; + } + + getFileEventInfo(msg); + response.getWriter().print(getResMsg(SUCCESS, "송신 요청했습니다.")); + + } catch (Exception ex) { + logger.debug(ex.getMessage(), ex); + response.setStatus(500); + try { + response.getWriter().println(getResMsg(FAIL, ex.getMessage())); + throw ex; + } catch (Exception e) { + } + } + } + + /** + * 요구 송신을 처리한다. + * @param message 요청 받은 메시지 + * @throws Exception + */ + private void getFileEventInfo(String message) throws Exception + { + // 송신한 파일 정보 + logger.info("[Send File Event] ========================================================================="); + logger.info("[Send File Event] ▶▶▶▶▶▶▶▶▶▶ Local 송신요청 FILE EVENT 발생 !! ◀◀◀◀◀◀◀◀◀◀"); + logger.info("[Send File Event] ※ 요청 메시지 : [" + message +"]"); + logger.info("[Send File Event] ========================================================================="); + + String processCode = message.substring(0, 5); + String institutionCode = message.substring(5, 9); + + logger.info("processCode = " + processCode); + logger.info("institutionCode = " + institutionCode); + + //거래구분 코드 설정 + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(processCode, institutionCode); + if ( organInfo == null ){ + throw new Exception("미등록 업무구분/기관코드:" + processCode + "/" + institutionCode); + } + + String institutionName = organInfo.getOsdName(); + String processName = organInfo.getBatchName(); + String bizCode = message.substring(9, 19).trim(); + String fileName = message.substring(19, message.length() - 2).trim(); + + logger.info("[Send File Event] -------------------------------------------------------------------------"); + logger.info("[Send File Event] ■ File Event 파싱 정보"); + logger.info("[Send File Event] - 업무구분명 : [" + processName +"] (업무구분코드: "+ processCode +")"); + logger.info("[Send File Event] - 대외기관명 : [" + institutionName +"] (대외기관코드: "+ institutionCode +")"); + logger.info("[Send File Event] - 거래구분코드: [" + bizCode +"]"); + logger.info("[Send File Event] - 송신파일명 : [" + fileName +"]"); + if (fileName.contains("/")) { + int position = fileName.lastIndexOf("/"); + fileName = fileName.substring(position + 1); + logger.info("[Send File Event] - 송신파일명2 : [" + fileName +"]"); + } + + logger.info("[Send File Event] -------------------------------------------------------------------------"); + + /* 저장할 디렉토리 및 파일정보 + * sourceDir : 파일을 읽어올 최상위 디렉토리 + * targetDir : 파일을 저장할 디렉토리 + * + * 현재는 FileEvent에 의해서 옮겨지는 Arch디렉토리가 읽어 올 디렉토리가 된다. (sourceDir) + * Arch 디렉토리에 있는 파일을 읽어서 Arch디렉토리 밑에 업무코드명과 동일하게 디렉토리를 만들고 저장한다. + */ + String targetDir = BatchDirUtil.getRequestArchDir() +"/"+ processCode +"/"+ institutionCode ; + String localDir = BatchDirUtil.getRequestRootDir() +"/"+ processCode +"/"+ institutionCode ; + /* + * FileEvent가 SchedulerProcess로 전달할 기본 EAIBatchMsg를 생성한다. + * FileEventListener가 입력가능한 값들은 EAIBatchMsg의 항목 중 다음과 같다. + * - UUID + * - Layer 구분 코드 (한시적) + * - ProcessCode: 송신한 서브디렉토리와 동일 + * - FileName : 송송신 원 파일명 + * - FilePath : 파일이 실재 존재하는 디렉토리 + * - RenamedFileName : 저장후 이름이 변경된 파일명 + */ + // BatchMsgDoc 생성 + BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(false); //UUID 생성, false:초기화안함 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_FILE_EVENT, CommonKeys.SUB_LAYER_FILE_EVENT); // layer, flowPahse, 시작시간 설정 + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(processCode); // 업무코드 + batchMsgDoc.getBatchMsg().getHeader().setProcessName(processName); // 업무명 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_REQUEST_RECEIVE); // 업무유형 (요구송신 설정) + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(institutionCode); // 대외기관코드 + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(institutionName); // 대외기관명 + batchMsgDoc.getBatchMsg().getHeader().setFileName(fileName); // 원 파일명 + batchMsgDoc.getBatchMsg().getHeader().setBizCode(bizCode); // 거래구분코드 + batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(message); // 거래구분코드 + batchMsgDoc.getBatchMsg().getHeader().setFilePath(targetDir); // 파일이 실재 존재하는 디렉토리 + batchMsgDoc.getBatchMsg().getHeader().setFileErrorPath(targetDir); // 장애발생시 실파일이 이동할 디렉토리를 지정한다. + + moveFile(batchMsgDoc, localDir, fileName, targetDir); + + SchedulerMessageVO info = SchedulerMessageManager.getInstance().getScheduleInfo(bizCode, processCode, institutionCode); + if ( info == null ){ + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC016", new String[] {processCode, institutionCode, bizCode}); + throw new Exception(errMsg); //해당 정보에 대한 스케쥴 정보가 존재하지 않습니다. (업무코드: {1}, 대외기관코드: {2}, 거래구분코드: {3}) + } + + info.setFileName(fileName); + //1. 요구송신 스케쥴러 단계 DB로그를 위한 BatchMsg 객체 생성 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); // layer, flowPahse, 시작시간 설정 + + //2. 요구송신 디렉토리 설정 (송신_Real/업무구분/대외기관/..) + //요구송신 기준 디렉토리 --> 배치업무유형코드(ProcessCode) 와 대외기관코드 (InstitutionCode) 로 계산. + String strPathName = BatchDirUtil.getRequestArchDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + + StringBuffer sb = new StringBuffer(); + sb.append(processCode); + sb.append("/"); + sb.append(institutionCode); + strPathName = strPathName + sb.toString(); + info.setFilePath(strPathName); + + //3. UUID 설정 및 스케쥴 송송신 시각 설정 + info.setUUID (batchMsgDoc.getBatchMsg().getHeader().getUUID()); + info.setSubUUID (batchMsgDoc.getBatchMsg().getBody().getSubUUID()); + info.setStartTime(DatetimeUtil.getCurrentDate() + "000000000"); + info.setEndTime (DatetimeUtil.getCurrentDate() + "235900000"); + info.setHdrInfoName(message); + info.setRenamedFileName(batchMsgDoc.getBatchMsg().getHeader().getRenamedFileName()); + + //4. Job_Queue 테이블에 등록 + logger.info("[요구송신 스케쥴러] ========================================================================="); + logger.info("[요구송신 스케쥴러] ■ 요구송신 스케쥴 정보를 Job_Queue 테이블에 추가......"); + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(info); + logger.info("[요구송신 스케쥴러] ==> 배치 Job_Queue 테이블 INSERT 건수: "+ resultCnt); + logger.info("[요구송신 스케쥴러] ========================================================================="); + + // 단계 종료시간을 추가한다. + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + // 요구송신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (batchMsgDoc); + logger.info("[Send File Event] ※ Event 파일명 : [" + fileName +"]"); + + } + + private void moveFile(BatchDoc batchMsgDoc, String dirPath, String fileName, String targetDir) throws Exception + { + String renamedFileName = fileName + "_" + CalendarUtil.getCurrentTimeNoDash(); + File realFile = new File(dirPath +"/"+ fileName); + File archFile = new File(targetDir +"/"+ renamedFileName); + + //Root 디렉토리에서 Arch 디렉토리로 파일 이동 + logger.info("[Send File Event] -------------------------------------------------------------------------"); + logger.info("[Send File Event] ■ 요구송신 파일 이동 (송신_Real -> 송신_Arch)"); + logger.info("[Send File Event] - Real 디렉토리: ["+ dirPath +"/"+ fileName +"] (exists: "+ realFile.exists() +")"); + logger.info("[Send File Event] - Arch 디렉토리: ["+ targetDir +"/"+ renamedFileName +"] (exists: "+ archFile.exists() +")"); + logger.info("[Send File Event] - 변경된 파일명: " + renamedFileName); + logger.info("[Send File Event] -------------------------------------------------------------------------"); + + boolean isSuccessMoveFile = FileUtil.copyTransferFile(realFile, archFile, true); + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIIFE002", new String[] {realFile.getAbsolutePath(), archFile.getAbsolutePath()}); + throw new Exception(errMsg); //요구송신 데이터파일을 송신_Real 디렉토리({1})에서 송신_Arch 디렉토리({2})로 이동시 실패하였습니다. + } + batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(renamedFileName); //변경된 파일명 설정 + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/web/FepFileSupport.java b/src/com/eactive/eai/agent/web/FepFileSupport.java new file mode 100644 index 0000000..8a3535e --- /dev/null +++ b/src/com/eactive/eai/agent/web/FepFileSupport.java @@ -0,0 +1,44 @@ +package com.eactive.eai.agent.web; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.doc.Header; + +public class FepFileSupport { + /** encoding */ + public static final String ENCODING = "MS949"; + /** 파일 송신 상태 검사 */ + public static final String SUCCESS = "SUCCESS"; + /** 파일 요구 수신 */ + public static final String FAIL = "FAIL"; + + /** + * HTTP 요청에 대한 응답 + * @param responseCode 성공 여부 + * @param responseMessage 메시지 + * @return HTTP 요청 응답 전문 + */ + public static String getResMsg(String responseCode, String responseMessage) { + String outStr = String.format("%-10s%s@@", responseCode, CommonLib.stringFormat(responseMessage, false, ' ', 100)); + return outStr; + } + + /** + * 파일 송수신 후 결과 통보 + * @param sendOrReceive 송수신 구분. S: 송신, R: 수신 + * @param resultCode 성공 여부 + * @param batchDoc + * @param remoteFilename 송수신 파일 이름 + * @param ListFileName 수신할 List 파일 이름 + * @param ListFileYn 수신시 List 파일 존재 여부. Y/N + * @return 파일 송수신 결과 통보 전문 + */ + public static String getNotifyMessage(String sendOrReceive, boolean resultCode, BatchDoc batchDoc, String listFileName, String ListFileYn, int fileCount, String remoteFilename) { + String result = resultCode ? SUCCESS : FAIL; + Header header = batchDoc.getBatchMsg().getHeader(); + String outStr = String.format("%s%-10s%5s%4s%-10s%-100s%010d%-100s%1s@@", sendOrReceive, result, + header.getProcessCode(), header.getInstitutionCode(), header.getBizCode(), + remoteFilename, fileCount, listFileName, ListFileYn); + return outStr; + } +} diff --git a/src/com/eactive/eai/agent/web/FepReqRecvFile.java b/src/com/eactive/eai/agent/web/FepReqRecvFile.java new file mode 100644 index 0000000..fe8f24f --- /dev/null +++ b/src/com/eactive/eai/agent/web/FepReqRecvFile.java @@ -0,0 +1,200 @@ +package com.eactive.eai.agent.web; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class FepReqRecvFile extends HttpServlet{ + + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * 1. 기능 : Eai Bat Call + * 2. 처리 개요 : 요청 메세지를 받아서 처리 후 메세지 리턴. + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + try { + logger.info("Servlet starting ......."); + + String msg = request.getParameter("msg"); + logger.debug("msg["+msg+"]"); + response.setCharacterEncoding("EUC-KR"); + + if ( msg == null || msg.getBytes().length < 140 ){ + response.setCharacterEncoding("EUC-KR"); + response.getWriter().print(getResMsg(false, "E:메시지 값이 전달되지 않았습니다.")); + return; + } + if ( !msg.endsWith("@@") ){ + response.setCharacterEncoding("EUC-KR"); + response.getWriter().print(getResMsg(false, "E:종료문자열이 \"@@\" 이어야 합니다.")); + return; + } + + String trx_id = msg.substring(0, 19).trim(); + logger.debug("trx_id["+trx_id+"]"); + String fileName = msg.substring(38, 138).trim(); + logger.debug("fileName["+fileName+"]"); + + if ( !trx_id.equals("FEP_REQ_RECV") ){ + response.setCharacterEncoding("EUC-KR"); + response.getWriter().print(getResMsg(false, "E:요청 시작 문자열이 \"FEP_REQ_RECV\" 이어야 합니다.")); + return; + } + getFileEventInfo(fileName); + response.setCharacterEncoding("EUC-KR"); + response.getWriter().print(getResMsg(true, fileName)); + + } catch (Exception ex) { + logger.debug(ex.getMessage(), ex); + try { + response.getWriter().print(getResMsg(false, "E:" + ex.getMessage())); + throw ex; + } catch (Exception e) { + } + } + } + private String getResMsg( boolean flag, String msg){ + String sFlag = "1"; + if ( flag ) sFlag = "0"; + String outStr = "FEP_REQ_RECV " + + DatetimeUtil.getCurrentDate() + + "0000000000" + sFlag + CommonLib.stringFormat(msg, false, ' ', 100) + "@@"; + return outStr; + + } + + private void getFileEventInfo(String reqFileName) throws Exception + { + // 수신한 파일 정보 + logger.info("[Req Recv File Event] ========================================================================="); + logger.info("[Req Recv File Event] ▶▶▶▶▶▶▶▶▶▶ Local 수신요청 FILE EVENT 발생 !! ◀◀◀◀◀◀◀◀◀◀"); + logger.info("[Req Recv File Event] ※ Event 파일명 : [" + reqFileName +"]"); + logger.info("[Req Recv File Event] ========================================================================="); + + String processCode = reqFileName.substring(0, 5); + String institutionCode = reqFileName.substring(6, 10); + + logger.info("processCode = " + processCode); + + logger.info("institutionCode = " + institutionCode); + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(processCode, institutionCode); + if ( organInfo == null ){ + throw new Exception("미등록 업무구분/기관코드:" + processCode + "/" + institutionCode); + } + String institutionName = organInfo.getOsdName(); + String processName = organInfo.getBatchName(); + bizCodeStartIndex = organInfo.getBizCdStartIdx(); + bizCodeEndIndex = organInfo.getBizCdEndIdx(); + logger.info("processName = " + processName); + + String fileName = reqFileName.substring(11); + + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + logger.info("[Req Recv File Event] -------------------------------------------------------------------------"); + logger.info("[Req Recv File Event] ■ File Event 파싱 정보"); + logger.info("[Req Recv File Event] - 업무구분명 : [" + processName +"] (업무구분코드: "+ processCode +")"); + logger.info("[Req Recv File Event] - 대외기관명 : [" + institutionName +"] (대외기관코드: "+ institutionCode +")"); + logger.info("[Req Recv File Event] - 수신파일명 : [" + fileName +"]"); + logger.info("[Req Recv File Event] - 거래구분코드: [" + bizCode +"]"); + logger.info("[Req Recv File Event] -------------------------------------------------------------------------"); + + + /* + * FileEvent가 SchedulerProcess로 전달할 기본 EAIBatchMsg를 생성한다. + * FileEventListener가 입력가능한 값들은 EAIBatchMsg의 항목 중 다음과 같다. + * - UUID + * - Layer 구분 코드 (한시적) + * - ProcessCode: 수신한 서브디렉토리와 동일 + * - FileName : 송수신 원 파일명 + * - FilePath : 파일이 실재 존재하는 디렉토리 + * - RenamedFileName : 저장후 이름이 변경된 파일명 + */ + // BatchMsgDoc 생성 + BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(false); //UUID 생성, false:초기화안함 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_FILE_EVENT, CommonKeys.SUB_LAYER_FILE_EVENT); // layer, flowPahse, 시작시간 설정 + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(processCode); // 업무코드 + batchMsgDoc.getBatchMsg().getHeader().setProcessName(processName); // 업무명 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_REQUEST_RECEIVE); // 업무유형 (요구송신 설정) + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(institutionCode); // 대외기관코드 + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(institutionName); // 대외기관명 + batchMsgDoc.getBatchMsg().getHeader().setFileName(fileName); // 원 파일명 + batchMsgDoc.getBatchMsg().getHeader().setBizCode(bizCode); // 거래구분코드 + SchedulerMessageVO info = SchedulerMessageManager.getInstance().getRecvScheduleInfo(bizCode, processCode, institutionCode); + if ( info == null ){ + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC016", new String[] {processCode, institutionCode, bizCode}); + throw new Exception(errMsg); //해당 정보에 대한 스케쥴 정보가 존재하지 않습니다. (업무코드: {1}, 대외기관코드: {2}, 거래구분코드: {3}) + } + + info.setFileName(fileName); + //1. 요구수신 스케쥴러 단계 DB로그를 위한 BatchMsg 객체 생성 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); // layer, flowPahse, 시작시간 설정 + + //2. 요구수신 디렉토리 설정 (수신_Real/업무구분/대외기관/..) + //요구수신 기준 디렉토리 --> 배치업무유형코드(ProcessCode) 와 대외기관코드 (InstitutionCode) 로 계산. + String strPathName = BatchDirUtil.getResponseRealDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + + + StringBuffer sb = new StringBuffer(); + sb.append(processCode); + sb.append("/"); + sb.append(institutionCode); + strPathName = strPathName + sb.toString(); + info.setFilePath(strPathName); + + + //3. UUID 설정 및 스케쥴 송수신 시각 설정 + info.setUUID (batchMsgDoc.getBatchMsg().getHeader().getUUID()); + info.setSubUUID (batchMsgDoc.getBatchMsg().getBody().getSubUUID()); + info.setStartTime(DatetimeUtil.getCurrentDate() + "000000000"); + info.setEndTime (DatetimeUtil.getCurrentDate() + "235900000"); + + //4. Job_Queue 테이블에 등록 + logger.info("[요구수신 스케쥴러] ========================================================================="); + logger.info("[요구수신 스케쥴러] ■ 요구수신 스케쥴 정보를 Job_Queue 테이블에 추가......"); + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(info); + logger.info("[요구수신 스케쥴러] ==> 배치 Job_Queue 테이블 INSERT 건수: "+ resultCnt); + logger.info("[요구수신 스케쥴러] ========================================================================="); + + // 단계 종료시간을 추가한다. + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + // 요구송신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (batchMsgDoc); + logger.info("[Req Recv File Event] ※ Event 파일명 : [" + fileName +"]"); + + } + +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/web/FepSendFile.java b/src/com/eactive/eai/agent/web/FepSendFile.java new file mode 100644 index 0000000..80ca836 --- /dev/null +++ b/src/com/eactive/eai/agent/web/FepSendFile.java @@ -0,0 +1,64 @@ +package com.eactive.eai.agent.web; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.inbound.remote.RemoteTransfer; +import com.eactive.eai.inbound.remote.RemoteTransferLogKeys; + +public class FepSendFile extends HttpServlet{ + + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * 1. 기능 : Eai Bat Call + * 2. 처리 개요 : 요청 메세지를 받아서 처리 후 메세지 리턴. + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return + * @exception + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + try { + logger.info("Servlet starting ......."); + + String fileName = request.getParameter("msg"); +// logger.debug("[FepSendFile]msg-->" + fileName); +// String sysCd = msg.substring(0, 5); +// String fileName = msg.substring(5); +// logger.debug("sysCd["+sysCd+"]"); + logger.debug("fileName["+fileName+"]"); + + if ( fileName == null || fileName.getBytes().length <= 11 ){ + response.setCharacterEncoding("EUC-KR"); + response.getWriter().print("E:파라메터값(msg)이 전달되지 않았습니다."); + return; + } + +// String procCode = fileName.substring(0, 5); +// String instCode = fileName.substring(6, 10); + RemoteTransfer transfer = new RemoteTransfer(); + String rtnmsg = transfer.recvFile( fileName, RemoteTransferLogKeys.START_BY_API, RemoteTransferLogKeys.STARTER_SYSTEM); + + + String outStr = new String(rtnmsg.getBytes(),"EUC-KR"); + logger.debug("outStr["+outStr+"]"); + response.setCharacterEncoding("EUC-KR"); + response.getWriter().print(outStr); + + } catch (Exception ex) { + logger.debug(ex.getMessage(), ex); + response.setStatus(500); + try { + response.getWriter().println(ex.getMessage()); + throw ex; + } catch (Exception e) { + } + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/web/FrontFilter.java b/src/com/eactive/eai/agent/web/FrontFilter.java new file mode 100644 index 0000000..cb4eba4 --- /dev/null +++ b/src/com/eactive/eai/agent/web/FrontFilter.java @@ -0,0 +1,103 @@ +package com.eactive.eai.agent.web; + +import java.io.IOException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + +public class FrontFilter implements Filter +{ + public static final String PROP_GROUP = "FrontFilter"; + public static final String PROP_KEY1 = "SERVER_LIST"; + public static final String PROP_KEY2 = "CLIENT_LIST"; + + public void init(FilterConfig config) throws ServletException{ + + } + + public void destroy(){ + + } + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException{ + try { + HttpServletRequest request = (HttpServletRequest)req; + HttpServletResponse response = (HttpServletResponse)res; + PropManager manager = PropManager.getInstance(); + String serverList = manager.getProperty(PROP_GROUP,PROP_KEY1); + String clientList = manager.getProperty(PROP_GROUP,PROP_KEY2); + if(serverList==null) { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.warn("[FrontFilter] Cannot configure the "+PROP_GROUP+"."+PROP_KEY1+" property."); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Cannot configure the "+PROP_GROUP+"."+PROP_KEY1+" property."); + return; + } + + if(clientList == null) clientList = ""; + + String[] serverIpList = serverList.split(","); + String[] clientIpList = clientList.split(","); + + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + String remoteAddr = request.getRemoteAddr(); + if( isAllowedIP(serverIpList, remoteAddr) ) { + if(logger.isDebugEnabled()) { + logger.debug("FrontFilter] HTTP Access. server IP - " + remoteAddr); + } + } + else if( isAllowedIP(clientIpList, remoteAddr) ) { + if(logger.isDebugEnabled()) { + logger.debug("FrontFilter] HTTP Access. client IP - " + remoteAddr); + } + } + else { + if(logger.isWarnEnabled()) { + logger.warn("FrontFilter] Invalid Access. - " + remoteAddr); + } + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid Access."); + return; + } + chain.doFilter(req,res); + } catch(Exception e) { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.error("FrontFilter] Error - " + e.getMessage(), e); + throw new ServletException(e.getMessage()); + + } + } + + private boolean isAllowedIP(String[] ipList, String remoteIp) { + + if(ipList == null || ipList.length == 0) { + return false; + } + + for( String allow : ipList ) { + if (allow.indexOf('*') == -1) { + if (allow.equals(remoteIp)) { + return true; + } + } else { + String allowRegexp = allow.replaceAll("\\*", "[0-9]+").trim(); + Matcher matcher = Pattern.compile(allowRegexp, Pattern.CASE_INSENSITIVE).matcher(remoteIp); + if (matcher.matches()) { + return true; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/agent/web/ImgJobPriorityAgent.java b/src/com/eactive/eai/agent/web/ImgJobPriorityAgent.java new file mode 100644 index 0000000..296cf5b --- /dev/null +++ b/src/com/eactive/eai/agent/web/ImgJobPriorityAgent.java @@ -0,0 +1,177 @@ +//package com.eactive.eai.agent.web; +// +//import java.io.BufferedReader; +//import java.io.InputStreamReader; +//import java.io.PrintWriter; +//import java.net.URL; +//import java.net.URLConnection; +//import java.util.ArrayList; +//import java.util.HashMap; +// +//import javax.servlet.http.HttpServlet; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityManager; +//import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityVO; +//import com.eactive.eai.common.property.PropManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +// +//public class ImgJobPriorityAgent extends HttpServlet +//{ +// +// private static final long serialVersionUID = 1L; +// Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT); +// +// /** +// * 1. 기능 : 요청으로 전달된 Command 실행 +// * 2. 처리 개요 : 요청으로 전달된 Command 실행하고 실행된 결과를 ObjectOutStream을 통해 전송 +// * 3. 주의사항 +// * +// * @param request HttpServletRequest +// * @param response HttpServletResponse +// * @return +// * @exception +// **/ +// public void service(HttpServletRequest request, HttpServletResponse response) { +// String propName = "TelegramInfo{BIIMG_KFTS}"; +// String rurl = "http://172.17.167.92/mf/Pres_Logic/mf1/jsp_mf1eaitranconfirm/evnEaiTranConfirm_Response.jsp"; +// String rvalue = "rvalue=0"; +// boolean isNormal = true; +// +// try { +// logger.info("[ImgJobPriorityAgent] Servlet starting ......."); +// +// try{ +// PropManager pmanager = PropManager.getInstance(); +// rurl = pmanager.getProperty(propName, "result.url"); +// }catch (Exception e){ +// e.printStackTrace(); +// isNormal = false; +// rvalue="rvalue=-1"; +// logger.error("[ImgJobPriorityAgent] url property 를 가져오는데 실패했습니다. 프로퍼티가 설정되어있는지 확인요함. - propName : ["+propName+"], url을 기본값 ["+rurl+"]로 설정합니다."); +// } +// +// logger.info("[ImgJobPriorityAgent] rurl : ["+rurl+"]"); +// +// String list = request.getParameter("list"); +// String strsendCount = request.getParameter("scount"); +// String strtotalCount = request.getParameter("tcount"); +// String[] lists = list.split(","); +// +// if (list == null || list.length() <=0 || lists.length != 3){ +// logger.error("ImgJobPriorityAgent ] 우선순위 목록 데이터가 비정상적입니다. - ["+list+"]"); +// isNormal = false; +// rvalue="rvalue=-1"; +// } +// +// int sendCount = 0; +// int totalCount = 0; +// +// try{ +// sendCount = Integer.parseInt(strsendCount); +// totalCount = Integer.parseInt(strtotalCount); +// +// if (sendCount < 0 || totalCount <0 || sendCount > totalCount){ +// logger.error("ImgJobPriorityAgent ] count value faile.. [sendCount/totalCount] - ["+sendCount+"/"+totalCount+"]"); +// isNormal = false; +// rvalue="rvalue=-1"; +// } +// +// }catch (Exception ne){ +// ne.printStackTrace(); +// logger.error("ImgJobPriorityAgent ] count value faile.. [sendCount/totalCount] - ["+sendCount+"/"+totalCount+"]"); +// isNormal = false; +// rvalue="rvalue=-1"; +// } +// +// +// if (isNormal){ +// BatchJobPriorityManager jobpmanager = BatchJobPriorityManager.getInstance(); +// HashMap jobmap = jobpmanager.getPriorityDatas(); +// +// ArrayList alist = (ArrayList)jobmap.get(lists[0]); +// +// if (alist != null && alist.size()>0){ +// +// BatchJobPriorityVO vo1 = (BatchJobPriorityVO)alist.get(1); //두번째 가져오기.. +// +// if (vo1.isExecuted() && vo1.getDataCount() < totalCount ){ +// logger.error("ImgJobPriorityAgent ] 어음 이미지 데이터가 대외기관으로 전송중이므로 메모리 정보 업데이트가 불가합니다."); +// isNormal = false; +// rvalue="rvalue=-2"; +// } +// }else { +// ArrayList palist = new ArrayList(); +// +// for (int plistIndex = 0; plistIndex < lists.length; plistIndex++){ +// +// BatchJobPriorityVO jpvo = new BatchJobPriorityVO(); +// +// //기본정보를 설정한다. +// jpvo.setBizCode(lists[plistIndex]); +// jpvo.setOsdCd("KFTS"); +// jpvo.setOsdName("결제원송신"); +// jpvo.setProcessCd("BIIMG"); +// jpvo.setProcessName("어음이미지"); +// +// +// if (plistIndex == 0){ +// jpvo.setExecutedFlag(true); +// jpvo.setDataCount(1); //첫번째는 시작 파일로 파일 수는 1개임. +// } +// if (plistIndex == 1){ +// jpvo.setExecutedFlag(true); +// jpvo.setDataCount(sendCount); //데이터파일은 파라메터값으로 설정. +// jpvo.setDataCountInfo(totalCount); +// } +// +// palist.add(plistIndex, jpvo); +// +// } +// jobpmanager.addJobPriorityData(lists[0], palist); +// +// logger.info("[ImgJobPriorityAgent] 메모리정보 업데이트했습니다. - ["+list+"/"+strsendCount+"/"+strtotalCount+"]"); +// } +// } +// +// URL u = new URL(rurl); +// URLConnection conn = u.openConnection(); +// +// if (conn == null) { +// logger.error("[ImgJobPriorityAgent] HttpURLConnection 을 생성할 수 없습니다. (URL : "+ rurl +")"); +// } +// +// conn.setDoInput(true); +// conn.setDoOutput(true); +// conn.setUseCaches(false); +// +// +// PrintWriter pout = new PrintWriter(conn.getOutputStream()); +// pout.println(rvalue); +// pout.close(); +// +// try{ +// +// BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); +// +// }catch (Exception ce){ +// logger.error("[ImgJobPriorityAgent] 처리결과를 전송할 connection이 올바른지 확인이 필요합니다. - "+ce.getMessage()); +// } +// +// } catch (Exception ex) { +// ex.printStackTrace(); +// response.setStatus(500); +// +// try { +// response.getWriter().println(ex.getMessage()); +// throw ex; +// } catch (Exception e) { +// // IGNORE +// } +// } +// } +// +//} diff --git a/src/com/eactive/eai/agent/web/WebAgent.java b/src/com/eactive/eai/agent/web/WebAgent.java new file mode 100644 index 0000000..9950999 --- /dev/null +++ b/src/com/eactive/eai/agent/web/WebAgent.java @@ -0,0 +1,74 @@ +package com.eactive.eai.agent.web; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.command.CommandException; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class WebAgent extends HttpServlet +{ + private static final long serialVersionUID = 1L; + ObjectInputStream is = null; + + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + protected Object execute(Command command) throws CommandException { + try{ + return command.execute(); + + }catch (CommandException ce){ + logger.error( ce.getMessage(), ce); + throw ce; + }catch (Exception e){ + logger.error( e.getMessage(), e); + String errorMsg = ExceptionUtil.getErrorCode(e, "BECEAICAG010"); + if (logger.isError()) logger.error(errorMsg); + throw new CommandException(errorMsg); + } + } + + public void service(HttpServletRequest request, HttpServletResponse response) { + + try { + + ObjectInputStream is = new ObjectInputStream(request.getInputStream()); + ObjectOutputStream os = new ObjectOutputStream(response.getOutputStream()); + + Command command = (Command)is.readObject(); + Object obj; + try{ + obj = execute(command); + }catch (Exception e){ + obj = e.getMessage(); + }finally{ + is.close(); + os.close(); + } + + os.writeObject((Serializable)obj); + + is.close(); + os.close(); + + } catch (Exception e) { + logger.error( e.getMessage(), e); + response.setStatus(500); + try { + response.getWriter().println(e.getMessage()); + throw e; + } catch (Exception ex) { + logger.error( ex.getMessage(), ex); + } + + } + + } +} diff --git a/src/com/eactive/eai/batch/bokex/BOKEXAddTelegramManager.java b/src/com/eactive/eai/batch/bokex/BOKEXAddTelegramManager.java new file mode 100644 index 0000000..4ec8b70 --- /dev/null +++ b/src/com/eactive/eai/batch/bokex/BOKEXAddTelegramManager.java @@ -0,0 +1,284 @@ +package com.eactive.eai.batch.bokex; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashSet; + +import com.eactive.eai.batch.flowController.DemandTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageDAO; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class BOKEXAddTelegramManager { + + private static BOKEXAddTelegramManager instance = new BOKEXAddTelegramManager(); + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public static BOKEXAddTelegramManager getInstance() { + return instance; + } + private Socket socket = null; + private DataInputStream din = null; + private DataOutputStream dout = null; + private String userId; + private String password; + + + + private BOKEXAddTelegramManager(){ + } + + public String doTelegram( String reqData ){ + String resData = ""; + if ( socket != null){ + return ""; + } + + try { + if ( !connect()) { + return ""; + } + + din = new DataInputStream(socket.getInputStream()); + dout = new DataOutputStream(socket.getOutputStream()); + + // "FOREXFTP2FXB110406000010 N000200902261755301104FTP00000000000011104FTP@ 0030B0N"; + byte[] loginData = "FOREXFTP2FXB113706000010 N000 0030B0N".getBytes(); + // + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); + String curDate = formatter.format(Calendar.getInstance().getTime()); + + System.arraycopy( curDate.getBytes() , 0, loginData, 30, 14); + System.arraycopy( userId.getBytes() , 0, loginData, 44, userId.getBytes().length); + System.arraycopy( password.getBytes() , 0, loginData, 64, password.getBytes().length); + + String loginResult = getRecvData( new String(loginData) ); + if ( !loginResult.substring(27,30).equals("000") ){ + return loginResult; + } + resData = getRecvData(reqData); + // "FOREXFTP2FXB110406000040 N00020090226175530"; + byte[] looutData = "FOREXFTP2FXB113706000040 N000 ".getBytes(); + System.arraycopy( curDate.getBytes() , 0, looutData, 30, 14); + getRecvData(new String (looutData)); + + + } catch (Exception e) { + logger.error( e.getMessage(), e); + } finally { + if ( socket != null ){ + try { + socket.close(); + } catch (Exception e) {} + } + socket = null; + } + return resData; + } + private String getRecvData( String sendData ){ + String recvData = null; + + try { + + int sendLen = sendData.getBytes().length; + byte[] sendBuf = new byte[sendLen + 4]; + System.arraycopy( ( ""+(sendLen + 10000)).getBytes(), 1, sendBuf, 0, 4 ); + System.arraycopy( sendData.getBytes(), 0, sendBuf, 4, sendLen); + dout.write(sendBuf); + + byte[] recvBuf = new byte[4096]; + ByteArrayOutputStream boutll = new ByteArrayOutputStream(); + + ArrayList al = new ArrayList(); + + boolean contFlag = false; + do { + // LL 필드 수신 + int nRemainBytes = 4; + while (nRemainBytes > 0) { + int nReadBytes = recvData(din, 60, recvBuf, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음 + boutll.write(recvBuf, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + String strll = new String(boutll.toByteArray()); + nRemainBytes = Integer.parseInt(strll); + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + + while (nRemainBytes > 0) { + int nReadBytes = recvData(din, 60, recvBuf, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음 + bout.write(recvBuf, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + String resTelegram = new String(bout.toByteArray()); + al.add(resTelegram); + String resTelegramType = getTelegramType(resTelegram); + if ( resTelegramType.equals("02100010")){ + if (resTelegram.substring(50,51).equals("Y") ){ + contFlag = true; + }else{ + contFlag = false; + } + if ( recvData != null ){ + recvData = recvData + resTelegram.substring(51); + }else{ + recvData = resTelegram; + } + }else if ( resTelegramType.equals("02100020")){ + if (resTelegram.substring(42,43).equals("Y") ){ + contFlag = true; + }else{ + contFlag = false; + } + + if ( recvData != null ){ + recvData = recvData + resTelegram.substring(43); + }else{ + recvData = resTelegram; + } + }else if ( resTelegramType.equals("02100030")){ + if (resTelegram.substring(50,51).equals("Y") ){ + contFlag = true; + }else{ + contFlag = false; + } + + if ( recvData != null ){ + recvData = recvData + resTelegram.substring(51); + }else{ + recvData = resTelegram; + } + + } else { + recvData = resTelegram; + } + + } while (contFlag); + + } catch (Exception e) { + logger.error( e.getMessage(), e); + return ""; + } + return recvData; + } + + private boolean connect() throws Exception{ + DemandTargetVO vo = getSysConnList(); + if ( vo == null ){ + return false; + } + + userId = vo.getSocketID(); + password = vo.getSocketPwd(); + int nPortNum = -1; + try { + nPortNum = Integer.parseInt(vo.getPortNumber()); + + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC002", new String[] {vo.getPortNumber()}); + throw new Exception(errMsg); + } + + socket = socketInit(vo.getIpAddress(), nPortNum); + if (socket == null) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJC003"); + throw new Exception(errMsg); + } + + return true; + } + + private String getTelegramType(String str){ + byte[] telegramType = new byte[8]; + System.arraycopy( str.getBytes(), 16, telegramType, 0, 8); + return new String(telegramType); + } + + private Socket socketInit(String remoteIP, int remotePort) throws Exception + { + try { + return new Socket(remoteIP, remotePort); + + } catch (UnknownHostException ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC001", new String[] {remoteIP, Integer.toString(remotePort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다. + + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC002", new String[] {remoteIP, Integer.toString(remotePort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), I/O Exception이 발생했습니다. + } + } + + private DemandTargetVO getSysConnList() { + + DemandTargetVO dtVO = null; + try { + //1. 해당 작업의 대외기관 연결정보 조회 + DemandTargetVO[] sysConnList = FlowControllerManager.getInstance().getRemoteHostInfo(BOKEXKeys.PROC_CODE, BOKEXKeys.INSTI_CODE); + if (sysConnList == null || sysConnList.length == 0) { + logger.info("[BOKEXAddTelegramManager:checkSysConnList]["+ BOKEXKeys.PROC_CODE +" | "+ BOKEXKeys.INSTI_CODE +"] ==> 해당 작업의 요구송수신 연결정보가 존재하지 않음 !! ★★ 연결정보 체크 필요 ★★"); + return null; + } + //1. Job_Processing 테이블에서 모든 연결정보ID 조회 + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + HashSet runsysConnList = dao.getExecutingSysConnList(); + + for (int inx=0; inx < sysConnList.length; inx++) { + //대외기관 연결상태가 장애이면 다음 연결정보 조회 + if (sysConnList[inx].getOrganSocketStatus().equals(DemandTargetVO.ORGAN_SOCKET_STATUS_ERROR)) { + continue; + } + //해당 연결정보가 사용중이지 않으면 해당 연결정보 할당 + if (!runsysConnList.contains(sysConnList[inx].getSystemConnCode())) { + dtVO = sysConnList[inx]; + break; + } + } + if ( dtVO == null ) { + logger.info("[BOKEXAddTelegramManager:checkSysConnList]["+ BOKEXKeys.PROC_CODE +" | "+ BOKEXKeys.INSTI_CODE +"]★★★ ==> 해당 작업의 연결정보가 모두 사용중 임 !! -> 다음 Timer Event 시 연결정보 Release 된 경우 수행됨."); + return null; + } + + } catch (Exception e) { + logger.warn( "진행작업 조회 중 오류 발생"); + return null; + } + return dtVO; + } + private int recvData(DataInputStream din, int timeoutMilisec, byte[] buffer, int len) throws Exception + { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + int timoutCount = 0; + + while (true) { + try { + readBytes = din.read(buffer, 0, len); + if (readBytes < 0) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM010"); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + return readBytes; //socket 에서 읽어들인 byte 수 리턴 (1 이상) + + } catch (SocketTimeoutException ex) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM008", new String[] { timoutCount+"", (timeoutMilisec/1000)+"" }); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초] + + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJM011"); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + } + } + } + +} diff --git a/src/com/eactive/eai/batch/bokex/BOKEXKeys.java b/src/com/eactive/eai/batch/bokex/BOKEXKeys.java new file mode 100644 index 0000000..f059c7a --- /dev/null +++ b/src/com/eactive/eai/batch/bokex/BOKEXKeys.java @@ -0,0 +1,14 @@ +package com.eactive.eai.batch.bokex; + +/** +* 1. 기능 : 한국은행 외환망 부가전문 용 패키지에서 사용하는 상수를 정의한 Interface +* 2. 처리 개요 : +* - 한국은행 외환망 부가전문 용 패키지에서 사용하는 상수를 정의한 Interface +* 3. 주의사항 +* +*/ +public class BOKEXKeys +{ + public static final String PROC_CODE = "FNF00"; + public static final String INSTI_CODE = "BOK1"; +} diff --git a/src/com/eactive/eai/batch/code/CodeMessageDAO.java b/src/com/eactive/eai/batch/code/CodeMessageDAO.java new file mode 100644 index 0000000..bac0d7b --- /dev/null +++ b/src/com/eactive/eai/batch/code/CodeMessageDAO.java @@ -0,0 +1,85 @@ +package com.eactive.eai.batch.code; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.HashMap; + +/** +* 1. 기능 : 각종 메시지를 코드로 관리하기 위한 Rule 정보 테이블에 대한 Data Access Object 클래스 +* 2. 처리 개요 : 각종 메시지를 코드로 관리하기 위한 Rulw 정보에 대한 DB 로직을 처리한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class CodeMessageDAO extends BaseDAO implements CodeMessageQuery +{ + + /** + * 1. 기능 : 메시지/코드 Rule 정보 전체를 SELECT하는 메서드 + * 2. 처리 개요 : 메시지/코드 Rule 정보 전체를 SELECT 한다. + * - + * 3. 주의사항 + * + * @return 코드, 메시지를 저장하고 있는 Properties 객체 + * @exception DAOException JDBC 관련 오류(SQLException) + **/ + public HashMap getAllMessages() throws DAOException { + HashMap allMsg = new HashMap(); + ResultSet rs = null; + CodeMessageVO cmv = null; + + try { + this.connect(GET_ALL_MESSAGES); + rs = executeQuery(); + while(rs.next()) { + cmv = new CodeMessageVO(); + cmv.setMsgKey (rs.getString("Msg" )); + cmv.setMsgTxt (rs.getString("MsgCtnt" )); + cmv.setMsgEtc (rs.getString("TreatMatrCtnt" )); + cmv.setSmsSendType (rs.getString("SMSSendYn" )); + cmv.setItsmObstclGrdDstcd(rs.getString("ITSMObstclGrdDstcd" )); + allMsg.put(cmv.getMsgKey(), cmv); + } + return allMsg; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMCD101")); + } finally { + disconnect(); + } + } + + /** + * 지정된 메시지코드를 가지는 코드메시지 레코드를 읽어서 리턴한다. + */ + public CodeMessageVO getOneCodeMessage(String msg) throws DAOException { + ResultSet rs = null; + try { + this.connect(GET_ONE_MESSAGE); + this.preparedStatement.setString(1, msg); + rs = this.executeQuery(); + + CodeMessageVO cmv = null; + while(rs.next()) { + cmv = new CodeMessageVO(); + cmv.setMsgKey (rs.getString("Msg" )); + cmv.setMsgTxt (rs.getString("MsgCtnt" )); + cmv.setMsgEtc (rs.getString("TreatMatrCtnt" )); + cmv.setSmsSendType (rs.getString("SMSSendYn" )); + cmv.setItsmObstclGrdDstcd(rs.getString("ITSMObstclGrdDstcd" )); + } + return (cmv); + } catch(Exception e) { + //ExceptionUtil.getErrorCode() 사용 불가 (무한 LOOP 발생) + throw new DAOException( "코드 [" + msg + "] 의 레코드를 TSEAIBP05 테이블 에서 찾을 수 없습니다." ); + } finally { + this.disconnect(); + } + } +} diff --git a/src/com/eactive/eai/batch/code/CodeMessageHandler.java b/src/com/eactive/eai/batch/code/CodeMessageHandler.java new file mode 100644 index 0000000..b7011e7 --- /dev/null +++ b/src/com/eactive/eai/batch/code/CodeMessageHandler.java @@ -0,0 +1,81 @@ +package com.eactive.eai.batch.code; + +/** +* 1. 기능 : 메시지 코드 Rule 정보에 대한 Utility 기능을 제공하는 클래스 +* 2. 처리 개요 : 코드에 대한 메시지를 얻거나 생성한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class CodeMessageHandler +{ + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : Default Constructor + * - + * 3. 주의사항 + * + **/ + private CodeMessageHandler() { + } + + /** + * 1. 기능 : 코드에 대한 메시지 텍스트를 찾아 반환하는 메서드 + * 2. 처리 개요 : 코드에 대한 메시지 텍스트를 찾아 반환한다. + * - + * 3. 주의사항 + * + * @param code 메시지 코드 + * @return 메시지 텍스트 + **/ + public static String getMessage(String code) { + return CodeMessageManager.getInstance().getMessage(code); + } + + /** + * 1. 기능 : 코드에 대한 메시지 텍스트를 찾아 반환하는 메서드 + * 2. 처리 개요 : 코드에 대한 메시지 텍스트를 찾아 반환한다. + * - + * 3. 주의사항 + * + * @param code 메시지 코드 + * @param args 메시지 텍스트를 만들기 위한 인수 리스트 + * @return 메시지 텍스트 + **/ + public static String getMessage(String code, String[] args) { + String msg = CodeMessageManager.getInstance().getMessage(code); + return makeMessage(msg,args); + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + private static String makeMessage(String msg, String[] args) { + String keyword = null, head = null, tail = null; + int idx = -1; + for(int i=0;i messages; + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + /** + * 기동 여부 + */ + private boolean started; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : messages를 저장하기 위한 HashMap을 초기화한다. + * - + * 3. 주의사항 + * + **/ + private CodeMessageManager() { + messages = new HashMap(); + } + + /** + * 1. 기능 : CodeMessageManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : CodeMessageManager Singleton Object를 반환한다. + * - + * 3. 주의사항 + * + * @return CodeMessageManager + **/ + public static CodeMessageManager getInstance() { + return instance; + } + + /** + * 1. 기능 : Lifecycle의 start 메서드로 CodeMessageManager를 초기화하는 메서드 + * 2. 처리 개요 : CodeMessageDAO를 이용해 추출 Rule 정보 모두를 가져와 초기화한다. + * - + * 3. 주의사항 + * + * @exception LifecycleException + **/ + public void start() throws LifecycleException { + if (started) + throw new LifecycleException("BECEAIMCD201"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + messages = null; + + CodeMessageDAO dao = null; + try { + dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class); + messages = dao.getAllMessages(); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMCD202")); + } + + started = true; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 CodeMessageManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 코드, 텍스트 Rule 정보를 clear한다. + * - + * 3. 주의사항 + * + * @exception LifecycleException + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMCD203"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + messages.clear(); + + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : BizKeyManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : BizKeyManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + + /** + * 1. 기능 : 코드에 대한 메시지 텍스트를 반환하는 메서드 + * 2. 처리 개요 : 파라미터 코드에 대한 메시지 텍스트를 찾아 반환한다. + * - + * 3. 주의사항 + * + * @param code 메시지 코드 + * @return 메시지 텍스트 + **/ + public String getMessage(String code) { + if(code==null) return null; + //String msg = (String)messages.get(code); + + if (messages == null || messages.size() == 0) { + CodeMessageDAO dao = null; + try { + dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class); + CodeMessageVO codeInfo = dao.getOneCodeMessage(code); + if (codeInfo==null) return "UNDEFINE"; + + String msg = codeInfo.getMsgTxt(); + return (msg==null) ? "UNDEFINE" : msg; + } catch(DAOException e) { + return "The CodeMessage["+code+"] is not defiend."; + } + } else { + CodeMessageVO vo = (CodeMessageVO)messages.get(code); + if(vo==null) return "The CodeMessage["+code+"] is not defiend."; + String msg = vo.getMsgTxt(); + return (msg==null) ? "UNDEFINE" : msg; + } + } + + /** + * 1. 기능 : 코드에 대한 메시지 내용과 조치사항내용을 반환하는 메서드 + * 2. 처리 개요 : 파라미터 코드에 대한 메시지 내용과 조치사항내용을 찾아 반환한다. + * - + * 3. 주의사항 + * + * @param code 메시지 코드 + * @return 메시지 Value Object + **/ + + public CodeMessageVO getMessageVO(String code) { + if(code==null) return null; + + CodeMessageVO cmv = null; + if (messages == null || messages.size() == 0) { + CodeMessageDAO dao = null; + try { + dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class); + cmv = dao.getOneCodeMessage(code); + } catch(DAOException e) { + cmv = null; + } + } else { + cmv = (CodeMessageVO)messages.get( code ); + } + return cmv; + } + + + /** + * 1. 기능 : 메시지, 메시지 내용, 조치사항내용을 저장/변경하는 메서드 + * 2. 처리 개요 : 메시지에 대한 텍스트를 변경하거나 저장한다. + * - + * 3. 주의사항 + * + * @param code 메시지 코드 + * @param msg 메시지 텍스트 + **/ + + public void setMessage(CodeMessageVO cmm) { + messages.put(cmm.getMsgKey(), cmm); + } + + /** + * 1. 기능 : 코드 메시지 Rule 정보를 삭제하는 메서드. + * 2. 처리 개요 : 파라미터의 메시지 코드에 대한 Rule 정보를 삭제한다. + * - + * 3. 주의사항 + * + * @param code 메시지 코드 + **/ + public void removeMessage(String code) { + messages.remove(code); + } + + /** + * 1. 기능 : 코드 리스트를 반환하는 메서드 + * 2. 처리 개요 : 코드 리스트를 반환한다. + * - + * 3. 주의사항 + * + * @return 코드 리스트 + **/ + public String[] getAllCodes() { + String[] codes = new String[messages.size()]; + Iterator it = messages.keySet().iterator(); + for(int i=0;it.hasNext();i++) { + codes[i] = it.next(); + } + return codes; + } + + /** + * 1. 기능 : 전체 코드메시지 리스트를 Properties 로 반환하는 메서드 + * 2. 처리 개요 : 전체 코드메시지 리스틀 Properties로 반환한다. + * - + * 3. 주의사항 + * + * @return 전체 코드 메시지 리스트를 저장하고 있는 Properties + **/ + public HashMap getAllCodeMessages() { + return this.messages; + } + + public synchronized void reload(String key) throws Exception { + CodeMessageDAO dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class); + CodeMessageVO vo = dao.getOneCodeMessage(key); + if(vo != null) { + this.messages.put(key, vo); + } + else { + throw new Exception("CodeMessageManager not found in Database : key["+key+"]"); + } + } + +} diff --git a/src/com/eactive/eai/batch/code/CodeMessageQuery.java b/src/com/eactive/eai/batch/code/CodeMessageQuery.java new file mode 100644 index 0000000..3c99418 --- /dev/null +++ b/src/com/eactive/eai/batch/code/CodeMessageQuery.java @@ -0,0 +1,39 @@ +package com.eactive.eai.batch.code; + +import com.eactive.eai.common.dao.Keys; + +/** +* 1. 기능 : CodeMessageDAO에서 사용하는 SQL Query를 정의한 상수 인터페이스 +* 2. 처리 개요 : CodeMessageDAO에서 사용하는 SQL Query를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public interface CodeMessageQuery +{ + /** + * 코드, 텍스트 Rule 정보 전체를 SELECT하는 SQL Query + */ + public static final String GET_ALL_MESSAGES = "SELECT Msg ,\n" + + " MsgCtnt ,\n" + + " TreatMatrCtnt ,\n" + + " SMSSendYn ,\n" + + " ITSMObstclGrdDstcd\n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBP05"; + + /** + * 특정 코드메시지 레코드를 읽어낸다. + */ + public static final String GET_ONE_MESSAGE = "SELECT Msg ,\n" + + " MsgCtnt ,\n" + + " TreatMatrCtnt ,\n" + + " SMSSendYn ,\n" + + " ITSMObstclGrdDstcd\n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBP05\n" + + "WHERE Msg = ?"; + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/code/CodeMessageVO.java b/src/com/eactive/eai/batch/code/CodeMessageVO.java new file mode 100644 index 0000000..e92b4db --- /dev/null +++ b/src/com/eactive/eai/batch/code/CodeMessageVO.java @@ -0,0 +1,78 @@ +package com.eactive.eai.batch.code; + +import com.eactive.eai.common.util.NullControl; + +import java.io.Serializable; + +public class CodeMessageVO implements Serializable +{ + @Override + public String toString() { + return "CodeMessageVO [msgKey=" + msgKey + ", msgTxt=" + msgTxt + + ", msgEtc=" + msgEtc + ", smsSendType=" + smsSendType + + ", itsmObstclGrdDstcd=" + itsmObstclGrdDstcd + "]"; + } + + /** + * + */ + private static final long serialVersionUID = 1L; + private String msgKey; // 메시지ID + private String msgTxt; // 메시지내용 + private String msgEtc; // 조치사항내용 --> SMS발송 시 사용 문구 + private String smsSendType = "";// SMS발송 여부 + private String itsmObstclGrdDstcd = "";// ITSM장애등급구분코드 + + public CodeMessageVO() { + this(""); + } + + public CodeMessageVO(String msgKey) { + this(msgKey, ""); + } + + public CodeMessageVO(String msgKey, String msgTxt) { + this.msgKey = msgKey; + this.msgTxt = msgTxt; + } + + public void setMsgKey(String msgKey) { + this.msgKey = msgKey; + } + + public String getMsgKey() { + return this.msgKey; + } + + public void setMsgTxt(String msgTxt) { + this.msgTxt = msgTxt; + } + + public String getMsgTxt() { + return this.msgTxt; + } + + public void setMsgEtc(String msgEtc) { + this.msgEtc = msgEtc; + } + + public String getMsgEtc() { + return NullControl.trimSpace(this.msgEtc); + } + + public void setSmsSendType(String arg) { + this.smsSendType = arg; + } + + public String getSmsSendType() { + return this.smsSendType; + } + + public String getItsmObstclGrdDstcd() { + return itsmObstclGrdDstcd; + } + + public void setItsmObstclGrdDstcd(String itsmObstclGrdDstcd) { + this.itsmObstclGrdDstcd = itsmObstclGrdDstcd; + } +} diff --git a/src/com/eactive/eai/batch/common/BatchDirMakeUtil.java b/src/com/eactive/eai/batch/common/BatchDirMakeUtil.java new file mode 100644 index 0000000..b11138a --- /dev/null +++ b/src/com/eactive/eai/batch/common/BatchDirMakeUtil.java @@ -0,0 +1,140 @@ +//package com.eactive.eai.batch.common; +// +//import com.eactive.eai.common.dao.DAOFactory; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//import java.util.ArrayList; +// +//public class BatchDirMakeUtil +//{ +// +// //파일로거 +// private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT); +// +// private static String[] batchDirs; +// +// private static void setBatchDirs() throws Exception { +// BatchDirDAO dao = (BatchDirDAO)DAOFactory.newInstance().create(BatchDirDAO.class); +// ArrayList aList = dao.getBatchDirList(); +// batchDirs = new String[aList.size()]; +// aList.toArray(batchDirs); +// } +// +// private static void makeDirBatch(String dirSuffix, boolean makeParent) throws Exception { +// int successCnt = 0; +// for (int i=0; i bizGroupList = dao.getBizGroupList(processCode); +// +// for (int i=0; i organList = dao.getOrganList(processCode); +// +// for (int i=0; i organList = dao.getOrganList(processCode); +// +// for (int i=0; i organList = dao.getOrganList(processCode); +// +// for (int i=0; i bizGroupList = DirInfoManager.getInstance().getDirInfoByBatchCode(processCode); +// for (int i=0; i organList = OutsideManager.getInstance().getOutsideInfo(processCode); +// for (int i=0; i organList = OutsideManager.getInstance().getOutsideInfo(processCode); +// for (int i=0; i organList = OutsideManager.getInstance().getOutsideInfo(processCode); +// for (int i=0; i StringUtil.stoi(systime)){ + hhmm = simpledateformat.format(date) + hhmm + "0000"; + } + //hhmm가 현재시간보다 크지않을경우 다음날짜로 + else{ + hhmm = getDatewithSpan(simpledateformat.format(date),1) + hhmm + "0000"; + } + return hhmm; + } + + public static String getDatewithSpan(String s, int i) + { + int j = 0x36ee80; + SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd"); + SimpleTimeZone simpletimezone = new SimpleTimeZone(9 * j, "KST"); + simpledateformat.setTimeZone(simpletimezone); + int k = Integer.valueOf(s.substring(0, 4)).intValue(); + int l = Integer.valueOf(s.substring(4, 6)).intValue() - 1; + int i1 = Integer.valueOf(s.substring(6, 8)).intValue() + i; + Calendar calendar = Calendar.getInstance(); + calendar.set(k, l, i1); + return simpledateformat.format(calendar.getTime()); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/common/CommonKeys.java b/src/com/eactive/eai/batch/common/CommonKeys.java new file mode 100644 index 0000000..0767e16 --- /dev/null +++ b/src/com/eactive/eai/batch/common/CommonKeys.java @@ -0,0 +1,58 @@ +package com.eactive.eai.batch.common; + + +/** +* 1. 기능 : 배치프레임웍에서 공통으로 사용하는 상수를 정의한 Interface +* 2. 처리 개요 : +* - +* 3. 주의사항 +* +* @author : YCLee 06/01/24 +* @version : v 1.0.0 +* @since :JDK v1.4.2 +*/ +public class CommonKeys +{ + /* ******************************************************************* + * Master Layer 구분 상수 + ******************************************************************* */ + + public static final String LAYER_USER_INTERFACE = "UI"; //UI (요구송신재처리,요구수신강제등록) + public static final String LAYER_FILE_EVENT = "FE"; //File Event + public static final String LAYER_SOCKET_SERVER = "SS"; //Socket Server + public static final String LAYER_SCHEDULER = "SC"; //Scheduler + public static final String LAYER_FLOW_CONTROLLER = "FC"; //Flow Controller + + + /* ******************************************************************* + * Layer 구분 상수 + ******************************************************************* */ + public static final String SUB_LAYER_USER_INTERFACE = "UI"; //UI (요구송신재처리,요구수신강제등록) + public static final String SUB_LAYER_FILE_EVENT = "FE"; //File Event + public static final String SUB_LAYER_SOCKET_SERVER = "SS"; //Socket Server + public static final String SUB_LAYER_SCHEDULER_QUEUE = "SQ"; //Scheduler Queue + public static final String SUB_LAYER_SCHEDULER_PROCESSING = "SP"; //Scheduler Processing + public static final String SUB_LAYER_FLOW_CONTROLLER = "FC"; //Flow Controller + + public static final String SUB_LAYER_FLOW_PHASE_ST = "ST"; //Flow Controller 개시 [ST: Start ] + public static final String SUB_LAYER_FLOW_PHASE_FI = "FI"; //Flow Controller 파일정보교환 [FI: File Info ] + public static final String SUB_LAYER_FLOW_PHASE_DS = "DS"; //Flow Controller Data 송수신 [DS: Data Send ] + public static final String SUB_LAYER_FLOW_PHASE_MI = "MI"; //Flow Controller 결번정보교환 [MI: Missing Data Info] + public static final String SUB_LAYER_FLOW_PHASE_MS = "MS"; //Flow Controller 결번 송수신 [MS: Missing Data Send] + public static final String SUB_LAYER_FLOW_PHASE_UE = "UE"; //Flow Controller 단위업무종료 [UE: Unit End ] + public static final String SUB_LAYER_FLOW_PHASE_AE = "AE"; //Flow Controller 전업무종료 [AE: All End ] + public static final String SUB_LAYER_FLOW_PHASE_EX = "EX"; //Flow Controller 예외 [EX: Exception ] + public static final String SUB_LAYER_FLOW_PHASE_LT = "LT"; //Flow Controller 시스템회선상태확인(테스트) [LT: Line Test ] + public static final String SUB_LAYER_FLOW_PHASE_SE = "SE"; //Flow Controller 시스템장애통보 [SE: System Error ] + public static final String SUB_LAYER_FLOW_PHASE_SR = "SR"; //Flow Controller 시스템장애회복통보 [SR: System Recovery ] + public static final String SUB_LAYER_FLOW_PHASE_CK = "CK"; //Flow Controller 요구송신 테스트전문 + + /* ******************************************************************* + * 업무 유형 구분 상수 + ******************************************************************* */ + public static final String PROCESS_REQUEST_SEND = "RS"; //요구송신 + public static final String PROCESS_REQUEST_RECEIVE = "RR"; //요구수신 + public static final String PROCESS_RESPONSE_SEND = "AS"; //응답송신 + public static final String PROCESS_RESPONSE_RECEIVE = "AR"; //응답수신 + +} diff --git a/src/com/eactive/eai/batch/common/EzgatorUtil.java b/src/com/eactive/eai/batch/common/EzgatorUtil.java new file mode 100644 index 0000000..9038ff8 --- /dev/null +++ b/src/com/eactive/eai/batch/common/EzgatorUtil.java @@ -0,0 +1,273 @@ +package com.eactive.eai.batch.common; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; +import com.sennet.gator.EzGatorFile; +import com.sennet.gator.JobType; +import com.sennet.gator.console.main.EzGatorExecutor; + +public class EzgatorUtil { + + private static String CBS_DIR_INFO = "CBSDirInfo"; + + private static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); + + public static EzGatorFile[] listFiles(String server, int port, String path, HashMap extmap) throws IOException { + + EzGatorExecutor executor = new EzGatorExecutor(); + try { + + Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO ); + String keyPath = prop.getProperty("mft.key.path"); + String username = prop.getProperty("mft.user.name"); + executor.setIp(server); // API가 접속하는 서버, 송신할 파일이 있는 서버 + executor.setPort(port); + executor.setUserId(username); + executor.setPassword(""); + executor.setRemoteServerIp(server); + executor.setRemoteServerPort(port); + executor.setJobType(JobType.GETDIRINFO); // 작업 종류 + executor.setSrcFile(""); + if (extmap != null) { + executor.setOption("24h"); + } + executor.setPrivateKeyPath(keyPath); + + executor.init(); + executor.connect(); + executor.login(); + + EzGatorFile[] ezGatorFiles = null; + if (extmap == null) { + ezGatorFiles = executor.listFiles(path); + } else { + ArrayList list = new ArrayList(); + for (int inx = 0; inx < extmap.size(); inx++) { + String ext = extmap.get(inx); + EzGatorFile[] ezGatorFilesTemp = executor.listFiles(path + "/*." + ext); + logger.debug("DHJEONG==>server:" + server + ",port:" + port + ",username:" + username + ",path:" + path + ";" + ext); + for (int jnx = 0; jnx < ezGatorFilesTemp.length; jnx++) { + list.add(ezGatorFilesTemp[jnx]); + } + } + ezGatorFiles = new EzGatorFile[list.size()]; + list.toArray(ezGatorFiles); + } + logger.info("[MFT를 통해 검색된 체크파일 개수]server:" + server + ",port:" + port + ",path:" + path + ",files-->" + ezGatorFiles.length); + for (int inx = 0; inx < ezGatorFiles.length; inx++) { + logger.debug("[MFT를 통해 검색된 체크파일 목록]" + ezGatorFiles[inx].getRawListing()); + } + return ezGatorFiles; + + } catch (Throwable t) { + String arg[] = new String[2]; + arg[0] = server; + arg[1] = "" + port; + String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg); + logger.error(errMsg, t); + throw new IOException(t); + } finally { + executor.disconnect(); + } + } + + public static boolean retrieve(String server, int port, String remote, String localPath) throws Exception { + + logger.info("[retrieve]remote ------->" + remote + ", localPath---->" + localPath); + + File chkDir = new File(localPath); + + chkDir.mkdirs(); // 상위 디렉토리 미 존재시에도 write 한다. + try { + chkDir.setReadable(true, false); + chkDir.setWritable(true, false); + chkDir.setExecutable(true, false); + File p1 = chkDir.getParentFile(); + p1.setReadable(true, false); + p1.setExecutable(true, false); + p1.setWritable(true, false); + File p2 = p1.getParentFile(); + p2.setReadable(true, false); + p2.setExecutable(true, false); + p2.setWritable(true, false); + File p3 = p2.getParentFile(); + p3.setReadable(true, false); + p3.setExecutable(true, false); + p3.setWritable(true, false); + File p4 = p3.getParentFile(); + p4.setReadable(true, false); + p4.setExecutable(true, false); + } catch (Exception e) { + // + } + + String delimiter = StringUtil.getDirDelimiter(localPath); + String fName = remote.substring(remote.lastIndexOf(delimiter) + 1); + + EzGatorExecutor executor = new EzGatorExecutor(); + try { + Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO ); + String localServer = prop.getProperty("mft.local.server"); + String keyPath = prop.getProperty("mft.key.path"); + String username = prop.getProperty("mft.user.name"); + + int localPort = Integer.parseInt(prop.getProperty("mft.local.port")); + executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버 + executor.setPort(localPort); + executor.setUserId(username); + executor.setPassword(""); + executor.setJobType(JobType.RECVFILE); // 작업 종류 + executor.setPrivateKeyPath(keyPath); + executor.setRemoteServerIp(server); // 수신 서버 + executor.setRemoteServerPort(port); + executor.setSrcFile(remote); + executor.setSrcSuffix(null); + executor.setOption("ir"); + executor.setDestFile(localPath + fName); // 수신할 파일의 절대경로 + executor.setDestSuffix(null); + executor.init(); + executor.connect(); + executor.login(); + if (!executor.recvServerFile()) { + logger.warn("Command failed: " + executor.getErrorMsg()); + throw new Exception(executor.getErrorMsg()); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + executor.disconnect(); + } + + return true; + } + + public static boolean store(String server, int port, String remote, String localPath) throws Exception { + + EzGatorExecutor executor = new EzGatorExecutor(); + + try { + localPath = localPath.replace("\\r$", ""); + Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO ); + String localServer = prop.getProperty("mft.local.server"); + int localPort = Integer.parseInt(prop.getProperty("mft.local.port")); + String keyPath = prop.getProperty("mft.key.path"); + String username = prop.getProperty("mft.user.name"); + executor.setPrivateKeyPath(keyPath); + executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버 + executor.setPort(localPort); + executor.setUserId(username); + executor.setPassword(""); + executor.setJobType(JobType.SENDFILE); // 작업 종류 + executor.setRemoteServerIp(server); // 수신 서버 + executor.setRemoteServerPort(port); + executor.setSrcFile(localPath); + executor.setSrcSuffix(null); + executor.setOption("ir"); + executor.setDestFile(remote); // 수신할 파일의 절대경로 + executor.setDestSuffix(null); + executor.init(); + executor.connect(); + executor.login(); + boolean success = false; + try { + success = executor.sendServerFile(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } + if (!success) { + logger.warn("Command failed: " + executor.getErrorMsg()); + throw new Exception(executor.getErrorMsg()); + } + } catch (Throwable e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + executor.disconnect(); + } + return true; + } + + public static boolean delete(String server, int port, String fullfilename) throws IOException { + + EzGatorExecutor executor = new EzGatorExecutor(); + try { + fullfilename = fullfilename.replace("\\r$", ""); + Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO ); + String localServer = prop.getProperty("mft.local.server"); + int localPort = Integer.parseInt(prop.getProperty("mft.local.port")); + String keyPath = prop.getProperty("mft.key.path"); + String username = prop.getProperty("mft.user.name"); + executor.setPrivateKeyPath(keyPath); + executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버 + executor.setPort(localPort); + executor.setUserId(username); + executor.setPassword(""); + executor.setRemoteServerIp(server); // 수신 서버 + executor.setRemoteServerPort(port); + executor.setJobType(JobType.DELETEFILE); // 작업 종류 + executor.setSrcFile(fullfilename); + executor.init(); + executor.connect(); + executor.login(); + return executor.deleteServerFile(); + } catch (Exception e) { + String arg[] = new String[2]; + arg[0] = server; + arg[1] = "" + port; + String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg); + logger.error(errMsg, e); + throw new IOException(e); + } finally { + executor.disconnect(); + } + } + + public static boolean rename(String server, int port, String srcname, String tarname) throws IOException { + + EzGatorExecutor executor = new EzGatorExecutor(); + + try { + srcname = srcname.replace("\\r$", ""); + tarname = tarname.replace("\\r$", ""); + Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO ); + String localServer = prop.getProperty("mft.local.server"); + int localPort = Integer.parseInt(prop.getProperty("mft.local.port")); + String keyPath = prop.getProperty("mft.key.path"); + String username = prop.getProperty("mft.user.name"); + + executor.setPrivateKeyPath(keyPath); + executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버 + executor.setPort(localPort); + executor.setUserId(username); + executor.setPassword(""); + executor.setRemoteServerIp(server); // 수신 서버 + executor.setRemoteServerPort(port); + executor.setJobType(JobType.RENAMEFILE); // 작업 종류 + executor.setSrcFile(srcname); + executor.setDestFile(tarname); + executor.setOption("ov"); + executor.init(); + executor.connect(); + executor.login(); + return executor.renameServerFile(); + } catch (Exception e) { + String arg[] = new String[2]; + arg[0] = server; + arg[1] = "" + port; + String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg); + logger.error(errMsg, e); + throw new IOException(e); + } finally { + executor.disconnect(); + } + } +} diff --git a/src/com/eactive/eai/batch/common/FileUtil.java b/src/com/eactive/eai/batch/common/FileUtil.java new file mode 100644 index 0000000..e1c6743 --- /dev/null +++ b/src/com/eactive/eai/batch/common/FileUtil.java @@ -0,0 +1,421 @@ +package com.eactive.eai.batch.common; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.logger.LogManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +/** + *
+ * 디렉토리 또는 파일을 생성/삭제/이동/이름변경 하는 유틸리티이다.
+ * 참고) 윈도계열과 유닉스계열에 모두 적용된다.
+ * 
+ */ +public class FileUtil { + + //파일로거 + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * 디렉토리를 생성한다.
+ * 참고) 상위디렉토리가 이미 생성되어 있어야 한다. + * @param path 디렉토리 경로 문자열 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean mkdir(String path) { + return mkdir(path, false); + } + + /** + * 디렉토리를 생성한다.
+ * 참고) 상위디렉토리가 미 존재시 상위디렉토리까지 생성할 수 있다. + * @param path 디렉토리 경로 문자열 + * @param isRecursive 상위디렉토리 미 존재시 생성여부 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean mkdir(String path, boolean isRecursive) { + if (path==null || (path=path.trim()).equals("")) return false; + return mkdir(new File(path.replace('\\', '/')), isRecursive); + } + + /** + * 디렉토리를 생성한다.
+ * 참고) 상위디렉토리가 미 존재시 상위디렉토리까지 생성할 수 있다. + * @param path 디렉토리 경로 File 객체 + * @param isRecursive 상위디렉토리 미 존재시 생성여부 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean mkdir(File f, boolean isRecursive) { + if (f==null) return false; + if (f.exists()) { + logger.debug(" - 디렉토리 생성...["+ f.getAbsolutePath() +"] -> true (이미존재함)"); + setExecutable(f.getAbsolutePath()); + return true; + } + + boolean isSuccess = (isRecursive)? f.mkdirs() : f.mkdir(); + logger.debug(" - 디렉토리 생성...["+ f.getAbsolutePath() +"] -> "+ isSuccess); + setExecutable(f.getAbsolutePath()); + return isSuccess; + } + + /** + * 디렉토리를 삭제한다.
+ * 참고) 디렉토리 안에 내용이 없어야 한다. + * @param path 디렉토리 경로 문자열 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean rmdir(String path) { + return rmdir(path, false); + } + + /** + * 디렉토리를 삭제한다.
+ * 참고) 디렉토리 안의 내용 존재시 모든 내용을 삭제할 수 있다. + * @param path 디렉토리 경로 문자열 + * @param isRecursive 내용 존재시 삭제여부 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean rmdir(String path, boolean isRecursive) { + if (path==null || (path=path.trim()).equals("")) return false; + return rmdir(new File(path.replace('\\', '/')), isRecursive); + } + + /** + * 디렉토리를 삭제한다.
+ * 참고) 디렉토리 안의 내용 존재시 모든 내용을 삭제할 수 있다. + * @param path 디렉토리 경로 File 객체 + * @param isRecursive 내용 존재시 삭제여부 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean rmdir(File f, boolean isRecursive) { + if (f==null) return false; + if (!f.exists()) { + logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> true (존재안함)"); + return true; + } + if (f.isFile()) { + logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> false (파일임)"); + return false; + } + + if (isRecursive) { //디렉토리 내의 모든 내용도 삭제할때 + File[] fl = f.listFiles(); + + for (int i=0; i "+ isSuccess); + } else { + isSuccess = rmdir(fl[i], true); + } + if (!isSuccess) return false; + } + boolean isSuccess = f.delete(); + logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> "+ isSuccess); + return isSuccess; + + } else { + boolean isSuccess = f.delete(); + logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> "+ isSuccess); + return isSuccess; + } + } + + /** + * 파일을 삭제한다. + * @param path 파일 경로 문자열 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean delete(String path) { + if (path==null || (path=path.trim()).equals("")) return false; + return delete(new File(path.replace('\\', '/'))); + } + + /** + * 파일을 삭제한다. + * @param path 파일 경로 File 객체 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean delete(File f) { + if (f==null || !f.exists() || f.isDirectory()) return false; //존재하지 않거나 디렉토리면 리턴 true + return f.delete(); + } + + /** + * 파일 또는 디렉토리의 이름을 변경 또는 이동 시킨다.
+ * 주의) 윈도계열에서 이동시 다른 드라이브로 이동할 수는 없다. + * @param pathFrom 원본 디렉토리 또는 파일 경로 문자열 + * @param pathTo 목적 디렉토리 또는 파일 경로 문자열 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean move(String pathFrom, String pathTo) { + return move(pathFrom, pathTo, false); + } + + /** + * 파일 또는 디렉토리의 이름을 변경 또는 이동 시킨다.
+ * 참고) 목적 경로의 상위디렉토리 미 존재시 상위디렉토리 생성 후 이름변경 또는 이동할 수 있다. + * 주의) 윈도계열에서 이동시 다른 드라이브로 이동할 수는 없다. + * @param pathFrom 원본 디렉토리 또는 파일 경로 문자열 + * @param pathTo 목적 디렉토리 또는 파일 경로 문자열 + * @param isMkdir 목적경로의 상위디렉토리 미 존재시 생성여부 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean move(String pathFrom, String pathTo, boolean isMkdir) { + if (pathFrom==null || (pathFrom=pathFrom.trim()).equals("")) return false; + if (pathTo ==null || (pathTo =pathTo.trim() ).equals("")) return false; + return move(new File(pathFrom.replace('\\', '/')), pathTo.replace ('\\', '/'), isMkdir); + } + + /** + * 파일 또는 디렉토리의 이름을 변경 또는 이동 시킨다.
+ * 참고) 목적 경로의 상위디렉토리 미 존재시 상위디렉토리 생성 후 이름변경 또는 이동할 수 있다. + * 주의) 윈도계열에서 이동시 다른 드라이브로 이동할 수는 없다. + * @param pathFrom 원본 디렉토리 또는 파일 경로 File 객체 + * @param pathTo 목적 디렉토리 또는 파일 경로 문자열 + * @param isMkdir 목적경로의 상위디렉토리 미 존재시 생성여부 + * @return 성공시 리턴 true, 실패시 리턴 false + */ + public static boolean move(File f, String pathTo, boolean isMkdir) { + if (f==null) return false; + if (!f.exists()) { + logger.debug(" - 디렉토리 이동...["+ f.getAbsolutePath() +"] to ["+ pathTo +"] -> false (존재안함)"); + return false; + } + + //목적경로가 없을경우 강제로 만듬 + if (isMkdir) { + if (pathTo.endsWith("/")) pathTo = pathTo.substring(0, pathTo.length()-1); //맨끝 "/" 제거 + boolean isSuccess = mkdir(pathTo.substring(0, pathTo.lastIndexOf("/")), true); + if (!isSuccess) { + logger.debug(" - 디렉토리 이동...["+ f.getAbsolutePath() +"] to ["+ pathTo +"] -> false (미존재Path생성실패)"); + return false; + } + } + File f1 = new File(pathTo); + boolean isSuccess = f.renameTo(f1); + logger.debug(" - 디렉토리 이동...["+ f.getAbsolutePath() +"] to ["+ f1.getAbsolutePath() +"] -> "+ isSuccess); + setExecutable(pathTo); + return isSuccess; + } + + public static boolean copyTransferFile(File sourceFile, File targetFile) throws IOException { + return copyTransferFile(sourceFile, targetFile, false); + } + + public static boolean copyTransferFile(File sourceFile, File targetFile, boolean flag) throws IOException { + FileChannel inChannel = null; + FileChannel outChannel = null; + boolean success = true; + try { + inChannel = new FileInputStream(sourceFile).getChannel(); + outChannel = new FileOutputStream(targetFile).getChannel(); + inChannel.transferTo(0, inChannel.size(), outChannel); + } finally { + try { + if (inChannel != null) { + inChannel.close(); + } + if (outChannel != null) { + outChannel.close(); + } + } catch (IOException e) { + success = false; + logger.error( e.getMessage(), e); + } + } + if ( success && flag ){ + try { + sourceFile.delete(); + } catch (Exception e) { + success = false; + logger.error( e.getMessage(), e); + } + } + return success; + } + + public static byte[] readLine( FileInputStream fin ){ + byte[] fileLine = new byte[1024]; + byte[] newLine = null; + int len = 0; + int buf; + try { + while (( buf = fin.read()) != -1) { + if ( buf == '\n' ) + break; + if ( len == fileLine.length ){ + byte[] tmpLine = fileLine; + fileLine = new byte[len + 1024]; + System.arraycopy( tmpLine, 0, fileLine, 0, len ); + } + fileLine[len] = (byte)buf; + len++; + } + if ( ( len > 0 ) && ( fileLine[len-1] == '\r' ) ) + len--; + if ( len == 0 ) + return null; + newLine = new byte[len]; + System.arraycopy( fileLine, 0, newLine, 0, len ); + } catch (Exception e) { + return null; + } + return newLine; + } + private static void setExecutable ( String path ){ + + String cmd1 = "chmod 775 " + path; +// String cmd2 = "chgrp ftp " + path; + +// File dir = new File(path); + try { + Runtime.getRuntime().exec( cmd1 ); +// Runtime.getRuntime().exec( cmd2 ); +// dir.setExecutable(true, false); +// dir.setReadable(true, false); +// dir.setWritable(true, false); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + } + + static public List getFileList(File dir){ + ArrayList list = new ArrayList(); + File[] flist = dir.listFiles(); + for (File file : flist) { + if ( file.isFile() ){ + list.add(file); + }else if ( file.isDirectory()){ + ArrayList slist = (ArrayList) getFileList(file); + for (File file2 : slist) { + list.add(file2); + } + } + } + return list; + + } + + static public List getSendFileList(File dir){ +// ArrayList list = new ArrayList(); +// File[] deplist = dir.listFiles(); +// for (File deps : deplist) { +// File sendDir = new File( deps.getAbsoluteFile()+ File.separator + "snd" ); +// if ( sendDir.exists() && sendDir.isDirectory()){ +// ArrayList slist = (ArrayList) getFileList(sendDir); +// for (File file : slist) { +// list.add(file); +// } +// } +// } +// return list; + + ArrayList list = new ArrayList(); + + if ( dir.exists() && dir.isDirectory()){ + ArrayList slist = (ArrayList) getFileList(dir); + for (File file : slist) { + list.add(file); + } + } + + return list; + + + } + + static public String getRecvFileName(String fileName, String pattern, BatchDoc batchDoc){ + return getRecvFileName( fileName, pattern, batchDoc, true); + } + + static public String getRecvFileName(String fileName, String pattern, BatchDoc batchDoc, boolean flag){ + + String rFileName = fileName + ""; + String recvDate = null; + boolean useSeq = false; + if (pattern == null || pattern.trim().equals("")){ + return rFileName; + } + + if ( pattern.endsWith("001") ){ + useSeq = true; + pattern = pattern.substring(0, pattern.length()-3); + if ( pattern.endsWith("_") ){ + pattern = pattern.substring(0, pattern.length()-1); + } + } + String baseDate = batchDoc.getBatchMsg().getHeader().getBaseDate(); + if ( baseDate == null || baseDate.trim().equals("") || !DatetimeUtil.isRightDate(baseDate)){ + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); + baseDate = formatter.format(Calendar.getInstance().getTime()); + } + Calendar calendar = Calendar.getInstance(); + calendar.set(Integer.parseInt(baseDate.substring(0,4)),Integer.parseInt(baseDate.substring(4,6))-1,Integer.parseInt(baseDate.substring(6))); + + SimpleDateFormat sdf = new SimpleDateFormat( pattern ); + recvDate = sdf.format(calendar.getTime()); + + if ( recvDate != null && !recvDate.equals("") ){ + rFileName = rFileName + "_" + recvDate; + } + + if ( !useSeq ) + return rFileName; + + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String instCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + String fileSeq = "001"; + + try { + fileSeq = LogManager.getInstance().getFileNameSeq(procCode, instCode, rFileName, flag); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return rFileName + "_" + fileSeq; + } + + + public static byte[] readLine( BufferedInputStream bis ){ + byte[] fileLine = new byte[1024]; + byte[] newLine = null; + int len = 0; + int buf; + try { + while (( buf = bis.read()) != -1) { + if ( buf == '\n' ) + break; + if ( len == fileLine.length ){ + byte[] tmpLine = fileLine; + fileLine = new byte[len + 1024]; + System.arraycopy( tmpLine, 0, fileLine, 0, len ); + } + fileLine[len] = (byte)buf; + len++; + } + if ( ( len > 0 ) && ( fileLine[len-1] == '\r' ) ) + len--; + if ( len == 0 ) + return null; + newLine = new byte[len]; + System.arraycopy( fileLine, 0, newLine, 0, len ); + } catch (Exception e) { + return null; + } + return newLine; + } + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/common/ItmsSmsUtil.java b/src/com/eactive/eai/batch/common/ItmsSmsUtil.java new file mode 100644 index 0000000..0fe4f59 --- /dev/null +++ b/src/com/eactive/eai/batch/common/ItmsSmsUtil.java @@ -0,0 +1,203 @@ +//package com.eactive.eai.batch.common; +// +//import java.io.DataOutputStream; +//import java.net.Socket; +//import java.text.SimpleDateFormat; +//import java.util.Calendar; +// +//import com.eactive.eai.batch.code.CodeMessageManager; +//import com.eactive.eai.batch.code.CodeMessageVO; +//import com.eactive.eai.batch.doc.BatchDoc; +//import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +//import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +//import com.eactive.eai.common.property.PropManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public class ItmsSmsUtil { +// +// public static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT); +// +// public static final String SYSNOTIFYINFO = "SysNotifyInfo"; +// public static final String HOST = "itsm.host"; +// public static final String PORT = "itsm.port"; +// public static final String MSG_GB = "msg.gb"; +// public static final String MSG_DEL = "msg.del"; +// public static final String REQ_BY_GROUP = "req.group"; +// public static final String REQ_BY_TELNO = "req.telno"; +// public static final String REQ_APPL_CD = "req.appl.cd"; +// +// public static final String EAI_APPL_PREFIX = "eai.prefix"; +// public static final String DEFAULT_APPL_CD = "appl.cd"; +// public static final String CHECK_PERIOD = "check.period"; +// public static final String CHECK_DELAY = "check.delay"; +// +// public static final String EAI_SEND_YN = "eai.send.flag"; //업무팀에 보내고 나서 EAI 팀에도 보낼것인가? +// +// +// private ItmsSmsUtil(){ +// } +// +// public static void sendSMS( String reqGb, String reqCont, String msg ){ +// +// StringBuffer sb = new StringBuffer(); +// try { +// String del = PropManager.getInstance().getProperty(SYSNOTIFYINFO, MSG_DEL); +// //PEM메시지구분 인터페이스대상 식별 코드 PEM_INFO 8 +// sb.append(PropManager.getInstance().getProperty(SYSNOTIFYINFO, MSG_GB)); +// sb.append(del); +// +// sb.append(reqGb); // +// sb.append(del); +// +// if ( PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_BY_GROUP).equals(reqGb)){ +// String eaiApplCd = reqCont; +// if ( eaiApplCd == null || eaiApplCd.trim().equals("")){ +// eaiApplCd = PropManager.getInstance().getProperty(SYSNOTIFYINFO, DEFAULT_APPL_CD ); +// }else{ +// eaiApplCd = PropManager.getInstance().getProperty(SYSNOTIFYINFO, EAI_APPL_PREFIX) + eaiApplCd; +// } +// sb.append(eaiApplCd); +// }else{ +// sb.append(reqCont); +// } +// sb.append(del); +// +// //발생시간 이벤트발생시간 YYYYMMDDhhmmss 2011030310153000 +// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); +// String curDate = formatter.format(Calendar.getInstance().getTime()); +// sb.append(curDate); +// sb.append(del); +// +// String reqGroup = PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_APPL_CD ); +// sb.append(reqGroup); +// sb.append(del); +// +// sb.append(msg); +// +// sendToSocket( new String(sb)); +// +// } catch (Exception e) { +// logger.error("[ItmsSmsUtil][sendSMS]\n" + e.getMessage(),e); +// } +// return; +// } +// +// public static void sendToSocket( String msg ){ +// +// Socket socket = null; +// try { +// logger.debug( "SMS MESSAGE :" + msg ); +// +// if ( (socket = connect()) == null ) { +// return; +// } +// +// DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); +// dout.write(msg.getBytes()); +// +// +// } catch (Exception e) { +// logger.error("[ItmsSmsUtil][sendSMS]\n" + e.getMessage(),e); +// return; +// } finally { +// if ( socket != null ){ +// try { +// socket.close(); +// } catch (Exception e) {} +// } +// socket = null; +// } +// return; +// } +// +// private static Socket connect() throws Exception{ +// +// String ipAdress = PropManager.getInstance().getProperty(SYSNOTIFYINFO, HOST); +// if (ipAdress == null) +// throw new Exception("'SMS서버 IP정보' 프라퍼티가 없습니다. (PropGroupName:"+ SYSNOTIFYINFO +", PropName:"+ HOST +")"); +// +// String port = PropManager.getInstance().getProperty(SYSNOTIFYINFO, PORT); +// if (port == null) +// throw new Exception("'SMS서버 PORT정보' 프라퍼티가 없습니다. (PropGroupName:"+ SYSNOTIFYINFO +", PropName:"+ PORT +")"); +// int nPortNum = -1; +// try { +// nPortNum = Integer.parseInt(port); +// +// } catch (Exception ex) { +// String errMsg = "소켓 포트 정보가 잘못되었습니다. (PortNo:{" + port + "})"; +// throw new Exception(errMsg); +// } +// +// return socketInit(ipAdress, nPortNum); +// } +// +// private static Socket socketInit(String remoteIP, int remotePort) throws Exception +// { +// try { +// return new Socket(remoteIP, remotePort); +// } catch (Exception ex) { +// throw new Exception( "Socket 연결 에러 (IP:"+ remoteIP + ", Port:" + remotePort + ")," + ex.getMessage()); +// } +// } +// +// public static void sendSMS(BatchDoc batchDoc){ +// +// String errMsg = batchDoc.getBatchMsg().getBody().getErrorMsg(); +// CodeMessageVO vo = null; +// CodeMessageVO nvo = null; +// +// for ( int inx=0; inx < errMsg.length()-12;inx++){ +// if ( ( vo = CodeMessageManager.getInstance().getMessageVO(errMsg.substring(inx, inx+12))) != null ){ +// try { +// nvo = vo; +// } catch (Exception e) {} +// } +// } +// +// String message = "[송신실패]"; +// if ( "R".equals(batchDoc.getBatchMsg().getHeader().getProcessType().substring(1,2))){ +// message = "[수신실패]"; +// } +// message = message + "파일명:" + batchDoc.getBatchMsg().getHeader().getBizCode() +// + ",업무명:" + batchDoc.getBatchMsg().getHeader().getProcessName() +// + ",기관명:" + batchDoc.getBatchMsg().getHeader().getInstitutionName(); +// if ( nvo != null ) { +// message = message + "," + nvo.getMsgEtc(); +// } +// +// String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +//// String organCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); +// BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd( procCode, bizCode ); +// String applCd = ""; +// if ( jvo != null ){ +// applCd = jvo.getUapplCd(); +// } +// sendSMS( PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_BY_GROUP), applCd, message); +// +// // 업무팀이 세팅 되어 있으면 EAI에도 한번 더 보낸다. +// if (applCd != null && !applCd.trim().equals("")){ +// try { +// if (!PropManager.getInstance().getProperty(SYSNOTIFYINFO, EAI_SEND_YN).trim().equals("")){ +// sendSMS( PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_BY_GROUP), "", message); +// } +// } catch (Exception e) {} // 에러 무시 +// } +// +//// // 이제 대외 기관에도 보내 보자. +//// try { +//// OutsideVO ovo = OutsideManager.getInstance().getOutsideInfo(procCode, organCode); +//// if ( ovo.getSMSDpstCnsntYn().equals("1") ){ +//// String [] telnos = ovo.getOsidInstiTelno().split(","); +//// for (int i = 0; i < telnos.length; i++) { +//// String telno = telnos[i]; +//// sendSMS( PropManager.getInstance().getProperty(SMSINFO, REQ_BY_TELNO), telno, message); +//// } +//// } +//// } catch (Exception e) {} +// +// +// } +// +//} diff --git a/src/com/eactive/eai/batch/common/LogUtil.java b/src/com/eactive/eai/batch/common/LogUtil.java new file mode 100644 index 0000000..7b308f2 --- /dev/null +++ b/src/com/eactive/eai/batch/common/LogUtil.java @@ -0,0 +1,93 @@ +package com.eactive.eai.batch.common; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.logger.LogManager; + + +/** + * 1. 기능: JPD 및 Class에서 로깅을 위하여 호출하는 프로그램 + * - LogUtil에서는 다음과 같은 태그로 각 로그를 구분한다. + * S: 시작로글 + * C: 진행중인 로글 + * E: 에러 종료 로그 + * T: 정상 종료 로그 + * - 본 프로그램에서는 호출된 프로그램으로부터 값을 추출하여 적절한 태그를 추가한 다음 + * LogSender 프로그램을 호출한다. + * + * 2. 주의사항: LogUtil에서는 LogSender JPD에 연결이 안될 경우 별도의 로깅은 하지 않는다. + * 다만, File로 로깅 처리를 하도록 한다. + */ +public class LogUtil +{ + + /** + * 1.기능: LogUtil에서 실제 LogSender에 연결하는 메소드 + */ + + /* ============================================================================ + * 아래의 메소드는 EAIBatchMessageDocument를 입력으로 받는 메소드 + * - 최초 로그 생성시: setStartLog(BatchDoc) + * - 진행중인 로그: setLog(BatchDoc) + * - 에러로그: setLog(BatchDoc, ErrorMsg) + * - 종료로그: setEndLog(BatchDoc) + ============================================================================ */ + + /** + * 1.기능: Log를 처음 만드는 프로그램에서 호출하는 Log 생성 메소드 + */ + public static void setStartLog(BatchDoc doc) throws Exception + { + LogManager.getInstance().setLogStart(doc); + } + + /** + * 1.기능: 진행중인 로그를 저장하는 메소드 + */ + public static void setLog(BatchDoc doc) throws Exception + { + LogManager.getInstance().setLogStage(doc); + } + + /** + * 1.기능: 에러 로그를 저장하는 메소드 + */ + public static void setEndLog(BatchDoc doc) throws Exception + { + LogManager.getInstance().setLogEnd(doc); + } + + /** + * 1.기능: 에러 로그를 저장하는 메소드 + */ + public static void setErrorLog(BatchDoc doc, String errMsg) throws Exception + { + LogManager.getInstance().setLogError(doc, errMsg); + } + + /** + * 1.기능: 사용자중지 로그를 저장하는 메소드 + */ + public static void setCancelLog(BatchDoc doc, String errMsg) throws Exception + { + LogManager.getInstance().setLogCancel(doc, errMsg); + } + + /** + * 1.기능: 단계 진행중 로그 Master의 필드가 결정되는 경우 로그 Master update + */ + public static void updateLogMaster(BatchDoc doc) throws Exception + { + LogManager.getInstance().updateLogMaster(doc); + } + + public static void setLogFileStart(BatchDoc doc) throws Exception + { + LogManager.getInstance().setLogFileStart(doc); + } + + public static void setLogFileEnd(BatchDoc doc) throws Exception + { + LogManager.getInstance().setLogFileEnd(doc); + } +} + diff --git a/src/com/eactive/eai/batch/common/LoggingUtil.java b/src/com/eactive/eai/batch/common/LoggingUtil.java new file mode 100644 index 0000000..62dc71f --- /dev/null +++ b/src/com/eactive/eai/batch/common/LoggingUtil.java @@ -0,0 +1,198 @@ +package com.eactive.eai.batch.common; + + +public class LoggingUtil { + public static final char SPACE = ' '; + + public static final char ZERO = '0'; + + public static final String EMPTY_STRING = ""; + + public static final String EMPTY_STRING_ARRAY[] = new String[0]; + + private static final char[] HEX_CHAR_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + + /** + * BYTE ARRAY값을 HEXA STRING으로 변환하여 String을 리턴한다. + * @param abyte + * @return + */ + public static String byte2Hex(byte[] abyte) { + StringBuffer buf = new StringBuffer(); + int len = abyte.length; + + int high = 0; + int low = 0; + for (int i = 0; i < len; i++) { + high = ((abyte[i] & 0xf0) >> 4); + low = (abyte[i] & 0x0f); + buf.append(HEX_CHAR_ARRAY[high]); + buf.append(HEX_CHAR_ARRAY[low]); + } + return buf.toString(); + } + + /** + * 주어진 String값을 주어진 길이많큼 Padding/Trim한다. + * @param svalue - 입력스트링 + * @param isRightJustify - true이면 RIGHT JUSTIFY, false이면 LEFT JUSTIFY + * @param padding - Padding 문자 + * @param length - 리턴할 스트링의 바이트수 + * @return 포맷팅된 String결과 + */ + public static String stringFormat(String svalue, boolean isRightJustify, char padding, int length) { + if ( svalue == null ) return svalue; + + StringBuffer mpad = new StringBuffer(); + StringBuffer fmtStr = new StringBuffer(); + + String tvalue = svalue; + int pLength = 0; + + pLength = length - svalue.getBytes().length; + + if (pLength == 0) + return svalue; + else if ( pLength < 0) { + byte[] abytes = null; + if (isRightJustify) { + abytes = (new String( svalue.getBytes(), -(pLength), length)).getBytes(); + } else { + abytes = (new String( svalue.getBytes(), 0, length)).getBytes(); + } + + if ( abytes.length == length ) { + return new String( abytes ); + } else { + tvalue = new String( abytes ); + pLength = length - tvalue.length(); + } + } + + for(int i =0; i < pLength ; i++) { + mpad.append( padding ); + } + + if ( isRightJustify ) { + return fmtStr.append(mpad).append(tvalue).toString(); + } else { + return fmtStr.append(tvalue).append(mpad).toString(); + } + } + /** + * 송수신전문에 대한 DUMP를 프린트할 수 있는 포맷으로 변환하여 String Array로 리턴한다. + * @param bytes + * @return + */ + public static String[] makeDumpFormat(byte[] bytes) { + if (bytes == null || bytes.length == 0) + return EMPTY_STRING_ARRAY; + + String[] dumps = new String[bytes.length / 16 + ((bytes.length % 16) == 0 ? 4 : 5)]; + dumps[0] = " +----------------------------------------------------------------------+"; + dumps[1] = " | Offset | 0 1 2 3 4 5 6 7 8 9 A B C D E F | U S E R D A T A |"; + dumps[2] = " |----------+----------------------------------------+------------------|"; + dumps[dumps.length - 1] = " +----------------------------------------------------------------------+"; + + int len = 0; + byte PERIOD = 0x2E; + char aChar = ' '; + boolean isDBCS = false; + boolean isHalfDBCS = false; + + + for (int i = 3; i < dumps.length - 1; i++) { + len = ( ((bytes.length - (i - 2) * 16) >= 0) ? 16 : (bytes.length - (i - 3)*16) ); + byte[] buf = new byte[len]; + System.arraycopy( bytes, (i-3)*16, buf, 0, len ); + StringBuffer sb = new StringBuffer(); + + sb.append(" | ").append( stringFormat( new String( Integer.toHexString((i-3)*16) ).toUpperCase(), true, ZERO, 8) ).append(" | "); + + String hexStr = byte2Hex( buf ); + StringBuffer fmtStr = new StringBuffer(); + + int k = hexStr.length()/8 + ((hexStr.length() % 8) == 0 ? 0 : 1); + for (int j=0; j < k ; j++) { + int l = ((hexStr.length() - (j+1)*8 ) >= 0 ? 8 : (hexStr.length() - j*8 )); + fmtStr.append( hexStr.substring(j*8, j*8 + l ) ).append(" "); + } + + sb.append( stringFormat(fmtStr.toString(), false, SPACE, 39) ).append("| "); + + k = 0; + // 한글 및 특수문자가 깨지게 표시되는 것 을 방지한다. + for ( int j=0; j < len; j++) { + if ( buf[j] >> 7 == 0 ) { + // Single Byte Character + if ( isDBCS ) { + isDBCS = false; + if ( k != 0 && ((k % 2) == 1 )) { + buf[j - 1] = PERIOD; + } + } + aChar = (char)buf[j]; + if ( Character.isWhitespace( aChar ) || Character.isISOControl( aChar ) || buf[j] == 0 ) { + buf[j] = PERIOD; + } + continue; + } + // Double Bytes Character. + if ( !isDBCS ) isDBCS = true; + if ( j == 0 && isHalfDBCS ) { + buf[j] = PERIOD; + isDBCS = false; + continue; + } + // To check the DBCS pairwise + k++; + } + if ( isDBCS && ((k%2)==1) ) { + buf[ len -1 ] = PERIOD; + isHalfDBCS = true; + } else { + isHalfDBCS = false; + } + + dumps[i] = sb.append( stringFormat(new String(buf), false, SPACE, 16) ).append(" |").toString(); + } + return dumps; + + } + + + public static String hexDump(byte[] message) { + String[] dumpMsg = makeDumpFormat(message); + StringBuffer dump = new StringBuffer(); + dump.append("byte[size=" + message.length + "]"); + dump.append("\n"); + for (int i = 0; i < dumpMsg.length; i++) { + dump.append(dumpMsg[i]); + if (i < dumpMsg.length - 1) + dump.append("\n"); + } + + return dump.toString(); + } + + /** + * byte[] 길이로 분리하여 출력한다. raw data 확인용 + * @param message 송수신한 메시지 + * @return Ascii로 변환한 문자열 + */ + public static String asciiDump(byte[] message) { + int max = 140; + + StringBuffer result = new StringBuffer().append(message.length).append(" bytes").append(System.lineSeparator()); + int i = 0; + for (i = 0; i < (message.length) / max; i++) { + result.append(new String(message, i * max, max)).append(System.lineSeparator()); + } + //남는 부분 처리 + if (message.length > i * max) { + result.append(new String(message, i * max, message.length - (i * max))).append(System.lineSeparator()); + } + return result.toString(); + } +} + diff --git a/src/com/eactive/eai/batch/common/OSUtil.java b/src/com/eactive/eai/batch/common/OSUtil.java new file mode 100644 index 0000000..67b1cca --- /dev/null +++ b/src/com/eactive/eai/batch/common/OSUtil.java @@ -0,0 +1,52 @@ +package com.eactive.eai.batch.common; + +import java.io.IOException; + +public class OSUtil +{ + /** Operating system state flag for error. */ + private static final int INIT_PROBLEM = -1; + /** Operating system state flag for neither Unix nor Windows. */ + private static final int OTHER = 0; + /** Operating system state flag for Windows. */ + private static final int WINDOWS = 1; + /** Operating system state flag for Unix. */ + private static final int UNIX = 2; + + + public static int getOSType() + { + int os = OTHER; + try { + String osName = System.getProperty("os.name"); + if (osName == null) { + throw new IOException("os.name not found"); + } + osName = osName.toLowerCase(); + // match + if (osName.indexOf("windows") != -1) { + os = WINDOWS; + } else if (osName.indexOf("linux") != -1 + || osName.indexOf("sun os") != -1 + || osName.indexOf("sunos") != -1 + || osName.indexOf("solaris") != -1 + || osName.indexOf("mpe/ix") != -1 + || osName.indexOf("hp-ux") != -1 + || osName.indexOf("aix") != -1 + || osName.indexOf("freebsd") != -1 + || osName.indexOf("irix") != -1 + || osName.indexOf("digital unix") != -1 + || osName.indexOf("unix") != -1 + || osName.indexOf("mac os x") != -1) { + os = UNIX; + } else { + os = OTHER; + } + + } catch (Exception ex) { + os = INIT_PROBLEM; + } + return os; + } + +} diff --git a/src/com/eactive/eai/batch/common/SMSManager.java b/src/com/eactive/eai/batch/common/SMSManager.java new file mode 100644 index 0000000..01c7d84 --- /dev/null +++ b/src/com/eactive/eai/batch/common/SMSManager.java @@ -0,0 +1,151 @@ +package com.eactive.eai.batch.common; + +import java.io.DataOutputStream; +import java.net.InetAddress; +import java.net.Socket; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.Calendar; + +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + +public class SMSManager { + + private static SMSManager instance = new SMSManager(); + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public static SMSManager getInstance() { + return instance; + } + private Socket socket = null; + private DataOutputStream dout = null; + + public static final String SMSINFO = "SMSInfo"; + public static final String IP = "ip"; + public static final String PORT = "port"; + public static final String SENDER = "sender"; + public static final String PRIORITY = "priority"; + + + + private SMSManager(){ + } + + public boolean sendSMS( String telno, String msg ){ + + if ( socket != null){ + return false; + } + + try { + if ( !connect()) { + return false; + } + + dout = new DataOutputStream(socket.getOutputStream()); + byte[] reqData = new byte[137]; + for ( int inx=0; inx < reqData.length; inx++){ + reqData[inx] = ' '; + } + +// SEND_REQUEST(문자전송요청) +// "01199714977 01199756577 가나다라마바사가나다라마바사가나다라마바사가나다라마바사가나다라마바사가나다라마 kbdbsvr1 120061107233027 " +// 받는이번호 (자릿수 13Byte Fix, 형태 “01199714977 “, Left Shift , space filling) +// 보낸이번호 (자릿수 13Byte Fix, 형태 “01199714977 “, Left Shift , space filling) +// 메시지 (자릿수 80Byte Fix, 형태:문자형, Left Shift , space filling) +// 호스트 명 (자릿수:15Byte Fix, 형태 “kbdbsvr1 “, Left Shift , space filling) +// 우선구분 (자릿수:1Byte Fix, 형태:0-보통,1-긴급,2-우선) +// 전송일시 (자릿수:14Byte Fix, 형태: yyyyMMddHHmmss(24h)) +// 총 137 Byte Fix + + + // 받는이 전화 번호 + System.arraycopy( telno.getBytes(), 0, reqData, 0, Math.min(telno.getBytes().length, 13)); + + // 보내는 사람 전화 번호 : Rule Property 에서 읽어 온다. + String sender = PropManager.getInstance().getProperty(SMSINFO, SENDER); + if (sender != null){ + System.arraycopy( sender.getBytes(), 0, reqData, 13, Math.min(sender.getBytes().length, 13)); + } + + // 메시지 + System.arraycopy( msg.getBytes(), 0, reqData, 26, Math.min(msg.getBytes().length, 80)); + + // 호스트명 + String hostname = InetAddress.getLocalHost().getHostName(); + System.arraycopy( hostname.getBytes(), 0, reqData, 106, Math.min(hostname.getBytes().length, 15)); + + // 우선구분 0을 디폴트로... + String priority = PropManager.getInstance().getProperty(SMSINFO, PRIORITY); + if ( priority == null ) priority = "0"; + System.arraycopy( priority.getBytes(), 0, reqData, 121, Math.min(priority.getBytes().length, 1)); + + // 전송일시 + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); + String curDate = formatter.format(Calendar.getInstance().getTime()); + System.arraycopy( curDate.getBytes(), 0, reqData, 122, 14); + + logger.debug( "SMS MESSAGE :" + new String (reqData)); + dout.write(reqData); + + + } catch (Exception e) { + logger.error( e.getMessage(), e); + return false; + } finally { + if ( socket != null ){ + try { + socket.close(); + } catch (Exception e) {} + } + socket = null; + } + return true; + } + + + private boolean connect() throws Exception{ + + String ipAdress = PropManager.getInstance().getProperty(SMSINFO, IP); + if (ipAdress == null) + throw new Exception("'SMS서버 IP정보' 프라퍼티가 없습니다. (PropGroupName:"+ SMSINFO +", PropName:"+ IP +")"); + + String port = PropManager.getInstance().getProperty(SMSINFO, PORT); + if (port == null) + throw new Exception("'SMS서버 PORT정보' 프라퍼티가 없습니다. (PropGroupName:"+ SMSINFO +", PropName:"+ PORT +")"); + int nPortNum = -1; + try { + nPortNum = Integer.parseInt(port); + + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC002", new String[] {port}); + throw new Exception(errMsg); + } + + socket = socketInit(ipAdress, nPortNum); + if (socket == null) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJC003"); + throw new Exception(errMsg); + } + + return true; + } + + private Socket socketInit(String remoteIP, int remotePort) throws Exception + { + try { + return new Socket(remoteIP, remotePort); + + } catch (UnknownHostException ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC001", new String[] {remoteIP, Integer.toString(remotePort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다. + + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC002", new String[] {remoteIP, Integer.toString(remotePort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), I/O Exception이 발생했습니다. + } + } + +} diff --git a/src/com/eactive/eai/batch/common/StringUtil.java b/src/com/eactive/eai/batch/common/StringUtil.java new file mode 100644 index 0000000..f03e165 --- /dev/null +++ b/src/com/eactive/eai/batch/common/StringUtil.java @@ -0,0 +1,487 @@ +package com.eactive.eai.batch.common; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.text.DecimalFormat; +import java.util.StringTokenizer; + +public class StringUtil +{ + /** + * 1. 기능 : 주어진 문자열이 숫자로만 구성되어 있는지 확인한다. + * 공백이 있으면 false를 반환한다. + * 2. 처리 개요 : + * - char값이 48에서 57사이이면 숫자이다. + * + * @param str 문자열 + * @return 문자열이 모두 숫자로만 이루어진경우 true + */ + public static boolean isNumeric(String str) { + if (str==null || str.equals("")) return false; + + for (int i=0; i 57) return false; + } + return true; + } + + /** + * 1. 기능 : 주어진 문자열이 문자로만 구성되어 있는지 확인한다. + * 공백은 true를 반환한다. + * 2. 처리 개요 : + * - 입력된 String을 대문자로 모두 변환한다. (알파벳은 65(A)에서 90(Z)까지이다.) + * - char값이 65이상이면 문자이다. + * + * @param str 문자열 + * @return 문자열이 모두 문자로만 이루어진경우 true + */ + public static boolean isAlpha(String str) { + if (str==null || str.equals("")) return true; + + for (int i=0; i= 0) + { + stringbuffer.append(s.substring(0, i)).append(s2); + s = s.substring(i + s1.length()); + } + stringbuffer.append(s); + return stringbuffer.toString(); + } + + public static String nvl(String str) { + return nvl(str, ""); + } + + public static String nvl(String str, String defaultValue) { + if (str == null || str.equals("")) return defaultValue; + return str; + } + + public static String nvlTrim(String str) { + return nvlTrim(str, ""); + } + + public static String nvlTrim(String str, String defaultValue) { + if (str == null || str.trim().equals("")) return defaultValue; + return str.trim(); + } + + /** + *
+	 * 문자열을 주어진 포맷으로 일치시킨다.
+	 * 용례) matchFormat("20010101", "####/##/##") -> "2001/01/01"
+	 *       matchFormat("12345678", "##/## : ##") -> "12/34 : 56"
+	 * 
+ * @param str 원본문자열 + * @param format 결과 포맷형태('#'문자에 원본 문자가 위치, 그외 문자는 그대로 표시) + * @return 포맷으로 변환된 문자열 + */ + public static String matchFormat(String str, String format) { + if(str == null || str.length() == 0 ) return str; + int len = format.length(); + char[] result = new char[len]; + for(int i=0,j=0; i=0; i--) { + if (byteArr[i]>0) break; + crashFlag = !crashFlag; + } + return crashFlag; + } + + public static String toCurFormat(double arg) { + return new DecimalFormat("###,##0").format(arg); + } + + public static String getDirDelimiter(String path) { + return path.indexOf("/") >=0? "/" : //unix + path.indexOf("\\")>=0? "\\" : //windows + path.indexOf(".") >=0? "." : //host + "/"; //default(unix) + } + + public static String getRandomDigit(long digitLen) { + if (digitLen <= 0) return ""; + + String format = ""; + for (int i=0; i 0 ){ + newStr = new byte[len]; + System.arraycopy( val,0,newStr,0,len); + } + + return newStr == null ? null : new String(newStr);// 20250910 npe + } + + /** + * 1. 기능 : 주어진 문자열에서 지정된 문자를 잘라낸다. + * 2. 처리 개요 : + * - 주어진 문자열에서 끝에서 부터 지정된 문자를 반복되는 만큼 잘라낸다. + * 3. 주의사항 + * + * @param inStr - 입력 문자열 + * @param inChar - 잘라낼 문자 + * @return 결과문자열 + */ + public static byte[] rtrimChar( byte[] buf, char inChar){ + int len = buf.length; + + while ((0 < len) && ( (buf[len - 1] == inChar) || buf[len -1] == '\r' || buf[len -1] == '\n' )) { + len--; + } + if ( len > 0 ){ + byte[] newBuf = new byte[len]; + System.arraycopy( buf, 0, newBuf, 0, len); + return newBuf; + } else { + return null; + } + } + + /** + * 1. 기능 : 주어진 스트링에 대해 offset 만큼의 byte 를 잘라내어 리턴한다. + * 2. 처리 개요 : + * - substring("1234",2) --> "34" + * 3. 주의사항 + * + * @param inStr String Source + * @param offset offset + * @return String + */ + public static String substring( String inStr, int offset){ + int len = inStr.getBytes().length - offset; + byte newStr[] = new byte[len]; + System.arraycopy( inStr.getBytes(), offset, newStr, 0, len); + return new String (newStr); + } + + /** + * 1. 기능 : 에러대신 Zero String을 리턴하는 substring method + * 2. 처리 개요 : + * - getSubstring("1234",4,2) --> "" + * 3. 주의사항 + * + * @param Str String Source + * @param start start index. + * @param len length + * @return String + */ + public static String getSubstring(String Str, int start, int len) + { + if (Str == null) return ""; + int slen = Str.length(); + + if ((slen < 1) || (start<0) || (len < 1)) return ""; + + if ((slen-1) < start) return ""; + + if (slen < (start+len)) { + return Str.substring(start,Str.length()); + } + else { + return Str.substring(start,start+len); + } + } + + /** + * 1. 기능 : 주어진 스트링에 대해 offset 만큼의 byte 를 잘라내어 리턴한다. + * 2. 처리 개요 : + * - substring("1234",2) --> "34" + * 3. 주의사항 + * + * @param inStr String Source + * @param offset offset + * @return String + */ + public static byte[] split( byte[] str, int interval, byte[] del){ + int offset1 = 0; + int offset2 = 0; + int len = str.length; + int delLen = del.length; + int newLen = len + ( ( ( ( len - 1)/interval ) + 1 )* delLen ) ; + byte[] newByte = new byte[newLen]; + while ( offset1 < len - interval ){ + System.arraycopy( str, offset1, newByte, offset2, interval); + offset1 += interval; + offset2 += interval; + System.arraycopy( del, 0, newByte, offset2, delLen); + offset2 += delLen; + } + System.arraycopy( str, offset1, newByte, offset2, len - offset1); + offset2 += len - offset1; + System.arraycopy( del, 0, newByte, offset2, delLen); + + return newByte; + } + +// public static String getCheckFileName( String realDirPath ){ +// return realToRootDir( realDirPath ); +// PropManager pmanager = PropManager.getInstance(); +// String ext = ".chk"; +// if ( realDirPath == null || realDirPath.equals("")) +// return realDirPath; +// try { +// String recvReal = BatchDirUtil.getResponseRealDir(); +// ext = pmanager.getProperty("CBSDirInfo", "chk.ext"); +// if (realDirPath.indexOf(recvReal) > -1 ) +// return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseArchDir()) + ext; +// +// } catch (Exception e) {} +// return realDirPath + ext ; +// } + + public static String realToRootDir( String realDirPath ){ + if ( realDirPath == null || realDirPath.equals("")) + return realDirPath; + try { + String recvReal = BatchDirUtil.getResponseRealDir(); + if (realDirPath.indexOf(recvReal) > -1 ) + return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseRootDir() ); + } catch (Exception e) { + return null; + } + return null; + } + + + public static String realToArchDir( String realDirPath ){ + if ( realDirPath == null || realDirPath.equals("")) + return realDirPath; + try { +// String sendReal = BatchDirUtil.getRequestRealDir(); + String recvReal = BatchDirUtil.getResponseRealDir(); +// if ( realDirPath.indexOf(sendReal) > -1 ) +// return replaceStr( realDirPath, sendReal, BatchDirUtil.getResponseArchDir() ); +// else + if (realDirPath.indexOf(recvReal) > -1 ) + return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseArchDir() ); + } catch (Exception e) { + return null; + } + return null; + } + +// public static String rootToArchDir( String rootDirPath ){ +// if ( rootDirPath == null || rootDirPath.equals("")) +// return rootDirPath; +// try { +// String recvRoot = BatchDirUtil.getResponseRootDir(); +// if ( rootDirPath.indexOf(recvRoot) > -1 ) +// return replaceStr( rootDirPath, recvRoot, BatchDirUtil.getResponseArchDir() ); +// } catch (Exception e) { +// return null; +// } +// return rootDirPath; +// } + +// public static String rootToNasDir( String rootDirPath ){ +// if ( rootDirPath == null || rootDirPath.equals("")) +// return rootDirPath; +// try { +// String recvRoot = BatchDirUtil.getResponseRootDir(); +// if ( rootDirPath.indexOf(recvRoot) > -1 ) +// return replaceStr( rootDirPath, recvRoot, BatchDirUtil.getResponseNasDir() ); +// } catch (Exception e) { +// return null; +// } +// return rootDirPath; +// } + +// public static String rootToChkDir( String rootDirPath ){ +// if ( rootDirPath == null || rootDirPath.equals("")) +// return rootDirPath; +// try { +// String recvRoot = BatchDirUtil.getResponseRootDir(); +// if ( rootDirPath.indexOf(recvRoot) > -1 ) +// return replaceStr( rootDirPath, recvRoot, BatchDirUtil.getResponseChkDir() ); +// } catch (Exception e) { +// return null; +// } +// return rootDirPath; +// } + + public static String realToErrorDir( String realDirPath ){ + if ( realDirPath == null || realDirPath.equals("")) + return realDirPath; + try { +// String sendReal = BatchDirUtil.getRequestRealDir(); + String recvReal = BatchDirUtil.getResponseRealDir(); +// if ( realDirPath.indexOf(sendReal) > -1 ) +// return replaceStr( realDirPath, sendReal, BatchDirUtil.getResponseErrorDir() ); +// else + if (realDirPath.indexOf(recvReal) > -1 ) + return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseErrorDir() ); + } catch (Exception e) { + return null; + } + return null; + } + + public static long getTotRecCountFromHeader( String header ){ + long cnt = -1; + try { + cnt = Long.parseLong(header.substring(27, 37)); + } catch (Exception e) { +// e.printStackTrace(); + } + return cnt; + } + + public static String getBaseDateFromHeader( String header ){ + String baseDate = null; + try { + baseDate = header.substring(19, 27); + } catch (Exception e) { + baseDate = CalendarUtil.getCurrentTimeNoDash().substring(0,8); + } + return baseDate; + } + + public static String getDump(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString(); + } + + +} diff --git a/src/com/eactive/eai/batch/doc/BatchDoc.java b/src/com/eactive/eai/batch/doc/BatchDoc.java new file mode 100644 index 0000000..2ca3c03 --- /dev/null +++ b/src/com/eactive/eai/batch/doc/BatchDoc.java @@ -0,0 +1,181 @@ +package com.eactive.eai.batch.doc; + +import java.io.BufferedOutputStream; +import java.io.OutputStream; +import java.io.Serializable; + +import com.eactive.eai.common.util.Logger; +import com.jcraft.jsch.ChannelSftp; + +public class BatchDoc implements Serializable{ + + private static final long serialVersionUID = 1L; + BatchMsg batchMsg; + + /*** sFTP전송 종료 */ + private ChannelSftp sftpChannel; + + /*** 사용자 취소인 경우 true */ + private boolean userCancel; + + /** 기관별 로깅 */ + Logger logger; + + /**/ + private Object bos; + private long currIODataByte; + + public ChannelSftp getSftpChannel() { + return sftpChannel; + } + + public void setSftpChannel(ChannelSftp sftpChannel) { + this.sftpChannel = sftpChannel; + } + + public boolean isUserCancel() { + return userCancel; + } + + public void setUserCancel(boolean userCancel) { + this.userCancel = userCancel; + } + + public BatchMsg getBatchMsg() { + return batchMsg; + } + + public void setBatchMsg(BatchMsg batchMsg) { + this.batchMsg = batchMsg; + } + + public BatchMsg addNewBatchMsg(){ + batchMsg = new BatchMsg(); + return batchMsg; + } + + @Override + public String toString() { + return batchMsg.toString(); + } + + public class BatchMsg implements Serializable + { + private static final long serialVersionUID = 1L; + Header header; + Body body; + Phaseinfo phaseinfo; + String telegramHeader; + String telegramBody; + String fileHeader; + String fileTrailer; + + public void addNewHeader(){ + header = new Header(); + } + + public void addNewBody(){ + body = new Body(); + } + + public void addNewPhaseinfo(){ + phaseinfo = new Phaseinfo(); + } + + public Header getHeader() { + return header; + } + public void setHeader(Header header) { + this.header = header; + } + public Body getBody() { + return body; + } + public void setBody(Body body) { + this.body = body; + } + public Phaseinfo getPhaseinfo() { + return phaseinfo; + } + public void setPhaseinfo(Phaseinfo phaseinfo) { + this.phaseinfo = phaseinfo; + } + public String getTelegramHeader() { + return telegramHeader; + } + public void setTelegramHeader(String telegramHeader) { + this.telegramHeader = telegramHeader; + } + public String getTelegramBody() { + return telegramBody; + } + public void setTelegramBody(String telegramBody) { + this.telegramBody = telegramBody; + } + public String getFileHeader() { + return fileHeader; + } + public void setFileHeader(String fileHeader) { + this.fileHeader = fileHeader; + } + public String getFileTrailer() { + return fileTrailer; + } + public void setFileTrailer(String fileTrailer) { + this.fileTrailer = fileTrailer; + } + + @Override + public String toString() { + return "[BatchMsg]\n" + header + body + phaseinfo + "\nlogger=" + (logger == null ? "null" : logger.getName()) + + "\ntelegramHeader=" + telegramHeader + "\ntelegramBody=" + telegramBody + + "\nfileHeader=" + fileHeader + "\nfileTrailer=" + + fileTrailer + "]"; + } + } + + /** + * 로거가 없을 경우 기본 로거를 ElinkLogger.LOGGER_DEFAULT로 얻는다. + */ + public Logger getLogger() { + if (logger == null) { + logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.error("inst logger is null {}", batchMsg.toString()); + } + return logger; + } + + public void setLogger(Logger logger) { + this.logger = logger; + } + + /** + * 로거가 없을 경우 기본 로거를 loggerAdapter로 얻는다. + * @param loggerAdapter 로거가 없을 경우 기본 로거 + * @return + */ + public Logger getLogger(String loggerAdapter) { + if (logger == null) { + logger = Logger.getLogger(loggerAdapter); + logger.error("inst logger is null {}", batchMsg.toString()); + } + return logger; + } + + public void setIOStream(Object bos) { + this.bos = bos; + } + + public Object getIOStream() { + return this.bos; + } + + public void setCurrIODataByte(long currIODataByte) { + this.currIODataByte = currIODataByte; + } + + public long getCurrIODataByte() { + return this.currIODataByte ; + } + +} diff --git a/src/com/eactive/eai/batch/doc/Body.java b/src/com/eactive/eai/batch/doc/Body.java new file mode 100644 index 0000000..38ec50f --- /dev/null +++ b/src/com/eactive/eai/batch/doc/Body.java @@ -0,0 +1,397 @@ +package com.eactive.eai.batch.doc; + +import java.io.Serializable; + + +public class Body implements Serializable +{ + private static final long serialVersionUID = 1L; + String subUUID ; + String subLayerCode ; + String wLIServerName ; + String portNo ; + int nodeCount ; + String flowPhaseCode ; + String lastPhaseCode ; + String nextPhaseCode ; + String phaseType ; + String lastPhaseType ; + String nextPhaseType ; + String sndMsgCode ; + String rcvMsgCode ; + String phaseStartTime ; + String phaseEndTime ; + String lastPhaseStartTime ; + String lastPhaseEndTime ; + String actionTag ; + String recallTag ; + String timeoutInterval ; + int retryCount ; + int blockNum ; + int seqNum ; + String missingNmField ; + int missingNmCount ; + long curFileSize ; + long recCnt ; + long curFileRecCnt ; + String lastResCode ; + int errorCode ; + String errorMsg ; + String recvedMsg ; + String sendSummary ; + byte[] sendBuffer ; + String instExt ; + String recvFld01 ; + String recvFld02 ; + String recvFld03 ; + String recvFld04 ; + String recvFld05 ; + String recvFld06 ; + String recvFld07 ; + String recvFld08 ; + String recvFld09 ; + String recvFld10 ; + + public String getSubUUID() { + return subUUID; + } + public void setSubUUID(String subUUID) { + this.subUUID = subUUID; + } + public String getSubLayerCode() { + return subLayerCode; + } + public void setSubLayerCode(String subLayerCode) { + this.subLayerCode = subLayerCode; + } + public String getWLIServerName() { + return wLIServerName; + } + public void setWLIServerName(String wLIServerName) { + this.wLIServerName = wLIServerName; + } + public String getPortNo() { + return portNo; + } + public void setPortNo(String portNo) { + this.portNo = portNo; + } + public int getNodeCount() { + return nodeCount; + } + public void setNodeCount(int nodeCount) { + this.nodeCount = nodeCount; + } + public String getFlowPhaseCode() { + return flowPhaseCode; + } + public void setFlowPhaseCode(String flowPhaseCode) { + this.flowPhaseCode = flowPhaseCode; + } + public String getLastPhaseCode() { + return lastPhaseCode; + } + public void setLastPhaseCode(String lastPhaseCode) { + this.lastPhaseCode = lastPhaseCode; + } + public String getNextPhaseCode() { + return nextPhaseCode; + } + public void setNextPhaseCode(String nextPhaseCode) { + this.nextPhaseCode = nextPhaseCode; + } + public String getPhaseType() { + return phaseType; + } + public void setPhaseType(String phaseType) { + this.phaseType = phaseType; + } + public String getLastPhaseType() { + return lastPhaseType; + } + public void setLastPhaseType(String lastPhaseType) { + this.lastPhaseType = lastPhaseType; + } + public String getNextPhaseType() { + return nextPhaseType; + } + public void setNextPhaseType(String nextPhaseType) { + this.nextPhaseType = nextPhaseType; + } + public String getSndMsgCode() { + return sndMsgCode; + } + public void setSndMsgCode(String sndMsgCode) { + this.sndMsgCode = sndMsgCode; + } + public String getRcvMsgCode() { + return rcvMsgCode; + } + public void setRcvMsgCode(String rcvMsgCode) { + this.rcvMsgCode = rcvMsgCode; + } + public String getPhaseStartTime() { + return phaseStartTime; + } + public void setPhaseStartTime(String phaseStartTime) { + this.phaseStartTime = phaseStartTime; + } + public String getPhaseEndTime() { + return phaseEndTime; + } + public void setPhaseEndTime(String phaseEndTime) { + this.phaseEndTime = phaseEndTime; + } + public String getLastPhaseStartTime() { + return lastPhaseStartTime; + } + public void setLastPhaseStartTime(String lastPhaseStartTime) { + this.lastPhaseStartTime = lastPhaseStartTime; + } + public String getLastPhaseEndTime() { + return lastPhaseEndTime; + } + public void setLastPhaseEndTime(String lastPhaseEndTime) { + this.lastPhaseEndTime = lastPhaseEndTime; + } + public String getActionTag() { + return actionTag; + } + public void setActionTag(String actionTag) { + this.actionTag = actionTag; + } + public String getRecallTag() { + return recallTag; + } + public void setRecallTag(String recallTag) { + this.recallTag = recallTag; + } + public String getTimeoutInterval() { + return timeoutInterval; + } + public void setTimeoutInterval(String timeoutInterval) { + this.timeoutInterval = timeoutInterval; + } + public int getRetryCount() { + return retryCount; + } + public void setRetryCount(int retryCount) { + this.retryCount = retryCount; + } + public int getBlockNum() { + return blockNum; + } + public void setBlockNum(int blockNum) { + this.blockNum = blockNum; + } + public int getSeqNum() { + return seqNum; + } + public void setSeqNum(int seqNum) { + this.seqNum = seqNum; + } + public String getMissingNmField() { + return missingNmField; + } + public void setMissingNmField(String missingNmField) { + this.missingNmField = missingNmField; + } + public int getMissingNmCount() { + return missingNmCount; + } + public void setMissingNmCount(int missingNmCount) { + this.missingNmCount = missingNmCount; + } + public long getCurFileSize() { + return curFileSize; + } + public void setCurFileSize(long curFileSize) { + this.curFileSize = curFileSize; + } + public long getRecCnt() { + return recCnt; + } + public void setRecCnt(long recCnt) { + this.recCnt = recCnt; + } + public long getCurFileRecCnt() { + return curFileRecCnt; + } + public void setCurFileRecCnt(long curFileRecCnt) { + this.curFileRecCnt = curFileRecCnt; + } + public String getLastResCode() { + return lastResCode; + } + public void setLastResCode(String lastResCode) { + this.lastResCode = lastResCode; + } + public int getErrorCode() { + return errorCode; + } + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + public String getErrorMsg() { + return errorMsg; + } + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + public String getRecvedMsg() { + return recvedMsg; + } + public void setRecvedMsg(String recvedMsg) { + this.recvedMsg = recvedMsg; + } + public String getSendSummary() { + return sendSummary; + } + public void setSendSummary(String sendSummary) { + this.sendSummary = sendSummary; + } + public byte[] getSendBuffer() { + return sendBuffer; + } + public void setSendBuffer(byte[] sendBuffer) { + this.sendBuffer = sendBuffer; + } + public String getInstExt() { + return instExt; + } + public void setInstExt(String instExt) { + this.instExt = instExt; + } + public String getRecvFld01() { + return recvFld01; + } + public void setRecvFld01(String recvFld01) { + this.recvFld01 = recvFld01; + } + public String getRecvFld02() { + return recvFld02; + } + public void setRecvFld02(String recvFld02) { + this.recvFld02 = recvFld02; + } + public String getRecvFld03() { + return recvFld03; + } + public void setRecvFld03(String recvFld03) { + this.recvFld03 = recvFld03; + } + public String getRecvFld04() { + return recvFld04; + } + public void setRecvFld04(String recvFld04) { + this.recvFld04 = recvFld04; + } + public String getRecvFld05() { + return recvFld05; + } + public void setRecvFld05(String recvFld05) { + this.recvFld05 = recvFld05; + } + public String getRecvFld06() { + return recvFld06; + } + public void setRecvFld06(String recvFld06) { + this.recvFld06 = recvFld06; + } + public String getRecvFld07() { + return recvFld07; + } + public void setRecvFld07(String recvFld07) { + this.recvFld07 = recvFld07; + } + public String getRecvFld08() { + return recvFld08; + } + public void setRecvFld08(String recvFld08) { + this.recvFld08 = recvFld08; + } + public String getRecvFld09() { + return recvFld09; + } + public void setRecvFld09(String recvFld09) { + this.recvFld09 = recvFld09; + } + public String getRecvFld10() { + return recvFld10; + } + public void setRecvFld10(String recvFld10) { + this.recvFld10 = recvFld10; + } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Body\nsubUUID:"); + builder.append(subUUID); + builder.append("\nsubLayerCode:"); + builder.append(subLayerCode); + builder.append("\nwLIServerName:"); + builder.append(wLIServerName); + builder.append("\nportNo:"); + builder.append(portNo); + builder.append("\nnodeCount:"); + builder.append(nodeCount); + builder.append("\nflowPhaseCode:"); + builder.append(flowPhaseCode); + builder.append("\nlastPhaseCode:"); + builder.append(lastPhaseCode); + builder.append("\nnextPhaseCode:"); + builder.append(nextPhaseCode); + builder.append("\nphaseType:"); + builder.append(phaseType); + builder.append("\nlastPhaseType:"); + builder.append(lastPhaseType); + builder.append("\nnextPhaseType:"); + builder.append(nextPhaseType); + builder.append("\nsndMsgCode:"); + builder.append(sndMsgCode); + builder.append("\nrcvMsgCode:"); + builder.append(rcvMsgCode); + builder.append("\nphaseStartTime:"); + builder.append(phaseStartTime); + builder.append("\nphaseEndTime:"); + builder.append(phaseEndTime); + builder.append("\nlastPhaseStartTime:"); + builder.append(lastPhaseStartTime); + builder.append("\nlastPhaseEndTime:"); + builder.append(lastPhaseEndTime); + builder.append("\nactionTag:"); + builder.append(actionTag); + builder.append("\nrecallTag:"); + builder.append(recallTag); + builder.append("\ntimeoutInterval:"); + builder.append(timeoutInterval); + builder.append("\nretryCount:"); + builder.append(retryCount); + builder.append("\nblockNum:"); + builder.append(blockNum); + builder.append("\nseqNum:"); + builder.append(seqNum); + builder.append("\nmissingNmField:"); + builder.append(missingNmField); + builder.append("\nmissingNmCount:"); + builder.append(missingNmCount); + builder.append("\ncurFileSize:"); + builder.append(curFileSize); + builder.append("\nrecCnt:"); + builder.append(recCnt); + builder.append("\nlastResCode:"); + builder.append(lastResCode); + builder.append("\nerrorCode:"); + builder.append(errorCode); + builder.append("\nerrorMsg:"); + builder.append(errorMsg); + builder.append("\nrecvedMsg:"); + builder.append(recvedMsg); + builder.append("\nsendSummary:"); + builder.append(sendSummary); + builder.append("\ninstExt:"); + builder.append(instExt); + return builder.toString(); + } + +} diff --git a/src/com/eactive/eai/batch/doc/Header.java b/src/com/eactive/eai/batch/doc/Header.java new file mode 100644 index 0000000..1324a7f --- /dev/null +++ b/src/com/eactive/eai/batch/doc/Header.java @@ -0,0 +1,400 @@ +package com.eactive.eai.batch.doc; + +import java.io.Serializable; + +public class Header implements Serializable +{ + + private static final long serialVersionUID = 1L; + String uUID ; + String tRX_ID ; + String layerCode ; + String processType ; + String processCode ; + String processName ; + String institutionCode ; + String institutionName ; +// String instituaionType ; + String jobCode ; + String scheduleCode ; + String fileName ; + String filePath ; + String userID ; + String userName ; + String userPassword ; + String scheduleSTime ; + String scheduleETime ; + String renamedFileName ; + String flowCode ; + String systemConnCode ; + long fileSize ; + int blockSize ; + int sequenceSize ; + String remoteIP ; + String port ; + String batchStartTime ; + String requestResponse ; + String sendRecv ; + String ruleCode ; + String ruleDesc ; +// String protocol ; + String bizCode ; + String fileErrorPath ; + int packetSize ; + int recLen ; + long totRecCnt ; + String baseDate ; + String eventScheduleID ; + String hdrInfoName ; + String recvUserID ; + String recvUserPassword ; + boolean reqSendRetryFlag ; + public String getUUID() { + return uUID; + } + public void setUUID(String uUID) { + this.uUID = uUID; + } + public String getTRXID() { + return tRX_ID; + } + public void setTRXID(String tRX_ID) { + this.tRX_ID = tRX_ID; + } + public String getLayerCode() { + return layerCode; + } + public void setLayerCode(String layerCode) { + this.layerCode = layerCode; + } + public String getProcessType() { + return processType; + } + public void setProcessType(String processType) { + this.processType = processType; + } + public String getProcessCode() { + return processCode; + } + public void setProcessCode(String processCode) { + this.processCode = processCode; + } + public String getProcessName() { + return processName; + } + public void setProcessName(String processName) { + this.processName = processName; + } + public String getInstitutionCode() { + return institutionCode; + } + public void setInstitutionCode(String institutionCode) { + this.institutionCode = institutionCode; + } + public String getInstitutionName() { + return institutionName; + } + public void setInstitutionName(String institutionName) { + this.institutionName = institutionName; + } +// public String getInstituaionType() { +// return instituaionType; +// } +// public void setInstituaionType(String instituaionType) { +// this.instituaionType = instituaionType; +// } + public String getJobCode() { + return jobCode; + } + public void setJobCode(String jobCode) { + this.jobCode = jobCode; + } + public String getScheduleCode() { + return scheduleCode; + } + public void setScheduleCode(String scheduleCode) { + this.scheduleCode = scheduleCode; + } + public String getFileName() { + return fileName; + } + public void setFileName(String fileName) { + this.fileName = fileName; + } + public String getFilePath() { + return filePath; + } + public void setFilePath(String filePath) { + this.filePath = filePath; + } + public String getUserID() { + return userID; + } + public void setUserID(String userID) { + this.userID = userID; + } + public String getUserName() { + return userName; + } + public void setUserName(String userName) { + this.userName = userName; + } + public String getUserPassword() { + return userPassword; + } + public void setUserPassword(String userPassword) { + this.userPassword = userPassword; + } + public String getScheduleSTime() { + return scheduleSTime; + } + public void setScheduleSTime(String scheduleSTime) { + this.scheduleSTime = scheduleSTime; + } + public String getScheduleETime() { + return scheduleETime; + } + public void setScheduleETime(String scheduleETime) { + this.scheduleETime = scheduleETime; + } + public String getRenamedFileName() { + return renamedFileName; + } + public void setRenamedFileName(String renamedFileName) { + this.renamedFileName = renamedFileName; + } + public String getFlowCode() { + return flowCode; + } + public void setFlowCode(String flowCode) { + this.flowCode = flowCode; + } + public String getSystemConnCode() { + return systemConnCode; + } + public void setSystemConnCode(String systemConnCode) { + this.systemConnCode = systemConnCode; + } + public long getFileSize() { + return fileSize; + } + public void setFileSize(long fileSize) { + this.fileSize = fileSize; + } + public int getBlockSize() { + return blockSize; + } + public void setBlockSize(int blockSize) { + this.blockSize = blockSize; + } + public int getSequenceSize() { + return sequenceSize; + } + public void setSequenceSize(int sequenceSize) { + this.sequenceSize = sequenceSize; + } + public String getRemoteIP() { + return remoteIP; + } + public void setRemoteIP(String remoteIP) { + this.remoteIP = remoteIP; + } + public String getPort() { + return port; + } + public void setPort(String port) { + this.port = port; + } + public String getBatchStartTime() { + return batchStartTime; + } + public void setBatchStartTime(String batchStartTime) { + this.batchStartTime = batchStartTime; + } + public String getRequestResponse() { + return requestResponse; + } + public void setRequestResponse(String requestResponse) { + this.requestResponse = requestResponse; + } + public String getSendRecv() { + return sendRecv; + } + public void setSendRecv(String sendRecv) { + this.sendRecv = sendRecv; + } + public String getRuleCode() { + return ruleCode; + } + public void setRuleCode(String ruleCode) { + this.ruleCode = ruleCode; + } + public String getRuleDesc() { + return ruleDesc; + } + public void setRuleDesc(String ruleDesc) { + this.ruleDesc = ruleDesc; + } +// public String getProtocol() { +// return protocol; +// } +// public void setProtocol(String protocol) { +// this.protocol = protocol; +// } + public String getBizCode() { + return bizCode; + } + public void setBizCode(String bizCode) { + this.bizCode = bizCode; + } + public String getFileErrorPath() { + return fileErrorPath; + } + public void setFileErrorPath(String fileErrorPath) { + this.fileErrorPath = fileErrorPath; + } + public int getPacketSize() { + return packetSize; + } + public void setPacketSize(int packetSize) { + this.packetSize = packetSize; + } + public int getRecLen() { + return recLen; + } + public void setRecLen(int recLen) { + this.recLen = recLen; + } + public long getTotRecCnt() { + return totRecCnt; + } + public void setTotRecCnt(long totRecCnt) { + this.totRecCnt = totRecCnt; + } + public String getBaseDate() { + return baseDate; + } + public void setBaseDate(String baseDate) { + this.baseDate = baseDate; + } + public String getEventScheduleID() { + return eventScheduleID; + } + public void setEventScheduleID(String eventScheduleID) { + this.eventScheduleID = eventScheduleID; + } + public String getHdrInfoName() { + return hdrInfoName; + } + public void setHdrInfoName(String hdrInfoName) { + this.hdrInfoName = hdrInfoName; + } + public String getRecvUserID() { + return recvUserID; + } + public void setRecvUserID(String recvUserID) { + this.recvUserID = recvUserID; + } + public String getRecvUserPassword() { + return recvUserPassword; + } + public void setRecvUserPassword(String recvUserPassword) { + this.recvUserPassword = recvUserPassword; + } + public boolean getReqSendRetryFlag() { + return reqSendRetryFlag; + } + public void setReqSendRetryFlag(boolean reqSendRetryFlag) { + this.reqSendRetryFlag = reqSendRetryFlag; + } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Header\nUUID:"); + builder.append(uUID); + builder.append("\nTRX_ID:"); + builder.append(tRX_ID); + builder.append("\nlayerCode:"); + builder.append(layerCode); + builder.append("\nprocessType:"); + builder.append(processType); + builder.append("\nprocessCode:"); + builder.append(processCode); + builder.append("\nprocessName:"); + builder.append(processName); + builder.append("\ninstitutionCode:"); + builder.append(institutionCode); + builder.append("\ninstitutionName:"); + builder.append(institutionName); + builder.append("\njobCode:"); + builder.append(jobCode); + builder.append("\nscheduleCode:"); + builder.append(scheduleCode); + builder.append("\nfileName:"); + builder.append(fileName); + builder.append("\nfilePath:"); + builder.append(filePath); + builder.append("\nuserID:"); + builder.append(userID); + builder.append("\nuserName:"); + builder.append(userName); + builder.append("\nuserPassword:"); + builder.append(userPassword); + builder.append("\nscheduleSTime:"); + builder.append(scheduleSTime); + builder.append("\nscheduleETime:"); + builder.append(scheduleETime); + builder.append("\nrenamedFileName:"); + builder.append(renamedFileName); + builder.append("\nflowCode:"); + builder.append(flowCode); + builder.append("\nsystemConnCode:"); + builder.append(systemConnCode); + builder.append("\nfileSize:"); + builder.append(fileSize); + builder.append("\nblockSize:"); + builder.append(blockSize); + builder.append("\nsequenceSize:"); + builder.append(sequenceSize); + builder.append("\nremoteIP:"); + builder.append(remoteIP); + builder.append("\nport:"); + builder.append(port); + builder.append("\nbatchStartTime:"); + builder.append(batchStartTime); + builder.append("\nrequestResponse:"); + builder.append(requestResponse); + builder.append("\nsendRecv:"); + builder.append(sendRecv); + builder.append("\nruleCode:"); + builder.append(ruleCode); + builder.append("\nruleDesc:"); + builder.append(ruleDesc); +// builder.append("\nprotocol:"); +// builder.append(protocol); + builder.append("\nbizCode:"); + builder.append(bizCode); + builder.append("\nfileErrorPath:"); + builder.append(fileErrorPath); + builder.append("\npacketSize:"); + builder.append(packetSize); + builder.append("\nrecLen:"); + builder.append(recLen); + builder.append("\ntotRecCnt:"); + builder.append(totRecCnt); + builder.append("\nbaseDate:"); + builder.append(baseDate); + builder.append("\neventScheduleID:"); + builder.append(eventScheduleID); + builder.append("\nhdrInfoName:"); + builder.append(hdrInfoName); + builder.append("\nrecvUserID:"); + builder.append(recvUserID); + builder.append("\nrecvUserPassword:"); + builder.append(recvUserPassword); + builder.append("\nreqSendRetryFlag:"); + builder.append(reqSendRetryFlag); + return builder.toString(); + } + +} diff --git a/src/com/eactive/eai/batch/doc/Phaseinfo.java b/src/com/eactive/eai/batch/doc/Phaseinfo.java new file mode 100644 index 0000000..7250c1b --- /dev/null +++ b/src/com/eactive/eai/batch/doc/Phaseinfo.java @@ -0,0 +1,158 @@ +package com.eactive.eai.batch.doc; + +import java.io.Serializable; + +public class Phaseinfo implements Serializable +{ + private static final long serialVersionUID = 1L; + String ruleCode ; + String phaseCode ; + String phaseType ; + String flowClassName ; + String lengthTelegramID ; + String lengthClassName ; + String lengthMsgCode ; + int lengthFieldIndex ; + String phaseSeq ; + String phaseTelegramID ; + String phaseClassName ; + String phaseMsgCode ; + String telegramTypeValue ; + String bizCodeValue ; + String controlCodeValue ; + String responseCodeValue ; + public String getRuleCode() { + return ruleCode; + } + public void setRuleCode(String ruleCode) { + this.ruleCode = ruleCode; + } + public String getPhaseCode() { + return phaseCode; + } + public void setPhaseCode(String phaseCode) { + this.phaseCode = phaseCode; + } + public String getPhaseType() { + return phaseType; + } + public void setPhaseType(String phaseType) { + this.phaseType = phaseType; + } + public String getFlowClassName() { + return flowClassName; + } + public void setFlowClassName(String flowClassName) { + this.flowClassName = flowClassName; + } + public String getLengthTelegramID() { + return lengthTelegramID; + } + public void setLengthTelegramID(String lengthTelegramID) { + this.lengthTelegramID = lengthTelegramID; + } + public String getLengthClassName() { + return lengthClassName; + } + public void setLengthClassName(String lengthClassName) { + this.lengthClassName = lengthClassName; + } + public String getLengthMsgCode() { + return lengthMsgCode; + } + public void setLengthMsgCode(String lengthMsgCode) { + this.lengthMsgCode = lengthMsgCode; + } + public int getLengthFieldIndex() { + return lengthFieldIndex; + } + public void setLengthFieldIndex(int lengthFieldIndex) { + this.lengthFieldIndex = lengthFieldIndex; + } + public String getPhaseSeq() { + return phaseSeq; + } + public void setPhaseSeq(String phaseSeq) { + this.phaseSeq = phaseSeq; + } + public String getPhaseTelegramID() { + return phaseTelegramID; + } + public void setPhaseTelegramID(String phaseTelegramID) { + this.phaseTelegramID = phaseTelegramID; + } + public String getPhaseClassName() { + return phaseClassName; + } + public void setPhaseClassName(String phaseClassName) { + this.phaseClassName = phaseClassName; + } + public String getPhaseMsgCode() { + return phaseMsgCode; + } + public void setPhaseMsgCode(String phaseMsgCode) { + this.phaseMsgCode = phaseMsgCode; + } + public String getTelegramTypeValue() { + return telegramTypeValue; + } + public void setTelegramTypeValue(String telegramTypeValue) { + this.telegramTypeValue = telegramTypeValue; + } + public String getBizCodeValue() { + return bizCodeValue; + } + public void setBizCodeValue(String bizCodeValue) { + this.bizCodeValue = bizCodeValue; + } + public String getControlCodeValue() { + return controlCodeValue; + } + public void setControlCodeValue(String controlCodeValue) { + this.controlCodeValue = controlCodeValue; + } + public String getResponseCodeValue() { + return responseCodeValue; + } + public void setResponseCodeValue(String responseCodeValue) { + this.responseCodeValue = responseCodeValue; + } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Phaseinfo\nruleCode:"); + builder.append(ruleCode); + builder.append("\nphaseCode:"); + builder.append(phaseCode); + builder.append("\nphaseType:"); + builder.append(phaseType); + builder.append("\nflowClassName:"); + builder.append(flowClassName); + builder.append("\nlengthTelegramID:"); + builder.append(lengthTelegramID); + builder.append("\nlengthClassName:"); + builder.append(lengthClassName); + builder.append("\nlengthMsgCode:"); + builder.append(lengthMsgCode); + builder.append("\nlengthFieldIndex:"); + builder.append(lengthFieldIndex); + builder.append("\nphaseSeq:"); + builder.append(phaseSeq); + builder.append("\nphaseTelegramID:"); + builder.append(phaseTelegramID); + builder.append("\nphaseClassName:"); + builder.append(phaseClassName); + builder.append("\nphaseMsgCode:"); + builder.append(phaseMsgCode); + builder.append("\ntelegramTypeValue:"); + builder.append(telegramTypeValue); + builder.append("\nbizCodeValue:"); + builder.append(bizCodeValue); + builder.append("\ncontrolCodeValue:"); + builder.append(controlCodeValue); + builder.append("\nresponseCodeValue:"); + builder.append(responseCodeValue); + return builder.toString(); + } + +} diff --git a/src/com/eactive/eai/batch/encrypt/EncryptManager.java b/src/com/eactive/eai/batch/encrypt/EncryptManager.java new file mode 100644 index 0000000..987ba4d --- /dev/null +++ b/src/com/eactive/eai/batch/encrypt/EncryptManager.java @@ -0,0 +1,482 @@ +package com.eactive.eai.batch.encrypt; + +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 org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Hashtable; + +/** +* 1. 기능 : 전문 생성시 사용자 암호를 생성한다. +* 2. 처리 개요 : CMS은행을 기준으로 암호화 및 복호화 알고리즘을 구현한다. +* 3. 주의사항 +* +* @author : 이윤철 (2006/1/6) +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class EncryptManager implements Lifecycle +{ + //private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT); + + /** + * EncryptManager Single Instance + */ + private static EncryptManager instance = new EncryptManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 암호화 테이블 + */ + private static Hashtable codeTable; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : Flow Rule 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private EncryptManager() { + codeTable = new Hashtable(); + initTable(); + } + + + + // 암호화 대수 테이블 초기화 + private static void initTable() + { + if(codeTable.isEmpty()) + { + for(int i=65; i<91; i++) + { + String key = new Character((char)i).toString(); + String value = new Integer(100 - i).toString(); + + codeTable.put(key, value); + codeTable.put(value, key); + } + + for(int i=0; i<10; i++) + { + String key = new Integer(i).toString(); + String value = new Integer(9-i).toString(); + codeTable.put(key, value); + } + //logger.debug("** if Hashtable : A = : " + codeTable.get("A")); + //logger.debug("** Hashtable = : " + codeTable.toString()); + } + else + { + //logger.debug("** else Hashtable : A = : " + codeTable.get("A")); + } + } + + + /** + * 1. 기능 : EncryptManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : EncryptManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return FlowRuleManager Singleton object + **/ + public static EncryptManager getInstance() { + if(instance == null) + instance = new EncryptManager(); + return instance; + } + + /* ****************************************************************** */ + /* EncryptManager 자체적인 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : 암호화 알고리즘 + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @param 전송자명(영문), 전송자암호, 은행코드, 전송일(yymmdd) + * @return 사용자 암호 평문을 암호화하여 반환 + * @exception + **/ + public String getEncrypt(String transferName, String transferPwd, String bankCode, String transferDate) throws Exception + { + /** + * 1. 제한 조건 + * - 거래일은 YYMMDD 형태(6자리)이다. + * 2. 입력문장 예시 + * - transferName = "Kimchungjin"; //전송자명 (영문) + * transferPwd = "1234567890123456"; //전송자암호평문 + * bankCode = "02"; //은행코드 + * transferDate = "950815"; //전송년월일 + */ + + + //logger.debug( "[EncryptManager][getEncrypt]:transferName(" + transferName + "), transferPwd(" + transferPwd + // + "), bankCode(" + bankCode + "), transferDate(" + transferDate + ")"); + /* 변수 */ + String encryptSeed = ""; // encryptSeed = 은행코드(2)+거래일(6, yymmdd)+전송자명 앞 8자리, 총16자리 + String encryptMsg = ""; // 암호화된 결과를 보내는 문장 + + /* 전송자명 체크 + * - 전송자명이 8자리보다 적으면 빈자리는 Z로 채운다. + * - 전송자명이 8자리보다 크면 앞의 8자리만 사용한다. + */ + transferName = transferName.toUpperCase(); + if(transferName.length() > 8) + transferName = transferName.substring(0,8); + else + { + for(; transferName.length() < 8; ) + { + transferName += "Z"; + } + } + + /* 전송자암호 체크 : 전송자 암호는 6자리이며 앞에서부터 반복해서 16자리로 만든다. */ + // 암호에 공백이 들어 갈수 없다. 2009.01.08 + if(transferPwd.trim().length() != 6) + throw new Exception("전송자 암호 평문은 반드시 6자리이어야합니다.(공백불가) : " + transferPwd); + transferPwd = transferPwd.toUpperCase(); + for(int i=0; transferPwd.length() != 16; i++) + { + transferPwd += transferPwd.substring(i, i+1); + } + //transferPwd = "1234567890123456"; for test... + //logger.debug("transferPwd : " + transferPwd); + + /* 전송일 체크 */ + if(transferDate.length() != 6) + throw new Exception("전송일은 반드시 6자리(YYMMDD)이어야합니다. : " + transferDate); + + /* 암호화 Seed를 생성한다. */ + encryptSeed = bankCode + transferDate + transferName; + + /* 암호화 문장 생성 */ + for(int i=0; i<16; i++) + { + int m_Msg = new Integer((String)codeTable.get(transferPwd.substring(i, i+1))).intValue(); + int m_Key = new Integer((String)codeTable.get(encryptSeed.substring(i, i+1))).intValue(); + encryptMsg += (String)codeTable.get(new Integer((m_Msg + m_Key) % 36).toString()); + } + + return encryptMsg; + } + + public String getEncryptForKCB(String transferName, String transferPwd, String bankCode, String transferDate) throws Exception + { + /** + * 1. 제한 조건 + * - 거래일은 YYMMDD 형태(6자리)이다. + * 2. 입력문장 예시 + * - transferName = "Kimchungjin"; //전송자명 (영문) + * transferPwd = "1234567890123456"; //전송자암호평문 + * bankCode = "02"; //은행코드 + * transferDate = "950815"; //전송년월일 + * 적용 암호키 : A001050815Kimchu + */ + + /* 변수 */ + String encryptSeed = ""; // encryptSeed = 은행코드(A001)+거래일(6, yymmdd)+전송자명 앞 6자리, 총16자리 + String encryptMsg = ""; // 암호화된 결과를 보내는 문장 + + /* 전송자명 체크 + * - 전송자명이 6자리보다 적으면 빈자리는 Z로 채운다. + * - 전송자명이 6자리보다 크면 앞의 8자리만 사용한다. + */ + transferName = transferName.toUpperCase(); + if(transferName.length() > 6) + transferName = transferName.substring(0,6); + else + { + for(; transferName.length() < 6; ) + { + transferName += "Z"; + } + } + + /* 전송자암호 체크 : 전송자 암호는 6자리이며 앞에서부터 반복해서 16자리로 만든다. */ + // 암호에 공백이 들어 갈수 없다. 2009.01.08 +// if(transferPwd.trim().length() != 16) +// throw new Exception("전송자 암호 평문은 반드시 6자리이어야합니다.(공백불가) : " + transferPwd); + transferPwd = transferPwd.toUpperCase(); + for(int i=0; transferPwd.length() != 16; i++) + { + transferPwd += transferPwd.substring(i, i+1); + } + //transferPwd = "1234567890123456"; for test... + //logger.debug("transferPwd : " + transferPwd); + + /* 전송일 체크 */ + if(transferDate.length() != 6) + throw new Exception("전송일은 반드시 6자리(YYMMDD)이어야합니다. : " + transferDate); + + /* 암호화 Seed를 생성한다. */ + encryptSeed = bankCode + transferDate + transferName; + + /* 암호화 문장 생성 */ + for(int i=0; i<16; i++) + { + int m_Msg = new Integer((String)codeTable.get(transferPwd.substring(i, i+1))).intValue(); + int m_Key = new Integer((String)codeTable.get(encryptSeed.substring(i, i+1))).intValue(); + encryptMsg += (String)codeTable.get(new Integer((m_Msg + m_Key) % 36).toString()); + } + + return encryptMsg; + } + + + /** + * 1. 기능 : 복호화 알고리즘 메인 + * 2. 처리 개요 : + * + * 3. 주의사항 + * @param 전달받은 사용자암호(암호화된것), 암호해독 seed + * @return + * @exception + **/ + public String getDeEncrypt(String encryptMsg, String seed) + { + /* 변수 */ + String normalMsg = ""; + + seed = seed.toUpperCase(); + + for(int i=0; i<16; i++) + { + int m_Msg = new Integer((String)codeTable.get(encryptMsg.substring(i, i+1))).intValue() + 36; + int m_Key = new Integer((String)codeTable.get(seed.substring(i, i+1))).intValue(); + normalMsg += (String)codeTable.get(new Integer((m_Msg - m_Key) % 36).toString()); + } + + return normalMsg; + } + + /** + * 1. 기능 : 복호화 알고리즘 + * 복화화 알고리즘 Seed를 개별로 받아들임 + * 2. 처리 개요 : + * + * 3. 주의사항 + * @param 전달받은 사용자암호(암호화된것), 은행코드(2), 전송년월일(6), 전송자명(8) + * @return 사용자 암호 평문 + * @exception + **/ + public String getDeEncrypt(String encryptMsg, String bankCode, String transferDate, String transferName) + { + /* 전송자명 체크 + * - 전송자명이 8자리보다 적으면 빈자리는 Z로 채운다. + * - 전송자명이 8자리보다 크면 앞의 8자리만 사용한다. + */ + transferName = transferName.toUpperCase(); + if(transferName.length() > 8) + transferName = transferName.substring(0,8); + else + { + for(; transferName.length() < 8; ) + { + transferName += "Z"; + } + } + String seed = bankCode + transferDate + transferName; + return this.getDeEncrypt(encryptMsg, seed); + } + + /** + * 1. 기능 : 암호화 알고리즘 + * 2. 처리 개요 : this.getEncrypt(String, String, String, String)메소드는 코드내에 필요한 데이터를 추출(예. 전송자명 앞 8자리 추출) + * getEncryptPwd 메소드는 메소드를 호출하는 부분에서 필요한 모든 데이터의 값을 정의해서 호출하고, + * 해당 메소드내에서는 전달된 값으로 암호화하는 작업만 수행하도록 한다. + * 3. 주의사항 + * + * @param 전송자명(영문), 전송자암호, 은행코드, 전송일(yymmdd) + * @return 사용자 암호 평문을 암호화하여 반환 + * @exception + **/ + public String getEncryptPwd(String transferName, String transferPwd, String bankCode, String transferDate) throws Exception + { + /** + * 1. 제한 조건 + * - 거래일은 YYMMDD 형태(6자리)이다. + * 2. 입력문장 예시 + * - transferName = "KIMHYUNKUK"; //전송자명 (영문) + * transferPwd = "1234567890123456"; //전송자암호평문 + * bankCode = "004"; //은행코드 + * transferDate = 2008년 11월 13일; //전송년월일 + */ + + /* 변수 */ + String encryptSeed = ""; // 적용암호키 + String encryptMsg = ""; // 암호화된 결과를 보내는 문장 + + + transferName = transferName.toUpperCase(); + + + /* 전송자암호 체크 : 전송자 암호는 6자리이며 앞에서부터 반복해서 16자리로 만든다. */ + // 암호에 공백이 들어 갈수 없다. 2009.01.08 + if(transferPwd.trim().length() != 6) + throw new Exception("전송자 암호 평문은 반드시 6자리이어야합니다.(공백불가) : " + transferPwd); + transferPwd = transferPwd.toUpperCase(); + for(int i=0; transferPwd.length() != 16; i++) + { + transferPwd += transferPwd.substring(i, i+1); + } + + /* 전송일 체크 */ + if(transferDate.length() != 6) + throw new Exception("전송일은 반드시 6자리(YYMMDD)이어야합니다. : " + transferDate); + + /* 암호화 Seed를 생성한다. */ + encryptSeed = bankCode + transferDate + transferName; + + /* 암호화 문장 생성 */ + for(int i=0; i getAllHolidays() throws DAOException + { + + ArrayList holidays = new ArrayList(); + try + { + connect(GET_ALL_HOLIDAY); + ResultSet rs = executeQuery(); + + while(rs.next()) { + HolidayVO vo = new HolidayVO(rs.getString(1).trim(), rs.getString(2).trim(), rs.getString(3).trim()); + holidays.add(vo); + } + return holidays; + + }catch(Exception e){ + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMEH001")); + } + finally + { + disconnect(); + } + } +} diff --git a/src/com/eactive/eai/batch/eventscheduler/holiday/HolidayKeys.java b/src/com/eactive/eai/batch/eventscheduler/holiday/HolidayKeys.java new file mode 100644 index 0000000..cfffb42 --- /dev/null +++ b/src/com/eactive/eai/batch/eventscheduler/holiday/HolidayKeys.java @@ -0,0 +1,13 @@ +package com.eactive.eai.batch.eventscheduler.holiday; + +public final class HolidayKeys { + + public static final String LEGAL_HOLIDAY_TYPE = "LH"; //공휴일 +// public static final String TEMP_HOLIDAY_TYPE = "TH" ; //임시휴일 + public static final String NATIONAL_HOLIDAY_TYPE = "NH"; //명절 즉, 음력휴일 + + public static final String[] HOLIDAY_TYPE_KEYS={"1", "2", "3"}; + public static final String[] HOLIDAY_TYPE_VALUES={"LH", "TH", "NH"}; +// public static final String[] HOLIDAY_TYPE_DESC={"공휴일", "임시휴일", "음력휴일"}; + +} diff --git a/src/com/eactive/eai/batch/eventscheduler/holiday/HolidayManager.java b/src/com/eactive/eai/batch/eventscheduler/holiday/HolidayManager.java new file mode 100644 index 0000000..209a445 --- /dev/null +++ b/src/com/eactive/eai/batch/eventscheduler/holiday/HolidayManager.java @@ -0,0 +1,298 @@ +package com.eactive.eai.batch.eventscheduler.holiday; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import org.quartz.impl.calendar.AnnualCalendar; +import org.quartz.impl.calendar.WeeklyCalendar; + +import com.eactive.eai.batch.eventscheduler.util.LunarCalendar; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +public class HolidayManager implements Lifecycle +{ + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + private static HolidayManager instance = new HolidayManager(); + private LifecycleSupport lifecycle; + private boolean started; + private ArrayList holidays; + + private AnnualCalendar hcal; //등록된 휴일, 토, 일 + private AnnualCalendar scal; //등록된 휴일, 일 + + private HolidayManager(){ + lifecycle = new LifecycleSupport(this); + holidays = new ArrayList(); + } + + public static HolidayManager getInstance(){ + return instance; + } + + public void start() throws LifecycleException{ + if(started){ + throw new LifecycleException("BECEAIMEH201"); + } else{ + lifecycle.fireLifecycleEvent("starting", this); + + DAOFactory daoFactory = DAOFactory.newInstance(); + HolidayDAO dao = null; + + try { + + dao = (HolidayDAO)daoFactory.create(HolidayDAO.class); + holidays = dao.getAllHolidays(); + + makeCalendar(); + + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMEH202")); + } catch (Exception e){ + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMEH202")); + } + started = true; + lifecycle.fireLifecycleEvent("started", this); + + return; + } + } + + public void stop() throws LifecycleException{ + if(!started){ + throw new LifecycleException("BECEAIMEH203"); + } else { + lifecycle.fireLifecycleEvent("stoping", this); + holidays = null; + started = false; + lifecycle.fireLifecycleEvent("stopped", this); + return; + } + } + + public void addLifecycleListener(LifecycleListener listener){ + lifecycle.addLifecycleListener(listener); + } + + public LifecycleListener[] findLifecycleListeners(){ + return lifecycle.findLifecycleListeners(); + } + + public void removeLifecycleListener(LifecycleListener listener){ + lifecycle.removeLifecycleListener(listener); + } + + public boolean isStarted(){ + return started; + } + + public void removeHoliday(HolidayVO vo){ + String rymd = vo.getHoliday(); + String rtype = vo.getHolidayType(); + + try{ + for (int i=0; i getAllHoliday(){ + return holidays; + } + + public AnnualCalendar getCalendar (){ + return this.hcal; + } + + public void setCalendar (AnnualCalendar cal){ + this.hcal = cal; + } + + public boolean isAllHoliday(String day){ + + if (hcal == null){ //휴일 Calendar가 null이면 휴일 없음. + return false; + } + boolean result = false; + try { + Calendar dcal = createCalendar(day); + result = hcal.isDayExcluded(dcal); + + int dow = dcal.get(Calendar.DAY_OF_WEEK); + if (result==false){ //등록된 휴일 목록에 없으면 주말휴일에 포함되는지 확인 + WeeklyCalendar wcal = (WeeklyCalendar)hcal.getBaseCalendar(); + result = wcal.isDayExcluded(dow); + + } + }catch (Exception e){ + throw new RuntimeException ("occur RuntimeException at HolidayManager.isAllHoliday - "+day); + } + return result; + } + + public boolean isHoliday(String day){ + + if (scal == null){ //휴일 Calendar가 null이면 휴일 없음. + return false; + } + boolean result = false; + try { + Calendar dcal = createCalendar(day); + result = scal.isDayExcluded(dcal); + + int dow = dcal.get(Calendar.DAY_OF_WEEK); + if (result==false){ //등록된 휴일 목록에 없으면 일요일에 포함되는지 확인 + WeeklyCalendar wcal = (WeeklyCalendar)scal.getBaseCalendar(); + result = wcal.isDayExcluded(dow); + } + }catch (Exception e){ + logger.error(e.getMessage(), e); + throw new RuntimeException ("occur RuntimeException at HolidayManager.isHoliday - "+day + "\n" + e.getMessage()); + } + return result; + + } + + /* + public String[] getHolidayNm(){ + Iterator it = holidays.keySet().iterator(); + String eaiIns[] = new String[holidays.size()]; + for(int i = 0; it.hasNext(); i++) + eaiIns[i] = (String)it.next(); + + Arrays.sort(eaiIns); + return eaiIns; + } + + public HolidayVO[] getHolidayVos(){ + + Iterator it = holidays.values().iterator(); + HolidayVO vos[] = new HolidayVO[holidays.size()]; + for(int i = 0; it.hasNext(); i++){ + vos[i] = (HolidayVO)it.next(); + } + return vos; + } +*/ + public void makeCalendar() throws Exception{ + TimeZone tz = TimeZone.getTimeZone("Asia/Seoul"); + WeeklyCalendar weeklys = new WeeklyCalendar(tz); + weeklys.setDayExcluded(Calendar.SUNDAY, true); //일요일 + weeklys.setDayExcluded(Calendar.SATURDAY, true); //토요일 + + + WeeklyCalendar sunweek = new WeeklyCalendar(tz); + sunweek.setDayExcluded(Calendar.SUNDAY, true); //일요일 + + AnnualCalendar aholidays = new AnnualCalendar(weeklys); + scal = new AnnualCalendar(sunweek); + + Calendar cal = null; + Calendar c = new GregorianCalendar(); + int year = c.get(Calendar.YEAR); + + if (holidays.size()>0){ + for (int i=0; i +// * 사용법 :
+// * 작성 날짜 : 2008.02.27 +// * @author 천기숙 +// * @version 1.0 +// */ +//public class DirectoryUtil { +// +// public final static String DILIMITER = "/"; +// +// /** +// * 사용목적 : 메인디렉토리명과 서브 디렉토리명을 받아 전체 경로 반환
+// * 사용법 :
+// * 구현 설명 :
+// * 유효 리턴 값 : 디렉토리의 전체 경로
+// * 유효 인자 값 : baseDir - 메인디렉토리명, +// * subDir - 서브디렉토리명
+// * 작성 날짜 : (05-01-12 오후 03:36:00) +// */ +// public static String getDir(String baseDir, String subDir){ +// String dir = baseDir+DILIMITER+subDir; +// +// return dir; +// +// } +// +// /** +// * 사용목적 : 윈도우 디렉토리 구분자를 유닉스 디렉토리 구분자로 변경
+// * 사용법 :
+// * 구현 설명 :
+// * 유효 리턴 값 : 유닉스 디렉토리 구분자
+// * 유효 인자 값 : dir - 디렉토리
+// * 작성 날짜 : (05-01-12 오후 03:36:00) +// */ +// public static String replaceDilimiter (String dir){ +// String strBaseDir = dir.replaceAll("\\\\", DILIMITER); +// +// return strBaseDir; +// } +//} diff --git a/src/com/eactive/eai/batch/eventscheduler/util/ExpressionParser.java b/src/com/eactive/eai/batch/eventscheduler/util/ExpressionParser.java new file mode 100644 index 0000000..c343ceb --- /dev/null +++ b/src/com/eactive/eai/batch/eventscheduler/util/ExpressionParser.java @@ -0,0 +1,116 @@ +//package com.eactive.eai.batch.eventscheduler.util; +// +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +///** +//* 1. 기능 : Scheduler의 CronExpression을 조립 및 파싱하기 위한 클래스 +//* 2. 처리 개요 : +//* - 스케줄러 정보를 CronTrigger에서 사용될 Expression으로 조립 +//* - CronTrigger에서 사용되는 Expression을 사용자가 이해하기 쉬운 형태로 파싱 +//* 3. 주의사항 +//* +//* @author : kscheon +//* @version : v 1.0.0 +//*/ +//public final class ExpressionParser { +// +// /** +// * Default Logger +// */ +// static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_SCHEDULER); +// +// public final static String EXP_ALL = "*"; +// public final static String EXP_RANGE = "-"; +// public final static String EXP_ADD = ","; +// public final static String EXP_INCREMENT = "/"; +// public final static String EXP_LAST = "L"; +// public final static String EXP_NTH = "#"; +// +// public final static String assembleExpression(String[] token){ +// int length = token.length; +// if (length != 6){ +// logger.error("ExpressionParser ] assembleExpression - argument length is not 6 - "+length); +// } +// String expression = ""; +// +// for (int i=0; i< length; i++){ +// expression = expression+token[i]; +// +// if (i fileInfos; +// +// public LocalFileUtil(){ +// fileInfos = new HashMap(); +// } +// +// static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_SCHEDULER); +// +// public HashMap searchFileInfo(SchedulerEventVO vo, String searchFile) throws Exception { +// +// +// //Properties mapProp = vo.getEventPropMap(); +// +// String propGroup = vo.getPropGroupName(); +// Properties mapProp = null; +// +// try{ +// if(propGroup !=null && propGroup.length() > 0){ +// PropManager pmanager = PropManager.getInstance(); +// mapProp = pmanager.getPropGroupVO(propGroup).getProperties(); +// } +// +// }catch (Exception e){ +// e.printStackTrace(); +// logger.error("LocalFileUtil ] searchFileInfo - 프로퍼티 정보를 설정하는데 오류가 발생했습니다. - "+e.getMessage()); +// } +// +// searchFileName = searchFile; +// +// //propFile = ((String)mapProp.get(SchedulerKeys.FILE_PATTERN)).trim(); +// propLocalDir = ((String)mapProp.get(SchedulerKeys.LOCAL_DIR)).trim(); +// +// delimiter = StringUtil.getDirDelimiter(propLocalDir); +// +// posActionType = (String)(mapProp.get(SchedulerKeys.POST_ACTION_TYPE)==null?SchedulerKeys.POST_ACTION_DELETE:mapProp.get(SchedulerKeys.POST_ACTION_TYPE)); +// propArchiveDir = (String)mapProp.get(SchedulerKeys.ARCH_DIR); +// +// File f = new File(propLocalDir); +// String fileName = ""; +// +// if (f != null && f.exists()){ +// File[] fileList = f.listFiles(); +// +// +// if ((fileList != null) && (fileList.length != 0)) { +// for (int i=0; i propLocalDir.length()) { +// fileName = fileName.substring(propLocalDir.getBytes().length); +// } +// //첫번째 목록이 파일 타입인지 확인한다. +// if (fileList[i].isFile()){ +// String[] fileInfo = new String[2]; +// +// if (searchFileName !=null && searchFileName.length()>0){ +// if (fileName.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조 +// fileInfo[0] = propLocalDir; +// fileInfo[1] = fileName; +// fileInfos.put(fileName, fileInfo); +// +// logger.debug("LocalFileUtil ] 탐색하고자 하는 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+fileName+"]"); +// +// postAction(fileList[i], fileName); +// +// } +// }else { +// fileInfo[0] = propLocalDir; +// fileInfo[1] = fileName; +// fileInfos.put(fileName, fileInfo); +// +// postAction(fileList[i], fileName); +// +// logger.debug("LocalFileUtil ] 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+fileName+"]"); +// } +// +// } else { +// reDirectory(propLocalDir+delimiter+fileName); +// } +// } +// } +// } +// return fileInfos; +// } +// +// private void reDirectory (String currentDir) throws Exception { +// +// try { +// +// File rf = new File(currentDir); +// if (rf != null){ +// +// +// +// File[] subFile = rf.listFiles(); +// +// String localFileName = ""; +// +// if ((subFile != null) && (subFile.length != 0)) { +// for (int i=0; i currentDir.length()) { +// localFileName = localFileName.substring(currentDir.getBytes().length); +// } +// +// if(subFile[i].isDirectory()) { //directory type이면 +// reDirectory(currentDir+delimiter+localFileName); +// +// } else if(subFile[i].isFile()) { +// String[] fileInfo = new String[2]; +// +// +// if (searchFileName !=null && searchFileName.length()>0){ +// if (localFileName.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조 +// fileInfo[0] = currentDir; +// fileInfo[1] = localFileName; +// fileInfos.put(localFileName, fileInfo); +// +// logger.debug("LocalFileUtil ] 탐색하고자 하는 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+localFileName+"]"); +// +// postAction(subFile[i], localFileName); +// +// } +// }else { +// fileInfo[0] = currentDir; +// fileInfo[1] = localFileName; +// fileInfos.put(localFileName, fileInfo); +// +// postAction(subFile[i], localFileName); +// +// logger.debug("LocalFileUtil ] 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+localFileName+"]"); +// } +// +// } +// } +// } +// rf = null; +// subFile = null; +// } +// } catch (Exception f) { +// String arg[] = new String[1]; +// arg[0] = currentDir; +// throw new Exception(ExceptionUtil.getErrorCode(f, "BECEAIMEU001",arg)); +// } +// } +// +// private void postAction(File f, String fineName){ +// if (SchedulerKeys.POST_ACTION_ARCH.equals(posActionType)){ +// File af = new File(propArchiveDir); +// if (!af.exists()){ +// if(!af.mkdir()){ +// logger.error("LocalFileUtil ] searchFileInfo - Arch Directory 생성 실패"); +// } +// } +// //File af2 = new File(af, fineName+"_" +CalendarUtil.getCurrentTimeNoDash()); +// File af2 = new File(af, fineName); +// f.renameTo(af2); +// }else if (SchedulerKeys.POST_ACTION_DELETE.equals(posActionType)){ +// f.delete(); +// } +// } +//} diff --git a/src/com/eactive/eai/batch/eventscheduler/util/LunarCalendar.java b/src/com/eactive/eai/batch/eventscheduler/util/LunarCalendar.java new file mode 100644 index 0000000..5aaa7a6 --- /dev/null +++ b/src/com/eactive/eai/batch/eventscheduler/util/LunarCalendar.java @@ -0,0 +1,152 @@ +package com.eactive.eai.batch.eventscheduler.util; + +import com.ibm.icu.util.Calendar ; +import com.ibm.icu.util.ChineseCalendar ; + +public final class LunarCalendar { + private static final int CHINESE_DIFF = 2637; + + public LunarCalendar() { + // + } + + + /** + * 양력을 음력으로 변환 + * + */ + public static String toLunar( String lunarDateStr ) { + if( lunarDateStr == null || lunarDateStr.length() !=8 ) { + return "" ; + } + + Calendar cal = Calendar.getInstance() ; + ChineseCalendar cc = new ChineseCalendar(); + + cal.set( Calendar.YEAR, Integer.parseInt(lunarDateStr.substring(0,4)) ) ; + cal.set( Calendar.MONTH, Integer.parseInt(lunarDateStr.substring(4,6))-1 ) ; + cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt(lunarDateStr.substring(6)) ) ; + + cc.setTimeInMillis( cal.getTimeInMillis() ) ; + + + int y = cc.get(ChineseCalendar.EXTENDED_YEAR)- CHINESE_DIFF ; + int m = cc.get(ChineseCalendar.MONTH)+1 ; + int d = cc.get(ChineseCalendar.DAY_OF_MONTH) ; + + StringBuffer sb = new StringBuffer() ; + + sb.append( y ) ; + + if( m < 10 ) sb.append( "0" ) ; + sb.append( m ) ; + + if( d < 10 ) sb.append( "0" ) ; + sb.append( d ) ; + + return sb.toString() ; + } + + + /** + * 음력을 양력으로 변환 + * + */ + public static String toSolar( String solarDateStr ) { + if( solarDateStr == null || solarDateStr.length() !=8 ) { + return "" ; + } + + Calendar cal = Calendar.getInstance() ; + ChineseCalendar cc = new ChineseCalendar(); + + cc.set( ChineseCalendar.EXTENDED_YEAR, Integer.parseInt(solarDateStr.substring(0,4)) + CHINESE_DIFF ) ; + cc.set( ChineseCalendar.MONTH, Integer.parseInt(solarDateStr.substring(4,6))-1 ) ; + cc.set( ChineseCalendar.DAY_OF_MONTH, Integer.parseInt(solarDateStr.substring(6)) ) ; + + cal.setTimeInMillis( cc.getTimeInMillis() ) ; + + int y = cal.get(Calendar.YEAR) ; + int m = cal.get(Calendar.MONTH) + 1 ; + int d = cal.get(Calendar.DAY_OF_MONTH) ; + + StringBuffer sb = new StringBuffer() ; + + sb.append( y ) ; + + if( m < 10 ) sb.append( "0" ) ; + sb.append( m ) ; + + if( d < 10 ) sb.append( "0" ) ; + sb.append( d ) ; + + return sb.toString() ; + + } + + /** + public static String[] toSolarOfNationalHoliday (String date){ + + String[] nholiday = new String[3]; + + int dateInt = (Integer.parseInt(date))-1; //음력날짜 -1 + try { + + }catch (Exception e){ + e.printStackTrace(); + } + //지정된 음력날짜 앞뒤까지 휴일로 설정하기 위함. + for (int i=0; i"+lunarDate); +//// System.out.println("양력으로 20080524 ->"+date); +// +//// MultiThread Test +// new Thread("T1") { +// public void run() { +// for(int i=0; i<100; i++) { +// LunarCalendar lc = new LunarCalendar() ; +// String lunarDate = lc.toLunar("20080627") ; +// String date = lc.toSolar("20080524") ; +// System.out.println("T1 음력으로 20080627 ->"+lunarDate); +// System.out.println("T1 양력으로 20080524 ->"+date); +// } +// } +// }.start(); // T1 쓰레드 시작 +// +// new Thread("T2") { +// public void run() { +// for(int i=0; i<100; i++) { +// LunarCalendar lc = new LunarCalendar() ; +// String lunarDate = lc.toLunar("20080626") ; +// String date = lc.toSolar("20080523") ; +// System.out.println("T2 음력으로 20080626 ->"+lunarDate); +// System.out.println("T2 양력으로 20080523 ->"+date); +// } +// } +// }.start(); // T2 쓰레드 시작 +// } + +} diff --git a/src/com/eactive/eai/batch/eventscheduler/util/PrintCommandListener.java b/src/com/eactive/eai/batch/eventscheduler/util/PrintCommandListener.java new file mode 100644 index 0000000..8ee70fa --- /dev/null +++ b/src/com/eactive/eai/batch/eventscheduler/util/PrintCommandListener.java @@ -0,0 +1,57 @@ +//package com.eactive.eai.batch.eventscheduler.util; +// +//import org.apache.commons.logging.Log; +// +//import org.apache.commons.net.ProtocolCommandEvent; +//import org.apache.commons.net.ProtocolCommandListener; +// +///** +// * 사용목적 : 모든 command/reply traffic를 print하는 ProtocolCommandListener interface를 +// * 구현한 간단하게 클래스이다.
+// * 사용법 :
+// * 작성 날짜 : (05-01-11 오전 18:35:00) +// * @author 김철성 +// * @version 1.0 +// */ +//public class PrintCommandListener implements ProtocolCommandListener +//{ +// private Log writer; +// +// /** +// * 사용목적 : 생성자
+// * 사용법 :
+// * 구현 설명 :
+// * 유효 리턴 값 :
+// * 유효 인자 값 :
+// * 작성 날짜 : (05-01-11 오전 18:35:00) +// */ +// public PrintCommandListener(Log writer) { +// this.writer = writer; +// } +// +// /** +// * 사용목적 : ProtocolCommandEvent의 내용을 멤버 변수 PrintWriter 객체의 +// * print 메소드를 호출하는 메소드이다.
+// * 사용법 :
+// * 구현 설명 :
+// * 유효 리턴 값 :
+// * 유효 인자 값 :
+// * 작성 날짜 : (05-01-11 오전 18:35:00) +// */ +// public void protocolCommandSent(ProtocolCommandEvent event) { +// this.writer.debug(event.getMessage()); +// } +// +// /** +// * 사용목적 : ProtocolCommandEvent의 내용을 멤버 변수 PrintWriter 객체의 +// * print 메소드를 호출하는 메소드이다.
+// * 사용법 :
+// * 구현 설명 :
+// * 유효 리턴 값 :
+// * 유효 인자 값 :
+// * 작성 날짜 : (05-01-11 오전 18:35:00) +// */ +// public void protocolReplyReceived(ProtocolCommandEvent event) { +// this.writer.debug(event.getMessage()); +// } +//} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/eventscheduler/util/RemoteFTPUtil.java b/src/com/eactive/eai/batch/eventscheduler/util/RemoteFTPUtil.java new file mode 100644 index 0000000..6eef8a9 --- /dev/null +++ b/src/com/eactive/eai/batch/eventscheduler/util/RemoteFTPUtil.java @@ -0,0 +1,312 @@ +//package com.eactive.eai.batch.eventscheduler.util; +// +//import java.io.IOException; +//import java.io.OutputStream; +//import java.util.Properties; +//import java.util.Vector; +// +//import org.apache.commons.net.ftp.FTPClient; +//import org.apache.commons.net.ftp.FTPConnectionClosedException; +//import org.apache.commons.net.ftp.FTPFile; +//import org.apache.commons.net.ftp.FTPReply; +// +//import com.eactive.eai.batch.common.StringUtil; +//import com.eactive.eai.batch.eventscheduler.management.SchedulerEventVO; +//import com.eactive.eai.batch.eventscheduler.management.SchedulerKeys; +//import com.eactive.eai.common.exception.ExceptionUtil; +//import com.eactive.eai.common.property.PropManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import com.eactive.eai.inbound.remote.RemoteServerVO; +// +//public class RemoteFTPUtil { +// +// private Vector fileInfos; +// +// +// private FTPClient ftp = null; +// +// private OutputStream output = null; +// private String propIp = ""; +// private String propPort = "21"; +// private String propUser = ""; +// private String propPassword = ""; +// private String propRemoteDir = ""; +// private String propPassive = "active"; +// private String propArchiveDir = ""; +// private String searchFileName = ""; +// private String posActionType = ""; +// +// private String delimiter =""; +// +// static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_SCHEDULER); +// +// public RemoteFTPUtil() { +// fileInfos = new Vector(); +// } +// +// public Vector searchFileInfo(SchedulerEventVO vo, String searchFile) throws Exception { +// +// searchFileName = searchFile; +// //Properties mapProp = vo.getEventPropMap(); +// String propGroup = vo.getPropGroupName(); +// Properties mapProp = null; +// +// try{ +// if(propGroup !=null && propGroup.length() > 0){ +// PropManager pmanager = PropManager.getInstance(); +// mapProp = pmanager.getPropGroupVO(propGroup).getProperties(); +// } +// +// }catch (Exception e){ +// e.printStackTrace(); +// logger.error("RemoteFTPUtil ] searchFileInfo - 프로퍼티 정보를 설정하는데 오류가 발생했습니다. - "+e.getMessage()); +// } +// try { +// +// //RemoteDirectoryVO rdvo = vo.getRemoteDirectoryVO(); +// RemoteServerVO rsvo = vo.getRemoteServerVO(); +// +// propPassive = (String)(mapProp.get(SchedulerKeys.PASSIVE_MODE)==null?"active":mapProp.get(SchedulerKeys.PASSIVE_MODE)); +// +// propIp = rsvo.getRemoteServerIP(); +// propPort = rsvo.getRemoteFtpPort(); +// propUser = rsvo.getRemoteUserId(); +// propPassword = rsvo.getRemotePassword(); +// //propRemoteDir = rdvo.getRemoteDirName(); +// propRemoteDir = mapProp.getProperty(SchedulerKeys.REMOTE_DIR); +// +// /* +// propIp = mapProp.getProperty(SchedulerKeys.REMOTE_IP); +// propUser = mapProp.getProperty(SchedulerKeys.USER); +// propPassword = mapProp.getProperty(SchedulerKeys.PASSWORD); +// propRemoteDir = mapProp.getProperty(SchedulerKeys.REMOTE_DIR); +// propPort = mapProp.getProperty(SchedulerKeys.REMOTE_PORT); +// */ +// delimiter = StringUtil.getDirDelimiter(propRemoteDir); +// posActionType = (String)(mapProp.get(SchedulerKeys.POST_ACTION_TYPE)==null?SchedulerKeys.POST_ACTION_NONE:mapProp.get(SchedulerKeys.POST_ACTION_TYPE)); +// propArchiveDir = (String)mapProp.get(SchedulerKeys.ARCH_DIR); +// +// +// +// if (propRemoteDir == null || propRemoteDir.length() <=0){ +// throw new Exception(ExceptionUtil.getErrorCode("BECEAIMEU011")); +// } +// +// String remoteFileName = ""; +// +// logger.debug("RemoteFTPUtil ] propIp:propPort:propUser:propPassword - "+propIp+":"+propPort+":"+propUser+":"+propPassword ); +// ftp = connect(propIp, Integer.parseInt(propPort), propUser, propPassword, Boolean.getBoolean(propPassive)); +// +// // 디렉토리 변경 +// boolean result = ftp.changeWorkingDirectory(propRemoteDir); +// +// if (!result){ +// String arg[] = new String[1]; +// arg[0] = propRemoteDir; +// throw new Exception(ExceptionUtil.getErrorCode("BECEAIMEU012", arg)); +// } +// +// FTPFile[] ftpFiles = ftp.listFiles(propRemoteDir); +// +// if ((ftpFiles != null) && (ftpFiles.length != 0)) { +// for (int i=0; i propRemoteDir.length()) { +// remoteFileName = remoteFileName.substring(propRemoteDir.getBytes().length); +// } +// +// // 첫번째 목록이 파일 타입인지 확인한다. +// if (ftpFiles[i].isFile()){ +// String[] fileInfo = new String[2]; +// +// if (searchFileName !=null && searchFileName.length()>0){ +// if (remoteFileName.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조 +// +// fileInfo[0] = propRemoteDir; +// fileInfo[1] = remoteFileName; +// fileInfos.add(fileInfo); +// +// logger.debug("RemoteFTPUtil ] 지정된 파일을 찾았습니다. searchFileName - ["+searchFileName+"] - remoteFileName ["+remoteFileName+"]"); +// +// postAction(ftp, propRemoteDir, remoteFileName); +// +// } +// }else { +// fileInfo[0] = propRemoteDir; +// fileInfo[1] = remoteFileName; +// fileInfos.add(fileInfo); +// +// postAction(ftp, propRemoteDir, remoteFileName); +// +// } +// }else { +// reDirectory(ftp, propRemoteDir+delimiter+remoteFileName); +// } +// } +// } +// ftp.logout(); +// return fileInfos; +// } catch (FTPConnectionClosedException e) { +// e.printStackTrace(); +// String arg[] = new String[2]; +// arg[0] = propIp; +// arg[1] = ""+propPort; +// throw new IOException(ExceptionUtil.getErrorCode(e, "BECEAIMEU013", arg)); +// } catch (IOException e) { +// e.printStackTrace(); +// throw new IOException(ExceptionUtil.getErrorCode(e, "BECEAIMEU014")); +// } catch (Exception e) { +// e.printStackTrace(); +// throw new Exception(ExceptionUtil.getErrorCode(e, "BECEAIMEU014")); +// } finally { +// if (output != null) { +// try { +// output.close(); +// } catch (Exception e) { +// // do nothing +// } +// } +// if (ftp != null && ftp.isConnected()) { +// try { +// ftp.disconnect(); +// } catch (IOException f) { +// // do nothing +// } +// } +// ftp = null; +// } +// } +// +// +// private FTPClient connect(String server, int port, String username, +// String password, boolean passive) throws IOException { +// FTPClient ftpClient = new FTPClient(); +// +// try { +// +// if (passive) { +// ftpClient.enterLocalPassiveMode(); +// } else { +// ftpClient.enterLocalActiveMode(); +// } +// +// ftpClient.setControlEncoding("euc-kr"); +// +// int reply; +// ftpClient.connect(server, port); +// +// reply = ftpClient.getReplyCode(); +// +// if (!FTPReply.isPositiveCompletion(reply)) { +// ftpClient.disconnect(); +// throw new IOException(ExceptionUtil.getErrorCode("BECEAIMEU015")); +// } +// +// if (!ftpClient.login(username, password)) { +// ftpClient.logout(); +// String arg[] = new String[0]; +// arg[0] = username; +// throw new IOException(ExceptionUtil.getErrorCode("BECEAIMEU016", arg)); +// } +// return ftpClient; +// } catch (IOException ie) { +// try { +// String arg[] = new String[2]; +// arg[0] = server; +// arg[1] = ""+port; +// throw new IOException(ExceptionUtil.getErrorCode("BECEAIMEU017", arg)); +// } catch (Exception ex) { +// } +// throw ie; +// } finally { +// try { +// if (ftp.isConnected()) { +// ftp.disconnect(); +// } +// } catch (Exception f) { +// // do nothing +// } +// } +// } +// +// +// private void reDirectory (FTPClient ftp, String currentDir) throws Exception { +// +// +// try { +// // 디렉토리 변경 +// boolean isChange = ftp.changeWorkingDirectory(currentDir); +// if (!isChange) { +// String arg[] = new String[1]; +// arg[0]=currentDir; +// throw new Exception(ExceptionUtil.getErrorCode("BECEAIMEU018", arg)); +// } +// +// FTPFile[] subFile = ftp.listFiles(currentDir); +// +// String remoteFile = ""; +// +// if ((subFile != null) && (subFile.length != 0)) { +// for (int i=0; i currentDir.length()) { +// remoteFile = remoteFile.substring(currentDir.getBytes().length); +// } +// +// // 파일 타입인지 확인한다. +// if(subFile[i].isDirectory()) { //directory type이면 +// reDirectory(ftp, currentDir+delimiter+remoteFile); +// +// } else if(subFile[i].isFile()) { +// String[] fileInfo = new String[2]; +// +// +// if (searchFileName !=null && searchFileName.length()>0){ +// if (remoteFile.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조 +// fileInfo[0] = currentDir; +// fileInfo[1] = remoteFile; +// fileInfos.add(fileInfo); +// +// logger.debug("RemoteFTPUtil ] 지정된 파일을 찾았습니다. searchFileName - ["+searchFileName+"] - remoteFileName ["+remoteFile+"]"); +// +// postAction(ftp, currentDir, remoteFile ); +// } +// }else { +// fileInfo[0] = currentDir; +// fileInfo[1] = remoteFile; +// fileInfos.add(fileInfo); +// +// postAction(ftp, currentDir, remoteFile ); +// } +// +// } +// } +// } +// subFile = null; +// +// } catch (Exception f) { +// String arg[] = new String[1]; +// arg[0]=currentDir; +// throw new Exception(ExceptionUtil.getErrorCode(f, "BECEAIMEU019", arg)); +// } +// } +// +// private void postAction(FTPClient ftp, String dirName, String fileName) throws Exception{ +// if (SchedulerKeys.POST_ACTION_ARCH.equals(posActionType)){ +// +// //if (!ftp.rename(dirName+delimiter+fileName, propArchiveDir+delimiter+fileName+"_" +CalendarUtil.getCurrentTimeNoDash())){ +// if (!ftp.rename(dirName+delimiter+fileName, propArchiveDir+delimiter+fileName)){ +// logger.error("RemoteFTPUtil ] File remane failed"); +// logger.error(" : org -["+dirName+delimiter+fileName+"], new-["+propArchiveDir+delimiter+fileName+"]"); +// }else { +// logger.debug("RemoteFTPUtil ] File rename : org -["+dirName+delimiter+fileName+"], new-["+propArchiveDir+delimiter+fileName+"]"); +// } +// }else if (SchedulerKeys.POST_ACTION_DELETE.equals(posActionType)){ +// ftp.deleteFile(dirName+delimiter+fileName); +// } +// +// } +// +//} diff --git a/src/com/eactive/eai/batch/flowController/BatchTargetVO.java b/src/com/eactive/eai/batch/flowController/BatchTargetVO.java new file mode 100644 index 0000000..5ed9edf --- /dev/null +++ b/src/com/eactive/eai/batch/flowController/BatchTargetVO.java @@ -0,0 +1,140 @@ +package com.eactive.eai.batch.flowController; + +import com.eactive.eai.batch.common.StringUtil; + +import java.io.Serializable; + +/** +* 1. 기능 : 하나의 배치작업 업무를 나타내는 Value Object +* 즉, CMS은행, CMS업체등이 해당된다. +* 관련 테이블 - TSEAIBJ02, TSEAIBJ05 +* 2. 처리 개요 : +* +* 3. 주의사항 +* +* @author : YCLee +* @version : v 1.0.0 +* @see : +* @since :JDK v1.4.2 +*/ +public class BatchTargetVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 업무코드 + */ + private String processCode; // 예, CMSBK + + /** + * 대외기관코드 + */ + private String organCode; // 예, IL03 + + /** + * 대외기관명 + */ + private String organName; // 예, 삼성생명 + + + /** + * 업무명 + */ + private String processName; // 예, CMS은행 + + + /** + * 요구송수신 연결 정보 + */ + private DemandTargetVO[] demandTagetVOs; + + + /** + * 1. 기능 : Defualt Constructor + * 2. 처리 개요 : + * - Defualt Constructor + * 3. 주의사항 + * + **/ + public BatchTargetVO() { + } + + /** + * 1. 기능 : 대외기관 정보를 저장하는 생성자 함수 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param + **/ + public BatchTargetVO(String processCode, String processName, String organCode, String organName) { + this.processCode = StringUtil.nvlTrim(processCode); + this.processName = StringUtil.nvlTrim(processName); + this.organCode = StringUtil.nvlTrim(organCode); + this.organName = StringUtil.nvlTrim(organName); + } + + /** + * 1. 기능: processCode를 반환하는 getter 메소드 + */ + public String getProcessCode() + { + return this.processCode; + } + + /** + * 1. 기능: organCode를 반환하는 getter 메소드 + */ + public String getOrganCode() + { + return this.organCode; + } + + /** + * 1. 기능: organName를 반환하는 getter 메소드 + */ + public String getOrganName() + { + return this.organName; + } + + /** + * 1. 기능: processName을 반환하는 getter 메소드 + */ + public String getProcessName() + { + return this.processName; + } + + + /** + * 1. 기능 : 요구송수신 연결정보 리스트를 반환하는 getter 메소드 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param ruleKey rule의 PK + **/ + public DemandTargetVO[] getDemadnTargets() { + return this.demandTagetVOs; + } + + /** + * 1. 기능 : 요구송수신 연결정보 리스트를 저장하는 setter 메소드 + * 2. 처리 개요 : + * - Rule Key를 저장한다. + * 3. 주의사항 + * + * @param ruleKey rule의 PK + **/ + public int setDemadnTargets(DemandTargetVO[] demandTargetVOs) { + this.demandTagetVOs = new DemandTargetVO[demandTargetVOs.length]; + this.demandTagetVOs = demandTargetVOs; + return this.demandTagetVOs.length; + } + + + + +} diff --git a/src/com/eactive/eai/batch/flowController/DemandTargetVO.java b/src/com/eactive/eai/batch/flowController/DemandTargetVO.java new file mode 100644 index 0000000..c65138a --- /dev/null +++ b/src/com/eactive/eai/batch/flowController/DemandTargetVO.java @@ -0,0 +1,154 @@ +package com.eactive.eai.batch.flowController; + +import com.eactive.eai.batch.common.StringUtil; + +import java.io.Serializable; + +/** +* 1. 기능 : 요구송수신을 위한 연결정보를 나타내는 Value Object +* +* 2. 처리 개요 : +* +* 3. 주의사항 +* +* @author : YCLee 2006/1/11 +* @version : v 1.0.0 +* @see : +* @since :JDK v1.4.2 +*/ +public class DemandTargetVO implements Serializable +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + //대외기관 연결 상태 상수 설정 + public static final String ORGAN_SOCKET_STATUS_NORNAL = "1"; //정상 (DB에 저장되는 값임) + public static final String ORGAN_SOCKET_STATUS_ERROR = "0"; //장애 (DB에 저장되는 값임) + + + private String systemConnCode; + + /** + * 연결기관의 IP + */ + private String ipAddress; + + /** + * 연결기관의 port number + */ + private String portNumber; + + + /** + * 소켓연결시 사용하는 ID + */ + private String socketID; + + + /** + * 소켓연결시 사용하는 패스워드 + */ + private String socketPwd; + + + /** + * 연결 Timeout 간격 + */ + private String timeoutInterval; + + //대외기관 망상태 + private String organSocketStatus; + public void setOrganSocketStatus(String arg) { organSocketStatus = arg; } + public String getOrganSocketStatus() { return organSocketStatus; } + + + /** + * 1. 기능 : Defualt Constructor + * 2. 처리 개요 : + * - Defualt Constructor + * 3. 주의사항 + * + **/ + public DemandTargetVO() { + } + + /** + * 1. 기능 : IP, Port만 입력받는 생성자 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param IP, Port + **/ + public DemandTargetVO(String systemConnCode, String ipAddress, String portNumber, String socketID, String socketPwd, String timeoutInterval, String organSocketStatus) { + this.systemConnCode = StringUtil.nvlTrim(systemConnCode); + this.ipAddress = StringUtil.nvlTrim(ipAddress); + this.portNumber = StringUtil.nvlTrim(portNumber); + this.socketID = StringUtil.nvlTrim(socketID); + this.socketPwd = StringUtil.nvlTrim(socketPwd); + this.timeoutInterval = StringUtil.nvlTrim(timeoutInterval); + this.organSocketStatus = StringUtil.nvlTrim(organSocketStatus); + } + + public void setSystemConnCode(String systemConnCode) + { + this.systemConnCode = systemConnCode; + } + + public String getSystemConnCode() + { + return this.systemConnCode; + } + + public void setIpAddress(String ipAddress) + { + this.ipAddress = ipAddress; + } + + public String getIpAddress() + { + return this.ipAddress; + } + + public void setPortNumber(String portNumber) + { + this.portNumber = portNumber; + } + + public String getPortNumber() + { + return this.portNumber; + } + + public void setSocketID(String socketID) + { + this.socketID = socketID; + } + + public String getSocketID() + { + return this.socketID; + } + + public void setSocketPwd(String socketPwd) + { + this.socketPwd = socketPwd; + } + + public String getSocketPwd() + { + return this.socketPwd; + } + + public void setTimeoutInterval(String timeoutInterval) + { + this.timeoutInterval = timeoutInterval; + } + + public String getTimeoutInterval() + { + return this.timeoutInterval; + } + +} diff --git a/src/com/eactive/eai/batch/flowController/FlowControllerDAO.java b/src/com/eactive/eai/batch/flowController/FlowControllerDAO.java new file mode 100644 index 0000000..7a54684 --- /dev/null +++ b/src/com/eactive/eai/batch/flowController/FlowControllerDAO.java @@ -0,0 +1,229 @@ +package com.eactive.eai.batch.flowController; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; + +/** +* 1. 기능 : EAI서버 정보 테이블에 대한 Data Access Object 이다. +* 2. 처리 개요 : EAI서버 정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다. +* +* 3. 주의사항 +* +*/ +public class FlowControllerDAO extends BaseDAO implements FlowControllerQuery +{ + + /** + * 1. 기능 : 업무별 기본 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서 + * BatchTargetVO 객체 리스트로 생성 반환하는 메서드. + * 2. 처리 개요 : TSEAIBJ02 테이블을 조회해서 각 업무 기본 정보를 가져오고, 해당 업무별 연결 정보를 + * TSEAIBJ05 테이블에서 조회하여 연결 정보들을 DemandTargetVO[]로 만든 다음, processCode를 key로 하여 + * 전체를 hashmap의 형태로 반환한다. + * 3. 주의사항 + * + * @return Flow Rule 정보 전체데이터로 FlowRuleVO Collection + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 EAI서버 정보를 가져오다 발생되는 모든 에러 + **/ + public HashMap getAllTargets() throws DAOException + { + ResultSet rs = null; + + try { + + this.connect(GET_ALL_TARGETS); + //logger.debug("FlowControllerDAO.getAllTargets() >>> 수행 SQL 문 : \n"+ GET_ALL_TARGETS); + + rs = executeQuery(); + + HashMap all = new HashMap(); + + while (rs.next()) { + BatchTargetVO vo = new BatchTargetVO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)); + logger.debug(" - 대외기관 정보 로딩됨 ("+ vo.getProcessCode() +": "+ vo.getProcessName() +", "+ vo.getOrganCode() +": "+ vo.getOrganName() +")"); + + vo.setDemadnTargets(this.getDemandTartgetArray(vo.getProcessCode(), vo.getOrganCode())); + all.put(vo.getProcessCode() + vo.getOrganCode(), vo); + } + + return all; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIMFC001"); + throw new DAOException(errMsg); //요구송신 전체 대외기관 연결정보 로딩시 오류가 발생하였습니다. + } finally { + this.disconnect(); + } + } + + private DemandTargetVO[] getDemandTartgetArray(String processCode, String organCode) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + + super.preparedStatement = conn.prepareStatement(GET_DETAIL_DEMAND_TARGETS); + //logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 수행 SQL 문 : \n"+ GET_DETAIL_DEMAND_TARGETS); + + index = 1; + this.preparedStatement.setString(index++, processCode); //logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 바인드("+(index-1)+") : ["+ processCode +"]"); + this.preparedStatement.setString(index++, organCode ); //logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 바인드("+(index-1)+") : ["+ organCode +"]"); + + rs = executeQuery(); + + ArrayList aList = new ArrayList(); + while (rs.next()) { + DemandTargetVO vo = new DemandTargetVO(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7)); + logger.debug(" > 대외기관 요구송수신 연결 정보 ☞ (IP: "+ vo.getIpAddress() +", Port: "+ vo.getPortNumber() +", ID: "+ vo.getSocketID() +", PW: "+ vo.getSocketPwd() +", Timeout: "+ vo.getTimeoutInterval() +", OrganStatus: "+ vo.getOrganSocketStatus() +")"); + aList.add(vo); + } + + //logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 요구송수신 시스템 연결정보 건수: "+ aList.size()); + if (aList.size() == 0) { + logger.debug(" > 대외기관 요구송수신 연결 정보 없음"); + return new DemandTargetVO[0]; + } + + DemandTargetVO[] demandTargetArray = new DemandTargetVO[aList.size()]; + aList.toArray(demandTargetArray); + + return demandTargetArray; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIMFC002", new String[] {processCode, organCode}); + throw new DAOException(errMsg); //요구송신 업무구분(%1) 대외기관(%2)에 해당하는 연결정보 로딩시 오류가 발생하였습니다. + } finally { + //ResultSet 과 PreparedStatement 만 close. Connection 은 Close 하면 안됨 + try { if (rs!=null) rs.close(); } catch (Exception e) {throw new DAOException("BECEAICDB106");} + super.closeStatement(); + } + } + + public BatchTargetVO getBatchTargetVO(String processCode, String organCode) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + + this.connect(GET_BATCH_TARGETS); + //logger.debug("FlowControllerDAO.getBatchTargetVO() >>> 수행 SQL 문 : \n"+ GET_BATCH_TARGETS); + + index = 1; + this.preparedStatement.setString(index++, processCode); //logger.debug("FlowControllerDAO.getBatchTargetVO() >>> 바인드("+(index-1)+") : ["+ processCode +"]"); + this.preparedStatement.setString(index++, organCode ); //logger.debug("FlowControllerDAO.getBatchTargetVO() >>> 바인드("+(index-1)+") : ["+ organCode +"]"); + + rs = executeQuery(); + + if (rs.next() == false) { + //logger.debug("ResponseFlowDAO.getBatchTargetVO() >>> 요구송수신 시스템정보 건수: 0"); + String errMsg = ExceptionUtil.getErrorCode("BECEAIMFC003", new String[] {processCode, organCode}); + throw new DAOException(errMsg); //업무구분(%1)의 대외기관(%2) 정보가 등록되지 않았습니다. + } + + //logger.debug("ResponseFlowDAO.getBatchTargetVO() >>> 요구송수신 시스템정보 건수: 1"); + BatchTargetVO vo = new BatchTargetVO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)); + logger.debug(" - 대외기관 정보 로딩됨 ("+ vo.getProcessCode() +": "+ vo.getProcessName() +", "+ vo.getOrganCode() +": "+ vo.getOrganName() +")"); + vo.setDemadnTargets(this.getDemandTartgetArray(vo.getProcessCode(), vo.getOrganCode())); + return vo; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIMFC002", new String[] {processCode, organCode}); + throw new DAOException(errMsg); //요구송신 업무구분(%1) 대외기관(%2)에 해당하는 연결정보 로딩시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + + + + + /** + * 1. 기능 : 전달된 UUID에 해당하는 MsgPrcssStusCd 정보를 반환한다. + * 2. 처리 개요 : 전달된 UUID에 해당하는 MsgPrcssStusCd 정보를 읽어온다. + * 3. 주의사항 + * + * @return + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 전문 정보를 가져오다 발생되는 모든 에러 + **/ + public String getStatusCode(String uuid) throws DAOException + { + try + { + ResultSet rs = null; + String statusCode = ""; + + // 연결정보의 전체 갯수를 읽어온다. + this.connect(GET_STATUS_CODE); + this.preparedStatement.setString(1, uuid); + rs = this.executeQuery(); + + if(rs.next()) { + statusCode = rs.getString(1); + } else { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMFC008", new String[] {uuid}); + throw new DAOException(errMsg); //작업진행 테이블에 해당 정보가 없습니다. (UUID: %1) + } + rs.close(); + + return statusCode; + } catch(Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIMFC009", new String[] {uuid}); + throw new DAOException(errMsg); //작업진행 테이블에서 해당 작업의 상태 정보 조회시 오류가 발생하였습니다. (UUID: %1) + } finally { + this.disconnect(); + } + } + + + public int updateSystemConnLineStatus(String processCode, String organCode, String lineStatus) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + this.connect(UPDATE_SYSTEM_CONN_LINE_STATUS); + //logger.debug("FlowControllerDAO.updateSystemConnLineStatus() >>> 수행 SQL 문 : \n"+ ResponseFlowQuery.UPDATE_SYSTEM_CONN_LINE_STATUS); + + index = 1; + this.preparedStatement.setString(index++, lineStatus ); //logger.debug("ResponseFlowDAO.updateSystemConnLineStatus() >>> 바인드("+(index-1)+") : ["+ lineStatus +"]"); + this.preparedStatement.setString(index++, processCode); //logger.debug("ResponseFlowDAO.updateSystemConnLineStatus() >>> 바인드("+(index-1)+") : ["+ processCode +"]"); + this.preparedStatement.setString(index++, organCode ); //logger.debug("ResponseFlowDAO.updateSystemConnLineStatus() >>> 바인드("+(index-1)+") : ["+ organCode +"]"); + + retValue = this.executeUpdate(); + logger.debug("FlowControllerDAO.updateSystemConnLineStatus() >>> 연결 회선 상태 UPDATE 건 수 : "+ retValue); + + if (retValue == 0) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFRF010", new String[] {lineStatus}); + throw new DAOException(errMsg); //대외기관 연결정보 테이블에 회선 상태 update 건수가 0 건입니다. (회선상태: {1}) + } + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFRF011", new String[] {lineStatus}); + throw new DAOException(errMsg); //대외기관 연결정보 테이블에 회선 상태 update 시 오류가 발생하였습니다.(회선상태: {1}) + } finally { + disconnect(); + } + return retValue; + } + + +} diff --git a/src/com/eactive/eai/batch/flowController/FlowControllerManager.java b/src/com/eactive/eai/batch/flowController/FlowControllerManager.java new file mode 100644 index 0000000..973b0da --- /dev/null +++ b/src/com/eactive/eai/batch/flowController/FlowControllerManager.java @@ -0,0 +1,251 @@ +package com.eactive.eai.batch.flowController; + +import java.util.HashMap; +import java.util.Iterator; + +import com.eactive.eai.agent.AgentUtil; +import com.eactive.eai.agent.command.Command; +import com.eactive.eai.agent.flowController.UpdateBatchTargetCommand; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +/** +* 1. 기능 : Flow Controller에서 사용하는 메소드들의 모임 +* 2. 처리 개요 : 대부분의 값은 메모리에 로딩하지 않는 것으로 한다. +* 3. 주의사항 +* +* @author : YCLee 2006/1/11 +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class FlowControllerManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * EAIServerManager Single Instance + */ + private static FlowControllerManager instance = new FlowControllerManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * BatchTargetVO들을 저장하는 HashMap + */ + private HashMap targets; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : Flow Rule 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private FlowControllerManager() { + targets = new HashMap(); + } + + /** + * 1. 기능 : FlowControllerManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : FlowControllerManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return FlowControllerManager Singleton object + **/ + public static FlowControllerManager getInstance() { + return instance; + } + + /* ****************************************************************** */ + /* FlowControllerManager 자체적인 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : 요구 송수신에서 사용할 대외기관의 연결 정보를 반환한다. + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @return XML을 담고 있는 String 객체 반환 + * @exception + **/ + public DemandTargetVO[] getRemoteHostInfo(String processCode, String organCode) + { + if((BatchTargetVO)targets.get(processCode + organCode) == null) + return null; + else + return ((BatchTargetVO)targets.get(processCode + organCode)).getDemadnTargets(); + } + + public BatchTargetVO getBatchTargetInfo(String processCode, String organCode) + { + return (BatchTargetVO)targets.get(processCode + organCode); + } + + public HashMap getTargets() + { + return targets; + } + + /** + * 1.기능: F/C에서 요청 처리중 운영자에 의해서 해당 건이 취소되었는지를 확인하는 메소드 + */ + public boolean getStatusCode(String uuid) throws Exception + { + FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class); + + //반환값이 C(사용자취소)인 경우만 false로 반환한다. + if (dao.getStatusCode(uuid).equals("C")) + return false; + else + return true; + } + + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 FlowControllerManager 초기화하는 메서드 + * 2. 처리 개요 : FlowControllerDAO를 이용해 대상 기관의 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) throw new LifecycleException("BECEAIMFC010"); //FlowControllerManager 가 이미 시작되었습니다. + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + try { + FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class); + this.targets = dao.getAllTargets(); + + } catch (DAOException e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIMFC011"); + throw new LifecycleException(errMsg); //Lifecycle 에서 FlowControllerManager 시작 시 (대외기관 별 연결정보 로딩) 오류가 발생하였습니다. + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMFC012"); //FlowControllerManager 가 이미 종료되었습니다. + + this.targets.clear(); + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + + public int updateSystemConnLineStatus(String processCode, String organCode, String lineStatus) throws Exception { + logger.debug("▣▣▣▣▣ =================================================================================="); + logger.debug("▣▣▣▣▣ ★ 응답수신 '회선 "+ (lineStatus.equals(DemandTargetVO.ORGAN_SOCKET_STATUS_NORNAL)? "장애회복" : "장애") +" 통보 전문' 처리 Start......"); + logger.debug("▣▣▣▣▣ - 업무구분코드 : ["+ processCode +"]"); + logger.debug("▣▣▣▣▣ - 대외기관코드 : ["+ organCode +"]"); + + logger.debug("▣▣▣▣▣ ① 해당 대외기관의 전체 연결정보 DB Update......"); + FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class); + int resultCnt = dao.updateSystemConnLineStatus(processCode, organCode, lineStatus); + + logger.debug("▣▣▣▣▣ ② Agent를 통한 모든 서버의 연결정보 HashMap Update......"); + Command command = new UpdateBatchTargetCommand(); + String[] args = new String[] {processCode, organCode, lineStatus}; + command.setArgs(args); + HashMap map = AgentUtil.broadcast(command); + + Iterator it = map.keySet().iterator(); + while (it.hasNext()) { + String svrName = it.next(); + String resultStr = (String) map.get(svrName); + logger.debug("▣▣▣▣▣ - '"+ svrName +"' 서버 호출 결과: "+ resultStr); + } + logger.debug("▣▣▣▣▣ =================================================================================="); + + return resultCnt; + } + +} + diff --git a/src/com/eactive/eai/batch/flowController/FlowControllerQuery.java b/src/com/eactive/eai/batch/flowController/FlowControllerQuery.java new file mode 100644 index 0000000..05bf804 --- /dev/null +++ b/src/com/eactive/eai/batch/flowController/FlowControllerQuery.java @@ -0,0 +1,69 @@ +package com.eactive.eai.batch.flowController; + +import com.eactive.eai.common.dao.Keys; +/** +* 1. 기능 : FlowControllerDAO에서 사용하는 SQL Query를 정의한 Interface +* 2. 처리 개요 : +* - FlowControllerDAO에서 사용하는 SQL Query를 정의한 Interface +* 3. 주의사항 +* +* @author : YCLee 05/12/22 +* @version : v 1.0.0 +* @see : +* @since :JDK v1.4.2 +*/ +public interface FlowControllerQuery +{ + /** + * 업무 기본 정보를 조회하는 Query + */ + public static final String GET_ALL_TARGETS = "select A.BjobBzwkDstcd, A.BjobBzwkName, LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd, B.OsidInstiName \n" + + "from " + Keys.TABLE_OWNER + "TSEAIBJ02 A, " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" + + "where A.BjobBzwkDstcd = B.BjobBzwkDstcd \n" + + "and A.ThisMsgUseYn = '1' \n" + + "and B.ThisMsgUseYn = '1' \n"; + + /** + * 업무 기본 정보를 조회하는 Query + */ + public static final String GET_BATCH_TARGETS = "select A.BjobBzwkDstcd, A.BjobBzwkName, LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd, B.OsidInstiName \n" + + "from " + Keys.TABLE_OWNER + "TSEAIBJ02 A, " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" + + "where A.BjobBzwkDstcd = B.BjobBzwkDstcd \n" + + "and B.BjobBzwkDstcd like ?||'%' \n" + + "and LTRIM(RTRIM(B.OsidInstiDstcd)) = ? \n"+ + "and A.ThisMsgUseYn = '1' \n" + + "and B.ThisMsgUseYn = '1' \n"; + + /** + * 업무별 요구송수신 상세 연결 정보를 조회하는 Query + */ + public static final String GET_DETAIL_DEMAND_TARGETS = + "select SysLnkgDstcd, LnkgIPInfoName, LnkgPortInfoName, LnkgID, LnkgPwd, ToutVal, TCirtLnkgStusCd \n" + + "from " + Keys.TABLE_OWNER + "TSEAIBJ05 \n" + + "where BjobBzwkDstcd like ?||'%' \n" + + "and LTRIM(RTRIM(OsidInstiDstcd)) = ? \n"+ + "and RqstRspnsDstcd = 'R' \n" + + "and ThisMsgUseYn = '1' "; + + /** + * 해당 요청의 현재 status를 반환한다. + */ + public static final String GET_STATUS_CODE = "select MsgPrcssStusCd "+ + "from " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "where BjobDmndMsgID = ? "; + + /** + * 응답수신 Flow Controller에서 시스템 장애 통보 및 회복 통보 전문을 받았을때 회선 상태를 update 한다. + * 해당 대외기관의 요구송수신 연결정보 전체 update + */ + public static final String UPDATE_SYSTEM_CONN_LINE_STATUS = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ05 \n" + + "SET TCirtLnkgStusCd = ? \n" + + "WHERE BjobBzwkDstcd LIKE ?||'%' \n" + + "AND LTRIM(RTRIM(OsidInstiDstcd)) = ? \n" + + "AND RqstRspnsDstcd = 'R'"; + + +} + + diff --git a/src/com/eactive/eai/batch/flowController/Keys.java b/src/com/eactive/eai/batch/flowController/Keys.java new file mode 100644 index 0000000..28d7dd3 --- /dev/null +++ b/src/com/eactive/eai/batch/flowController/Keys.java @@ -0,0 +1,24 @@ +package com.eactive.eai.batch.flowController; + +/** +* 1. 기능 : server 패키지에서 사용하는 상수를 정의한 Interface +* 2. 처리 개요 : +* - server 패키지에서 사용하는 상수를 정의한 Interface +* 3. 주의사항 +* +* @author : YCLee 05/12/22 +* @version : v 1.0.0 +* @see : TestCallRunner, TestCallManager +* @since :JDK v1.4.2 +*/ +public class Keys +{ + /** + * EAI 배치 프레임웍에서 임시로 사용하는 기본 DataSource에 대한 JNDI 이름 + */ + public static final String EAI_BATCH_TEMP_DATASOURCE = "SONGDataSource"; + + + + +} diff --git a/src/com/eactive/eai/batch/ftp/FTPAdaptor.java b/src/com/eactive/eai/batch/ftp/FTPAdaptor.java new file mode 100644 index 0000000..0424da8 --- /dev/null +++ b/src/com/eactive/eai/batch/ftp/FTPAdaptor.java @@ -0,0 +1,692 @@ +package com.eactive.eai.batch.ftp; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class FTPAdaptor { + +// private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_ADAPTER); + + protected static FTPFile[] listFiles(String server, int port, String username, String password, String path, HashMap extmap, Logger logger) throws IOException { + logger.debug("[FTP connect]server -->" + server); + logger.debug("[FTP connect]port -->" + port); + logger.debug("[FTP connect]username-->" + username); + logger.debug("[FTP connect]password-->" + password); + logger.debug("[FTP listFiles]path-->" + path); + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + ftpClient.connect(server, port); + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg )); + } + + if (extmap == null) { + FTPFile[] tmpfiles = ftpClient.listFiles(path); + for (int jnx = 0; jnx < tmpfiles.length; jnx++) { + String filename = tmpfiles[jnx].getName(); + tmpfiles[jnx].setName(filename.replace(path, "")); + } + return tmpfiles; + } else { + ArrayList list = new ArrayList(); + int returnCnt = 0; + for (int inx = 0; inx < extmap.size(); inx++) { + String ext = extmap.get(inx); + FTPFile[] tmpfiles = ftpClient.listFiles(path + "/*." + ext); + for (int jnx = 0; jnx < tmpfiles.length; jnx++) { + String filename = tmpfiles[jnx].getName(); + tmpfiles[jnx].setName(filename.replace(path, "")); + list.add(tmpfiles[jnx]); + returnCnt++; + } + } + FTPFile[] files = new FTPFile[returnCnt]; + list.toArray(files); + return files; + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new IOException(e.getMessage()); + } finally { + ftpClient.quit(); + } + + } + + // 20241008 FTPFileObject 사용 + protected static FTPFileObject[] listFiles2(String server, int port, String username, String password, String path, Logger logger) throws IOException { + logger.debug("[FTP connect]server -->" + server); + logger.debug("[FTP connect]port -->" + port); + logger.debug("[FTP connect]username-->" + username); + logger.debug("[FTP connect]password-->" + password); + logger.debug("[FTP listFiles]path-->" + path); + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + ftpClient.connect(server, port); + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg )); + } + + FTPFile[] tmpfiles = ftpClient.listFiles(path); + for (int jnx = 0; jnx < tmpfiles.length; jnx++) { + String filename = tmpfiles[jnx].getName(); + tmpfiles[jnx].setName(filename.replace(path, "")); + } + + ArrayList oFiles = new ArrayList(); + FTPFileObject[] rFiles = new FTPFileObject[tmpfiles.length]; + FTPFileObject nFile; + for(FTPFile file :tmpfiles){ + nFile = new FTPFileObject(); + nFile.setFile(file.isFile()); + nFile.setName(file.getName()); + nFile.setSize(file.getSize()); + oFiles.add(nFile); + } + oFiles.toArray(rFiles); + + return rFiles; + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new IOException(e.getMessage()); + } finally { + ftpClient.quit(); + } + + } + + protected static long retrieve(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String localPath, int bandWidthLimit, Logger logger, String ftpFileType) throws Exception { + + logger.debug("[FTP retrieve]remote-->" + remote); + logger.debug("[FTP retrieve]localPath-->" + localPath); + long size = -1; + + BufferedOutputStream bos = null; + BufferedInputStream bis = null; + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + + ftpClient.connect(server, port); + if("ASCII".equals(ftpFileType)) + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); + else + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg )); + } + + File chkDir = new File(localPath); + String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(localPath); + String fName = remote.substring(remote.lastIndexOf(delimiter) + 1); + logger.debug("[retrieve]fName ------->" + fName); + + if (!chkDir.exists() && !chkDir.mkdirs()) { + logger.error("[체크파일을 생성할 수 없습니다.]"); // 상위 디렉토리 미 존재시에도 write 한다. + return -1; + } + + File file = new File(localPath + delimiter + fName); + OutputStream output = new FileOutputStream(file); + + if(bandWidthLimit > 0){ + /** + * 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit), + */ + //Buffer buffer = new Buffer(1024); + //int bandWidth = 1024*8; + long bufferSize = bandWidthLimit/8; + byte[] bufferArr = new byte[(int)bufferSize]; + + try { + bos = new BufferedOutputStream(output); + bis = new BufferedInputStream(ftpClient.retrieveFileStream(remote)); + batchDoc.setIOStream(bis); + + int readCount = 0; + int lootCnt = 0; + + long[] timeMillis = new long[2]; + timeMillis[0] = System.currentTimeMillis(); + + long rtt = 0;//round trip time 1회 전송시간 millisecond + long rttMax = 0; + long rttMin = 0; + double rttAve = 0; + long rttSum = 0; + + long realBandWidth = 0; + long realBandWidthMax = 0; + long realBandWidthMin = 0; + double realBandWidthAve = 0; + long realBandWidthSum = 0; + long readByteSum = 0; + + long sizeStartTime = 0; + long sizePerSecond = 0; + int sleepTimeCriteria = 990; + + while (true){ + + lootCnt++; + sleepTimeCriteria = 990; //여유 10milli + + //강제중지 설정시 + if (batchDoc.isUserCancel()){ + throw new Exception("사용자가 전송을 중지 했습니다."); + } + + timeMillis[0] = System.currentTimeMillis(); + readCount = bis.read(bufferArr); + timeMillis[1] = System.currentTimeMillis(); + if(readCount<=0) break; + + bos.write(bufferArr,0,readCount); + + readByteSum += readCount; + batchDoc.setCurrIODataByte(readByteSum); + + if (sizePerSecond > 0){ + rtt = timeMillis[1] - sizeStartTime; + } else { + rtt = timeMillis[1] - timeMillis[0]; + } + + + if(rtt<=0 ){ + //rtt=1;//local test시 0이 발생 divide by zero오류 발생, 방어코드 + if(sizeStartTime==0)sizeStartTime = timeMillis[0]; + sizePerSecond += readCount; + + if(sizePerSecond >= bufferArr.length){ + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 990 sec, readCount["+readCount+"]sizePerSecond["+sizePerSecond+"]readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]"); + Thread.sleep(990); + sizePerSecond = 0; + sizeStartTime = 0; + } else { + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 0 sec, readCount["+readCount+"]sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]"); + } + continue; + } + + if ( readCount < bufferArr.length || sizePerSecond> 0){ + + if(sizeStartTime==0)sizeStartTime = timeMillis[0]; + sizePerSecond += readCount; + + if(sizePerSecond>0 && sizePerSecond < bufferArr.length){ + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] SLEEP 0 sec readCount["+readCount+"] sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]"); + + continue; + } + + } + + if (sizePerSecond > 0){ + realBandWidth = (long) (sizePerSecond * 8 * 1000 / rtt); + } else { + realBandWidth = (long) (bufferSize * 8 * 1000 / rtt); + } + + + //min, max, sum + rttSum += rtt; + if (rtt > rttMax)rttMax = rtt; + else if (rtt < rttMin)rttMin = rtt; + + realBandWidthSum += realBandWidth; + if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth; + else if(realBandWidth 0 && sizePerSecond>bufferSize){ + sleepTimeCriteria = (int) (sleepTimeCriteria*sizePerSecond/bufferSize); + } + + + + if(rtt < sleepTimeCriteria){ + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(sleepTimeCriteria-rtt)+"]sleepTimeCriteria["+sleepTimeCriteria+"]"); + + Thread.sleep((long) (sleepTimeCriteria-rtt)); + } else { + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]sleepTimeCriteria["+sleepTimeCriteria+"]"); + + } + + sizePerSecond = 0; + sizeStartTime = 0; + + } + + realBandWidthAve = realBandWidthSum/lootCnt; + rttAve = rttSum/lootCnt; + + logger.info("SFTPAdaptor] ####Statistics : bufferSize["+bufferSize + +"] loopCnt["+lootCnt + +"] readByteSum["+readByteSum + +"] rttAve["+rttAve + +"] rttMax["+rttMax + +"] rttMin["+rttMin + +"] bandWidthLimit["+bandWidthLimit + +"] realBandWidthAve["+realBandWidthAve + +"] realBandWidthMax["+realBandWidthMax + +"] realBandWidthMin["+realBandWidthMin + +"]"); + + } finally { + if (bos != null){ + bos.flush(); + bos.close(); + } + + if (bis != null)bis.close(); + if(output!=null) output.close(); + } + } else { + ftpClient.retrieveFile(remote, output); + if(output!=null) output.close(); + } + + if ( file.exists() ) + size = file.length(); + + // check the reply code to verify success + int reply = ftpClient.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + logger.warn("Command failed: " + ftpClient.getReplyString()); + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + + if (ftpClient != null) + ftpClient.quit(); + } + return size; + } + + protected static long retrieve(String server, int port, String username, String password, String remote, String localPath, Logger logger) throws Exception { + + logger.debug("[FTP retrieve]remote-->" + remote); + logger.debug("[FTP retrieve]localPath-->" + localPath); + long size = -1; + + //BufferedOutputStream bos = null;// 20250910 + //BufferedInputStream bis = null;// 20250910 + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + + ftpClient.connect(server, port); + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg )); + } + + File chkDir = new File(localPath); + String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(localPath); + String fName = remote.substring(remote.lastIndexOf(delimiter) + 1); + logger.debug("[retrieve]fName ------->" + fName); + + if (!chkDir.exists() && !chkDir.mkdirs()) { + logger.error("[체크파일을 생성할 수 없습니다.]"); // 상위 디렉토리 미 존재시에도 write 한다. + return -1; + } + + File file = new File(localPath + delimiter + fName); + OutputStream output = new FileOutputStream(file); + + ftpClient.retrieveFile(remote, output); + output.close(); + + if ( file.exists() ) + size = file.length(); + + // check the reply code to verify success + int reply = ftpClient.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + logger.warn("Command failed: " + ftpClient.getReplyString()); + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if (ftpClient != null) + ftpClient.quit(); + } + return size; + } + + protected static boolean store(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String localPath, int bandWidthLimit, Logger logger) throws Exception { + logger.debug("[FTP store]remote-->" + remote); + logger.debug("[FTP store]localPath-->" + localPath); + + BufferedOutputStream bos = null; + BufferedInputStream bis = null; + FileInputStream input = null; + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + + ftpClient.connect(server, port); + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg )); + } + + File file = new File(localPath); + + String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(remote); + String remotePath = remote.substring(0,remote.lastIndexOf(delimiter)); + String fileName = remote.substring(remote.lastIndexOf(delimiter) + 1); + + logger.debug("[FTP store]remotePath-->" + remotePath); + logger.debug("[FTP store]fileName-->" + fileName); + + boolean cd = ftpClient.changeWorkingDirectory(remotePath); + if ( !cd ){ + ftpClient.makeDirectory(remotePath); + ftpClient.changeWorkingDirectory(remotePath); + } + + input = new FileInputStream(file); + + if(bandWidthLimit > 0){ + /** + * 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit), + */ + //Buffer buffer = new Buffer(1024); + //int bandWidth = 1024*8; + long bufferSize = bandWidthLimit/8; + byte[] bufferArr = new byte[(int)bufferSize]; + + try { + bos = new BufferedOutputStream(ftpClient.storeFileStream(remote)); + bis = new BufferedInputStream(input); + batchDoc.setIOStream(bos); + + int readCount = 0; + int lootCnt = 0; + + long[] timeMillis = new long[2]; + timeMillis[0] = System.currentTimeMillis(); + + long rtt = 0;//round trip time 1회 전송시간 millisecond + long rttMax = 0; + long rttMin = 0; + double rttAve = 0; + long rttSum = 0; + + long realBandWidth = 0; + long realBandWidthMax = 0; + long realBandWidthMin = 0; + double realBandWidthAve = 0; + long realBandWidthSum = 0; + long writeByteSum = 0; + + long sizeStartTime = 0; + long sizePerSecond = 0; + + while (true){ + + lootCnt++; + + + //강제중지 설정시 + if (batchDoc.isUserCancel()){ + throw new Exception("사용자가 전송을 중지 했습니다."); + } + + readCount = bis.read(bufferArr); + if(readCount<=0) break; + + + //****sftp send...... + timeMillis[0] = System.currentTimeMillis(); + bos.write(bufferArr,0,readCount); + timeMillis[1] = System.currentTimeMillis(); + + writeByteSum += readCount; + batchDoc.setCurrIODataByte(writeByteSum); + + if (sizePerSecond > 0){ + rtt = timeMillis[1] - sizeStartTime; + } else { + rtt = timeMillis[1] - timeMillis[0]; + } + + if(rtt<=0){ + if(sizeStartTime==0)sizeStartTime = timeMillis[0]; + sizePerSecond += readCount; + realBandWidth = 0; + }else { + //rtt가 0보다 커야 bandwidth계산 + realBandWidth = (long) ((sizePerSecond+bufferSize) * 8 * 1000 / rtt); + + sizeStartTime = 0; + sizePerSecond = 0; + } + + realBandWidthSum += realBandWidth; + if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth; + else if(realBandWidth rttMax)rttMax = rtt; + else if (rtt < rttMin)rttMin = rtt; + + //1초이내로 처리가 된경우sleep,, 여유 10milli + if(rtt < 990){ //여유 10milli + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(990-rtt)+"]"); + + Thread.sleep((long) (990-rtt)); + + + } else { + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]"); + } + } + + realBandWidthAve = realBandWidthSum/lootCnt; + rttAve = rttSum/lootCnt; + + logger.info("SFTPAdaptor] ####Statistics : bufferSize["+bufferSize + +"] loopCnt["+lootCnt + +"] writeByteSum["+writeByteSum + +"] rttAve["+rttAve + +"] rttMax["+rttMax + +"] rttMin["+rttMin + +"] bandWidthLimit["+bandWidthLimit + +"] realBandWidthAve["+realBandWidthAve + +"] realBandWidthMax["+realBandWidthMax + +"] realBandWidthMin["+realBandWidthMin + +"]"); + + } finally { + try { + if (bos != null){ + bos.flush(); + bos.close(); + } + + if (bis != null)bis.close(); + if(input!=null) input.close(); + } catch (Throwable t){ + logger.error("Closing Error:"+t.getMessage()); + } + } + } else { + ftpClient.storeFile(fileName, input); + if(input!=null) input.close();// 20250910 obl + } + + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if (ftpClient != null) ftpClient.disconnect(); + } + return true; + } + + protected static boolean store(String server, int port, String username, String password, String remote, String localPath, Logger logger) throws Exception { + + logger.debug("[FTP store]remote-->" + remote); + logger.debug("[FTP store]localPath-->" + localPath); + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + + ftpClient.connect(server, port); + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg )); + } + + File file = new File(localPath); + + String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(remote); + String remotePath = remote.substring(0,remote.lastIndexOf(delimiter)); + String fileName = remote.substring(remote.lastIndexOf(delimiter) + 1); + + logger.debug("[FTP store]remotePath-->" + remotePath); + logger.debug("[FTP store]fileName-->" + fileName); + + boolean cd = ftpClient.changeWorkingDirectory(remotePath); + if ( !cd ){ + ftpClient.makeDirectory(remotePath); + ftpClient.changeWorkingDirectory(remotePath); + } + + FileInputStream input = new FileInputStream(file); + ftpClient.storeFile(fileName, input); + input.close(); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if (ftpClient != null) + ftpClient.quit(); + } + return true; + } + + protected static boolean rename(String server, int port, String username, String password, String srcname, String tarname, Logger logger) throws Exception { + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + + ftpClient.connect(server, port); + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( + "BECEAIMEU016", arg)); + } + + ftpClient.rename(srcname, tarname); + + ftpClient.quit(); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if (ftpClient != null) + ftpClient.quit(); + } + return true; + } + + protected static boolean delete(String server, int port, String username, String password, String srcname, Logger logger) throws Exception { + + FTPClient ftpClient = new FTPClient(); + try { + ftpClient.setControlEncoding("euc-kr"); + + ftpClient.connect(server, port); + ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + if (!ftpClient.login(username, password)) { + ftpClient.logout(); + String arg[] = new String[1]; + arg[0] = username; + throw new IOException(ExceptionUtil.getErrorCode( + "BECEAIMEU016", arg)); + } + + ftpClient.deleteFile(srcname); + + ftpClient.quit(); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if (ftpClient != null) + ftpClient.quit(); + } + return true; + } + +} diff --git a/src/com/eactive/eai/batch/ftp/FTPFileObject.java b/src/com/eactive/eai/batch/ftp/FTPFileObject.java new file mode 100644 index 0000000..28c65f6 --- /dev/null +++ b/src/com/eactive/eai/batch/ftp/FTPFileObject.java @@ -0,0 +1,29 @@ +package com.eactive.eai.batch.ftp; + +public class FTPFileObject { + + private boolean file ; + private String name ; + private long size; + public boolean isFile() { + return file; + } + public void setFile(boolean file) { + this.file = file; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public long getSize() { + return size; + } + public void setSize(long size) { + this.size = size; + } + + + +} diff --git a/src/com/eactive/eai/batch/ftp/FTPUtil.java b/src/com/eactive/eai/batch/ftp/FTPUtil.java new file mode 100644 index 0000000..78846d3 --- /dev/null +++ b/src/com/eactive/eai/batch/ftp/FTPUtil.java @@ -0,0 +1,106 @@ +package com.eactive.eai.batch.ftp; + +import java.io.IOException; +import java.util.HashMap; + +import org.apache.commons.net.ftp.FTPFile; +import com.eactive.eai.common.util.Logger; + +import com.eactive.eai.batch.doc.BatchDoc; + +public class FTPUtil { + + public static FTPFile[] listFiles(String server, int port, String username, String password, String path, HashMap extmap, boolean isSftp, Logger logger, String authType) + throws IOException { + if ( isSftp ){ + return SFTPAdaptor.listFiles(server, port, username, password, path, extmap, logger, authType); + }else{ + return FTPAdaptor.listFiles(server, port, username, password, path, extmap, logger); + } + + } + // 20241008 sftp jsch 방식 list + public static FTPFileObject[] listFilesJSCH(String server, int port, String username, String password, String path, boolean isSftp, Logger logger, String authType) + throws IOException { + if ( isSftp ){ + return SFTPAdaptor.listFilesJSCH(server, port, username, password, path, logger, authType); + }else{ + return FTPAdaptor.listFiles2(server, port, username, password, path, logger); + } + } + + public static long retrieve(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String remoteFileName, String localPath, + int connTimeout, int setTimeout, boolean isSftp, int bandWidth, Logger logger, String authType) throws Exception { + + if ( isSftp ){ + return SFTPAdaptor.retrieveJSCH(batchDoc, server, port, username, password, remote, remoteFileName, localPath, connTimeout, setTimeout, bandWidth, logger, authType); + }else{ + return FTPAdaptor.retrieve(batchDoc,server, port, username, password, remote+remoteFileName, localPath, bandWidth, logger, ""); + } + } + + public static long retrieve(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String remoteFileName, String localPath, + int connTimeout, int setTimeout, int bandWidth, Logger logger, String authType, String fileType) throws Exception { + if ( "0".equals(authType)) { + return FTPAdaptor.retrieve(batchDoc,server, port, username, password, remote+remoteFileName, localPath, bandWidth, logger, fileType); + }else { + return SFTPAdaptor.retrieveJSCH(batchDoc, server, port, username, password, remote, remoteFileName, localPath, connTimeout, setTimeout, bandWidth, logger, authType); + } + } + + public static long retrieve(String server, int port, String username, String password, String remote, String localPath, boolean isSftp, Logger logger, String authType) throws Exception { + + if ( isSftp ){ + return SFTPAdaptor.retrieve(server, port, username, password, remote, localPath, logger, authType); + }else{ + return FTPAdaptor.retrieve(server, port, username, password, remote, localPath, logger); + } + } + + public static boolean store(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String remoteFileName, String localPath, + int connTimeout, int setTimeout, boolean isSftp, int bandWidth, Logger logger, String authType) throws Exception { + + if ( isSftp ){ + return SFTPAdaptor.storeJSCH(batchDoc, server, port, username, password, remote, remoteFileName, localPath, connTimeout, setTimeout, bandWidth, logger, authType); + }else{ + return FTPAdaptor.store(batchDoc,server, port, username, password, remote+remoteFileName, localPath, bandWidth, logger); + } + } + + /** + * + * @param authType 1: ID 인증, 2: 키인증 + */ + public static boolean store(String server, int port, String username, String password, String remote, String localPath, boolean isSftp, Logger logger, String authType) throws Exception { + + if ( isSftp ){ + return SFTPAdaptor.store(server, port, username, password, remote, localPath, logger, authType); + }else{ + return FTPAdaptor.store(server, port, username, password, remote, localPath, logger); + } + + } + + public static boolean rename(String server, int port, String username, String password, String srcname, String tarname, boolean isSftp, Logger logger, String authType) throws Exception { + if ( isSftp ){ + return SFTPAdaptor.rename(server, port, username, password, srcname, tarname, logger, authType); + }else{ + return FTPAdaptor.rename(server, port, username, password, srcname, tarname, logger); + } + } + + /** + * KED backup을 위해서 만듬 + */ + public static boolean renameWithMkdirs(String server, int port, String username, String password, String srcname, String tarname, String filename, boolean isSftp, Logger logger, String authType) throws Exception { + return SFTPAdaptor.renameWithMkdirs(server, port, username, password, srcname, tarname, filename, logger, authType); + } + +// public static boolean delete(String server, int port, String username, String password, String srcname, boolean isSftp) throws Exception { +// if ( isSftp ){ +// return SFTPAdaptor.delete(server, port, username, password, srcname); +// }else{ +// return FTPAdaptor.delete(server, port, username, password, srcname); +// } +// } +} diff --git a/src/com/eactive/eai/batch/ftp/SFTPAdaptor.java b/src/com/eactive/eai/batch/ftp/SFTPAdaptor.java new file mode 100644 index 0000000..d646321 --- /dev/null +++ b/src/com/eactive/eai/batch/ftp/SFTPAdaptor.java @@ -0,0 +1,1280 @@ +package com.eactive.eai.batch.ftp; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTPFile; + +import com.eactive.eai.adapter.ftp.Transfer; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.util.Logger; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.ChannelSftp.LsEntry; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.SftpATTRS; +import com.jcraft.jsch.SftpException; + +import net.schmizz.sshj.SSHClient; +import net.schmizz.sshj.connection.Connection; +import net.schmizz.sshj.sftp.RemoteResourceInfo; +import net.schmizz.sshj.sftp.SFTPClient; +import net.schmizz.sshj.transport.TransportException; +import net.schmizz.sshj.transport.verification.PromiscuousVerifier; + +public class SFTPAdaptor { + private static void loadKnownHosts(SSHClient ssh) throws IOException { + // Host key 검사없이 인증 + ssh.addHostKeyVerifier(new PromiscuousVerifier()); + } + + + protected static FTPFile[] listFiles(String server, int port, String username, String password, String path, HashMap extmap, Logger logger, String authType) throws IOException { + logger.debug("[SFHT connect]server -->" + server); + logger.debug("[SFHT connect]port -->" + port); + logger.debug("[SFHT connect]username-->" + username); + logger.debug("[SFHT connect]password-->" + password); + logger.debug("[SFHT listFiles]path-->" + path); + + + SSHClient ssh = new SSHClient(); + try { + loadKnownHosts(ssh); + ssh.connect(server, port); + + // id 인증 + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_ID)) { + ssh.authPassword(username, password); + // key 방식 인증 + } else if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + if (StringUtils.isEmpty(password)) { + ssh.authPublickey(username); // 사용자 기본 + } else { + ssh.authPublickey(username, new File(password).getPath()); // private key 지정 + } + } + + SFTPClient sftp = ssh.newSFTPClient(); + logger.debug("sftp = " + sftp); + try{ + FTPFile[] files = null; + List list = sftp.ls(path); + // 라인이 너무 길어서 vi가 열리지 않음, 개발 라인으로 로깅 +// logger.debug("list = " + list); + files = new FTPFile[list.size()]; + for (int inx = 0; inx < list.size(); inx++) { + RemoteResourceInfo info =list.get(inx); + logger.debug("{"+info+"}"); + FTPFile file = new FTPFile(); + file.setName(info.getName()); + file.setSize(info.getAttributes().getSize()); + if ( info.isRegularFile() ) + file.setType(FTPFile.FILE_TYPE); + else if ( info.isDirectory() ) + file.setType(FTPFile.DIRECTORY_TYPE); + else + file.setType(FTPFile.UNKNOWN_TYPE); + + files[inx] = file; + } + return files; + }finally{ + sftp.close(); + } + + + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new IOException(e.getMessage()); + } finally { + if ( ssh != null && ssh.isConnected()) + ssh.close(); + } + + } +// protected static FTPFile[] listFiles_jsch(String server, int port, String username, String password, String path, HashMap extmap) throws IOException { +// logger.debug("[SFHT connect]server -->" + server); +// logger.debug("[SFHT connect]port -->" + port); +// logger.debug("[SFHT connect]username-->" + username); +// logger.debug("[SFHT connect]password-->" + password); +// logger.debug("[SFHT listFiles]path-->" + path); +// +// Session session = null; +// ChannelSftp sftpChannel = null; +// String[] serverList = server.split(","); +// try { +// +// for (int inx = 0; inx < serverList.length; inx++) { +// try { +// JSch jsch = new JSch(); +// +// session = jsch.getSession(username, serverList[inx], port); +// session.setPassword(password.getBytes()); +// session.setConfig("StrictHostKeyChecking", "no"); +// session.setTimeout(10 * 1000); +// session.connect(); +// +// } catch (JSchException e) { +// if ( inx == serverList.length -1) +// throw e; +// } +// } +// sftpChannel = (ChannelSftp) session.openChannel("sftp"); +// sftpChannel.connect(); +// +// FTPFile[] files = null; +// if (extmap == null) { +// @SuppressWarnings("unchecked") +// Vector v = sftpChannel.ls(path); +// files = new FTPFile[v.size()]; +// int inx = 0; +// for (Iterator iterator = v.iterator(); iterator.hasNext();) { +// LsEntry object = (LsEntry) iterator.next(); +// FTPFile file = new FTPFile(); +// SftpATTRS att = object.getAttrs(); +// file.setName(object.getFilename()); +// if (!att.isDir() && !att.isLink()) { +// file.setType(0); +// } +// file.setSize(att.getSize()); +// Calendar cal = new GregorianCalendar(); +// cal.setTime(new Date(att.getMTime())); +// files[inx++] = file; +// } +// } else { +// ArrayList list = new ArrayList(); +// for (int inx = 0; inx < extmap.size(); inx++) { +// String ext = extmap.get(inx); +// @SuppressWarnings("unchecked") +// Vector v = sftpChannel.ls(path + "/*." + ext); +// for (Iterator iterator = v.iterator(); iterator.hasNext();) { +// LsEntry object = (LsEntry) iterator.next(); +// FTPFile file = new FTPFile(); +// SftpATTRS att = object.getAttrs(); +// file.setName(object.getFilename()); +// if (!att.isDir() && !att.isLink()) { +// file.setType(0); +// } +// file.setSize(att.getSize()); +// Calendar cal = new GregorianCalendar(); +// cal.setTime(new Date(att.getMTime())); +// list.add(file); +// } +// } +// files = new FTPFile[list.size()]; +// list.toArray(files); +// } +// return files; +// +// } catch (JSchException e) { +// logger.error(e.getMessage(), e); +// throw new IOException(e.getMessage()); +// } catch (SftpException e) { +// logger.error(e.getMessage(), e); +// throw new IOException(e.getMessage()); +// } finally { +// if (sftpChannel != null) +// sftpChannel.disconnect(); +// if (session != null) +// session.disconnect(); +// } +// +// } + + /** + * 사용자 전송중지 기능 구현으로 JSch 사용 20220704 + * bandwidth 기능 구현 + * @param batchDoc + * @param server + * @param port + * @param username + * @param password + * @param remote + * @param localPath + * @param connTimeout + * @param setTimeout + * @param bandWidth : bit unit + * @param logger + * @return + * @throws Exception + */ + protected static long retrieveJSCH(BatchDoc batchDoc, String server, int port, String username, + String password, String remote, String remoteFileName, String localPath, int connTimeout, int setTimeout, int bandWidthLimit, Logger logger, String authType) throws Exception { + + logger.debug("[SFHT retrieve]remote-->" + remote); + logger.debug("[SFHT retrieve]localPath-->" + localPath); + + Session session = null; + ChannelSftp sftpChannel = null; + + try { + + JSch jsch = new JSch(); + + // 키 인증 방식인 경우 + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + jsch.addIdentity(password); + } + + session = jsch.getSession(username, server, port); + + // 키 인증 방식이 아닌 경우 + if (!StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + session.setPassword(password); + } + session.setConfig("StrictHostKeyChecking", "no"); + session.setConfig("max_input_buffer_size","increased_size"); + + if (connTimeout > 0)session.setTimeout(connTimeout*1000); + session.connect(); + if(setTimeout > 0) session.setTimeout(setTimeout * 1000); + + sftpChannel = (ChannelSftp) session.openChannel("sftp"); + //sftpChannel.setPtySize(arg0, arg1, arg2, arg3); + + sftpChannel.connect(); + logger.debug("SFTPAdaptor] ChannelSftp connected!! server:"+server+", port:"+port); + + if (batchDoc.isUserCancel()){ + throw new Exception("사용자가 전송을 중지 했습니다."); + } + + batchDoc.setSftpChannel(sftpChannel); + sftpChannel.cd(remote); + + retrieveJSCH(batchDoc, sftpChannel, remoteFileName, localPath, bandWidthLimit, logger); + } catch (JSchException e) { + logger.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + + batchDoc.setSftpChannel(null); + if (sftpChannel != null) sftpChannel.disconnect(); + if (session != null) session.disconnect(); + + } + return 0; + } + + protected static long retrieve(String server, int port, String username, + String password, String remote, String localPath, Logger logger, String authType) throws Exception { + + logger.debug("[SFHT retrieve]remote-->" + remote); + logger.debug("[SFHT retrieve]localPath-->" + localPath); + + SSHClient ssh = new SSHClient(); + try { + loadKnownHosts(ssh); + ssh.connect(server, port); + // id 인증 + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_ID)) { + ssh.authPassword(username, password); + // key 방식 인증 + } else if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + if (StringUtils.isEmpty(password)) { + ssh.authPublickey(username); // 사용자 기본 + } else { + ssh.authPublickey(username, new File(password).getPath()); // private key 지정 + } + } + SFTPClient sftp = ssh.newSFTPClient(); + File chkDir = new File(localPath); + String delimiter = StringUtil.getDirDelimiter(localPath); + String fName = remote.substring(remote.lastIndexOf(delimiter) + 1); + logger.debug("[retrieve]fName ------->" + fName); + + if (!chkDir.exists() && !chkDir.mkdirs()) { + logger.error("[수신 경로를 생성할 수 없습니다.]"); + return -1; + } + + try{ + sftp.get(remote,localPath); + }catch ( IOException ie){ + logger.error(ie.getMessage(), ie); + throw new Exception(ie.getMessage()); + }finally{ + sftp.close(); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if ( ssh != null && ssh.isConnected()) + ssh.close(); + } + return 0; + } + + /** + * bandWidth제한만큼 버퍼사이즈 설정해서 1초단위로 전송한다. + * @param batchDoc + * @param server + * @param port + * @param username + * @param password + * @param remote + * @param remoteFileName + * @param localFileName + * @param connTimeout + * @param setTimeout + * @param bandWidthLimit + * @param logger + * @return + * @throws Exception + */ + protected static boolean storeJSCH(BatchDoc batchDoc, String server, int port, String username, + String password, String remote, String remoteFileName, String localFileName, int connTimeout, int setTimeout, int bandWidthLimit, Logger logger, String authType) throws Exception { + + logger.debug("[SFHT storeJSCH]remote-->" + remote); + logger.debug("[SFHT storeJSCH]remoteFileName-->" + remoteFileName); + logger.debug("[SFHT storeJSCH]localFileName-->" + localFileName); + + Session session = null; + ChannelSftp sftpChannel = null; + BufferedOutputStream bos = null; + BufferedInputStream bis = null; + FileInputStream is = null; + + try { + + JSch jsch = new JSch(); + + // 키 인증 방식인 경우 + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + jsch.addIdentity(password); + } + + session = jsch.getSession(username, server, port); + + // 키 인증 방식이 아닌 경우 + if (!StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + session.setPassword(password); + } + + session.setConfig("StrictHostKeyChecking", "no"); + session.setConfig("max_input_buffer_size","increased_size"); + + if (connTimeout > 0)session.setTimeout(connTimeout*1000); + session.connect(); + if(setTimeout > 0) session.setTimeout(setTimeout * 1000); + + sftpChannel = (ChannelSftp) session.openChannel("sftp"); + //sftpChannel.setPtySize(arg0, arg1, arg2, arg3); + + sftpChannel.connect(); + logger.debug("SFTPAdaptor] ChannelSftp connected!! server:"+server+", port:"+port); + + storeJSCH(batchDoc, sftpChannel, remote, remoteFileName, localFileName, bandWidthLimit, logger); + } catch (JSchException e) { + logger.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + + batchDoc.setSftpChannel(null); + if (sftpChannel != null) sftpChannel.disconnect(); + if (session != null) session.disconnect(); + + } + return true; + } + + protected static boolean store(String server, int port, String username, + String password, String remote, String localPath, Logger logger, String authType) throws Exception { + + logger.debug("[SFHT store]remote-->" + remote); + logger.debug("[SFHT store]localPath-->" + localPath); + + SSHClient ssh = new SSHClient(); + try { + loadKnownHosts(ssh); + try{ + ssh.connect(server, port); + }catch(TransportException e){ + String msg = e.getMessage(); + String[] split = msg.split("`"); + String vc = split[3]; + ssh.close(); + ssh = new SSHClient(); + ssh.addHostKeyVerifier(vc); + ssh.connect(server, port); + + //20220531 대역폭 제한 + //window size scale factor가 얼마인지는?? window size x scale factor = real window size + Connection conn = ssh.getConnection(); + logger.debug("[SFHT store]conn.getMaxPacketSize()-->" + conn.getMaxPacketSize()); + logger.debug("[SFHT store]conn.getWindowSize()-->" + conn.getWindowSize()); + logger.debug("[SFHT store]conn.getTimeoutMs()-->" + conn.getTimeoutMs()); + } + // id 인증 + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_ID)) { + ssh.authPassword(username, password); + // key 방식 인증 + } else if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + if (StringUtils.isEmpty(password)) { + ssh.authPublickey(username); // 사용자 기본 + } else { + ssh.authPublickey(username, new File(password).getPath()); // private key 지정 + } + } + SFTPClient sftp = ssh.newSFTPClient(); + +// String delimiter = StringUtil.getDirDelimiter(remote); +// String remotePath = remote.substring(0, remote.lastIndexOf(delimiter)); +// String fileName = remote .substring(remote.lastIndexOf(delimiter) + 1); + +// logger.debug("[SFHT store]remotePath-->" + remotePath); +// logger.debug("[SFHT store]fileName-->" + fileName); + + try{ + sftp.put(localPath, remote); + }catch ( IOException ie){ + logger.error(ie.getMessage(), ie); + throw new Exception(ie.getMessage()); + }finally{ + sftp.close(); + } + + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if ( ssh != null && ssh.isConnected()) + ssh.close(); + } + + return true; + } + + + protected static boolean rename(String server, int port, String username, + String password, String srcname, String tarname, Logger logger, String authType) throws Exception{ + + logger.debug("[SFHT rename]srcname-->" + srcname); + logger.debug("[SFHT rename]tarname-->" + tarname); + + SSHClient ssh = new SSHClient(); + try { + loadKnownHosts(ssh); + ssh.connect(server, port); + // id 인증 + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_ID)) { + ssh.authPassword(username, password); + // key 방식 인증 + } else if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + if (StringUtils.isEmpty(password)) { + ssh.authPublickey(username); // 사용자 기본 + } else { + ssh.authPublickey(username, new File(password).getPath()); // private key 지정 + } + } + SFTPClient sftp = ssh.newSFTPClient(); + + try{ + sftp.rename(srcname, tarname); + }catch ( IOException ie){ + logger.error(ie.getMessage(), ie); + throw new Exception(ie.getMessage()); + }finally{ + sftp.close(); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if ( ssh != null && ssh.isConnected()) + ssh.close(); + } + return true; + } + + /** + * for KED backup, after mkdir, move file + */ + protected static boolean renameWithMkdirs(String server, int port, String username, + String password, String remote, String backupPath, String filename, Logger logger, String authType) throws Exception { + + logger.debug("[SFHT rename]remote-->" + remote); + logger.debug("[SFHT rename]remoteBackup-->" + backupPath + filename); + + SSHClient ssh = new SSHClient(); + try { + loadKnownHosts(ssh); + try{ + ssh.connect(server, port); + }catch(TransportException e){ + String msg = e.getMessage(); + String[] split = msg.split("`"); + String vc = split[3]; + ssh.close(); + ssh = new SSHClient(); + ssh.addHostKeyVerifier(vc); + ssh.connect(server, port); + } + // id 인증 + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_ID)) { + ssh.authPassword(username, password); + // key 방식 인증 + } else if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + if (StringUtils.isEmpty(password)) { + ssh.authPublickey(username); // 사용자 기본 + } else { + ssh.authPublickey(username, new File(password).getPath()); // private key 지정 + } + } + SFTPClient sftp = ssh.newSFTPClient(); + +// String delimiter = StringUtil.getDirDelimiter(remote); +// String remotePath = remote.substring(0, remote.lastIndexOf(delimiter)); +// String fileName = remote .substring(remote.lastIndexOf(delimiter) + 1); + +// logger.debug("[SFHT rename]remote-->" + remote); +// logger.debug("[SFHT rename]remoteBackup-->" + remoteBackup); + + try{ + sftp.mkdirs(backupPath); + sftp.rename(remote, backupPath + filename); + }catch ( IOException ie){ + logger.error(ie.getMessage(), ie); + throw new Exception(ie.getMessage()); + }finally{ + sftp.close(); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new Exception(e.getMessage()); + } finally { + if ( ssh != null && ssh.isConnected()) + ssh.close(); + } + + return true; + } + +// protected static boolean rename(String server, int port, String username, +// String password, String srcname, String tarname) throws Exception { +// Session session = null; +// ChannelSftp sftpChannel = null; +// String[] serverList = server.split(","); +// +// try { +// +// for (int inx = 0; inx < serverList.length; inx++) { +// try { +// JSch jsch = new JSch(); +// +// session = jsch.getSession(username, serverList[inx], port); +// session.setPassword(password); +// session.setConfig("StrictHostKeyChecking", "no"); +// session.setTimeout(10 * 1000); +// session.connect(); +// +// } catch (JSchException e) { +// if ( inx == serverList.length -1) +// throw e; +// } +// } +// +// sftpChannel = (ChannelSftp) session.openChannel("sftp"); +// sftpChannel.connect(); +// +// sftpChannel.rename(srcname, tarname); +// sftpChannel.quit(); +// +// } catch (JSchException e) { +// //logger.error(e.getMessage(), e); +// throw new Exception(e.getMessage()); +// } catch (SftpException e) { +// //logger.error(e.getMessage(), e); +// throw new Exception(e.getMessage()); +// } finally { +// if (sftpChannel != null) +// sftpChannel.disconnect(); +// if (session != null) +// session.disconnect(); +// } +// return true; +// } +// +// protected static boolean delete(String server, int port, String username, +// String password, String srcname) throws Exception { +// Session session = null; +// ChannelSftp sftpChannel = null; +// String[] serverList = server.split(","); +// try { +// +// for (int inx = 0; inx < serverList.length; inx++) { +// try { +// JSch jsch = new JSch(); +// +// session = jsch.getSession(username, serverList[inx], port); +// session.setPassword(password); +// session.setConfig("StrictHostKeyChecking", "no"); +// session.setTimeout(10 * 1000); +// session.connect(); +// +// } catch (JSchException e) { +// if ( inx == serverList.length -1) +// throw e; +// } +// } +// +// sftpChannel = (ChannelSftp) session.openChannel("sftp"); +// sftpChannel.connect(); +// +// sftpChannel.rm(srcname); +// sftpChannel.quit(); +// +// } catch (JSchException e) { +// logger.error(e.getMessage(), e); +// throw new Exception(e.getMessage()); +// } catch (SftpException e) { +// logger.error(e.getMessage(), e); +// throw new Exception(e.getMessage()); +// } finally { +// if (sftpChannel != null) +// sftpChannel.disconnect(); +// if (session != null) +// session.disconnect(); +// } +// return true; +// } + public static void main(String[] args) throws Exception { +// String[] serverList = "10.0.249.35".split(","); +// for (int inx = 0; inx < serverList.length; inx++) { +// System.out.println("serverList-->" + serverList[inx]); +// } +// +// FTPFile[] list = listFiles("172.31.32.111", 22, "eaiadm", "!2345Trewq", "/home/eaiadm/src", null ); +// for ( int inx= 0; inx < list.length; inx++){ +// FTPFile file = list[inx]; +// +// } + String filename = "NICE_CSALINB_F13.160809.AA"; + System.out.println("NICE_CSALINB_F13.160809.AA-->" + filename.indexOf(".")); + } + + + /** + * 재사용할 Session 객체를 얻는다. + * @return + * @throws JSchException + */ + public static Session getSessionJSCH(String server, int port, String username, String password, String authType, int connTimeout, int setTimeout, Logger logger) throws JSchException { + JSch jsch = new JSch(); + Session session = null; + // 키 인증 방식인 경우 + try { + if (StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + jsch.addIdentity(password); + } + + session = jsch.getSession(username, server, port); + + // 키 인증 방식이 아닌 경우 + if (!StringUtils.equals(authType, Transfer.AUTH_TYPE_KEY)) { + session.setPassword(password); + } + + session.setConfig("StrictHostKeyChecking", "no"); + session.setConfig("max_input_buffer_size", "increased_size"); + + if (connTimeout > 0) + session.setTimeout(connTimeout * 1000); + session.connect(); + if (setTimeout > 0) + session.setTimeout(setTimeout * 1000); + + return session; + } catch (JSchException e) { + logger.error(e.getLocalizedMessage(), e); + if (session != null) session.disconnect(); + throw e; + } + } + + /** + * 파일을 저장한다. + */ + public static boolean storeJSCH(BatchDoc batchDoc, ChannelSftp channelSftp, String remote, String remoteFileName, String localFileName, int bandWidthLimit, Logger logger) throws Exception { + + logger.debug("[SFHT storeJSCH]remote-->" + remote); + logger.debug("[SFHT storeJSCH]remoteFileName-->" + remoteFileName); + logger.debug("[SFHT storeJSCH]localFileName-->" + localFileName); + + BufferedOutputStream bos = null; + BufferedInputStream bis = null; + FileInputStream is = null; + + try { + if (batchDoc.isUserCancel()){ + throw new Exception("사용자가 전송을 중지 했습니다."); + } + + batchDoc.setSftpChannel(channelSftp); + + try { + channelSftp.cd(remote); + }catch (SftpException e) { + logger.debug("SFTPAdaptor]"+ remote +" 찾기 오류 발생!!!"); + try { + String dir = remote.substring(0, remote.lastIndexOf("/")); + String path = remote.replaceAll(dir + "/", ""); + channelSftp.cd(dir); + channelSftp.mkdir(path); + logger.debug("SFTPAdaptor]"+ path +" 생성"); + channelSftp.cd(path); + + }catch (SftpException ex) { + throw new Exception(remote + " 접근에 실패 하였습니다."); + } + } + + is = new FileInputStream(new File(localFileName)); + + if(bandWidthLimit > 0){ + /** + * 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit), + */ + //Buffer buffer = new Buffer(1024); + //int bandWidth = 1024*8; + long bufferSize = bandWidthLimit/8; + byte[] bufferArr = new byte[(int)bufferSize]; + + try { + bos = new BufferedOutputStream(channelSftp.put(remoteFileName)); + bis = new BufferedInputStream(is); + batchDoc.setIOStream(bos); + + int readCount = 0; + int availableCount = 0; + int lootCnt = 0; + + long[] timeMillis = new long[2]; + timeMillis[0] = System.currentTimeMillis(); + + long rtt = 0;//round trip time 1회 전송시간 millisecond + long rttMax = 0; + long rttMin = 0; + double rttAve = 0; + long rttSum = 0; + + long realBandWidth = 0; + long realBandWidthMax = 0; + long realBandWidthMin = 0; + double realBandWidthAve = 0; + long realBandWidthSum = 0; + long writeByteSum = 0; + + long sizeStartTime = 0; + long sizePerSecond = 0; + + while (true){ + + lootCnt++; + + + //강제중지 설정시 + if (batchDoc.isUserCancel()){ + //throw new Exception("사용자가 전송을 중지 했습니다."); + logger.debug("InputFileName : " + localFileName+ " User canceled"); + break; + } + + availableCount = bis.available(); + if(availableCount < 1) { + logger.debug("InputFileName : " + localFileName+ " Reached end of file."); + break; + } + + readCount = bis.read(bufferArr); + + if(readCount<=0) { + logger.debug("InputFileName : " + localFileName+ " read count less than 0."); + break; + } + + + //****sftp send...... + timeMillis[0] = System.currentTimeMillis(); + bos.write(bufferArr,0,readCount); + timeMillis[1] = System.currentTimeMillis(); + + writeByteSum += readCount; + batchDoc.setCurrIODataByte(writeByteSum); + + if (sizePerSecond > 0){ + rtt = timeMillis[1] - sizeStartTime; + } else { + rtt = timeMillis[1] - timeMillis[0]; + } + + if(rtt<=0){ + if(sizeStartTime==0)sizeStartTime = timeMillis[0]; + sizePerSecond += readCount; + realBandWidth = 0; + }else { + //rtt가 0보다 커야 bandwidth계산 + realBandWidth = (long) ((sizePerSecond+bufferSize) * 8 * 1000 / rtt); + + sizeStartTime = 0; + sizePerSecond = 0; + } + + realBandWidthSum += realBandWidth; + if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth; + else if(realBandWidth rttMax)rttMax = rtt; + else if (rtt < rttMin)rttMin = rtt; + + //1초이내로 처리가 된경우sleep,, 여유 10milli + if(rtt < 990){ //여유 10milli + logger.debug("SFTPAdaptor] remoteFileName ["+remoteFileName+"]"+ "loopCnt["+(lootCnt)+"] readCount["+readCount+"] availableCount["+availableCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(990-rtt)+"]"); + + Thread.sleep((long) (990-rtt)); + + //1초를 채웠으므로 초기화 한다. + sizeStartTime = 0; + sizePerSecond = 0; + + } else { + logger.debug("SFTPAdaptor] remoteFileName ["+remoteFileName+"]"+ "loopCnt["+(lootCnt)+"] readCount["+readCount+"] availableCount["+availableCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]"); + } + + } + + realBandWidthAve = realBandWidthSum/lootCnt; + rttAve = rttSum/lootCnt; + + logger.info("SFTPAdaptor] remoteFileName ["+remoteFileName+"]"+"####Statistics : bufferSize["+bufferSize + +"] loopCnt["+lootCnt + +"] writeByteSum["+writeByteSum + +"] rttAve["+rttAve + +"] rttMax["+rttMax + +"] rttMin["+rttMin + +"] bandWidthLimit["+bandWidthLimit + +"] realBandWidthAve["+realBandWidthAve + +"] realBandWidthMax["+realBandWidthMax + +"] realBandWidthMin["+realBandWidthMin + +"]"); + + } finally { + try { + if (bos != null){ + bos.flush(); + bos.close(); + } + + if (bis != null)bis.close(); + if(is!=null) is.close(); + } catch (Throwable t){ + logger.error("Closing Error:"+t.getMessage()); + } + } + } else { + channelSftp.put(is, remoteFileName); + + try {// 20250910 obl + if(is!=null) is.close(); + } catch (Throwable t){ + logger.error("is Closing Error:"+t.getMessage()); + } + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw e; + } finally { + batchDoc.setSftpChannel(null); + } + return true; + } + + /** + * 사용자 전송중지 기능 구현으로 JSch 사용 20220704 + * bandwidth 기능 구현 + * remote 경로로 cd한 다음 호출해야 한다. + * + */ + public static long retrieveJSCH(BatchDoc batchDoc, ChannelSftp channelSftp, String remoteFileName, String localPath, int bandWidthLimit, Logger logger) throws Exception { + logger.debug("[SFHT retrieve]remote-->{"+remoteFileName+"}"); + logger.debug("[SFHT retrieve]localPath-->" + localPath); + + BufferedOutputStream bos = null; + BufferedInputStream bis = null; + FileOutputStream os = null; + boolean fileReceived = false; + File receiveFile = null; + String localFileName = ""; + try { + batchDoc.setSftpChannel(channelSftp); + + File chkDir = new File(localPath); + if (!chkDir.exists() && !chkDir.mkdirs()) { + logger.error("[수신 경로를 생성할 수 없습니다.]"); + return -1; + } + + String delimiter = StringUtil.getDirDelimiter(localPath); + + //sftpChannel.get(remote,localPath); + if (localPath.endsWith(delimiter))localFileName = localPath+remoteFileName; + else localFileName = localPath+delimiter+remoteFileName; + logger.debug("[retrieve]localFileName ------->" + localFileName); + + receiveFile = new File(localFileName); + os = new FileOutputStream(receiveFile); + + if(bandWidthLimit > 0){ + /** + * 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit), + */ + //Buffer buffer = new Buffer(1024); + //int bandWidth = 1024*8; + long bufferSize = bandWidthLimit/8; + byte[] bufferArr = new byte[(int)bufferSize]; + + try { + bos = new BufferedOutputStream(os); + bis = new BufferedInputStream(channelSftp.get(remoteFileName)); + fileReceived = true; + batchDoc.setIOStream(bis); + + int readCount = 0; + int lootCnt = 0; + + long[] timeMillis = new long[2]; + timeMillis[0] = System.currentTimeMillis(); + + long rtt = 0;//round trip time 1회 전송시간 millisecond + long rttMax = 0; + long rttMin = 0; + double rttAve = 0; + long rttSum = 0; + + long realBandWidth = 0; + long realBandWidthMax = 0; + long realBandWidthMin = 0; + double realBandWidthAve = 0; + long realBandWidthSum = 0; + long readByteSum = 0; + + long sizeStartTime = 0; + long sizePerSecond = 0; + int sleepTimeCriteria = 990; + + while (true){ + lootCnt++; + sleepTimeCriteria = 990; //여유 10milli + + //강제중지 설정시 + if (batchDoc.isUserCancel()){ + throw new Exception("사용자가 전송을 중지 했습니다."); + } + + timeMillis[0] = System.currentTimeMillis(); + readCount = bis.read(bufferArr); + timeMillis[1] = System.currentTimeMillis(); + if(readCount<=0) break; + + bos.write(bufferArr,0,readCount); + + readByteSum += readCount; + batchDoc.setCurrIODataByte(readByteSum); + + if (sizePerSecond > 0){ + rtt = timeMillis[1] - sizeStartTime; + } else { + rtt = timeMillis[1] - timeMillis[0]; + } + + if(rtt<=0 ){ + //rtt=1;//local test시 0이 발생 divide by zero오류 발생, 방어코드 + if(sizeStartTime==0)sizeStartTime = timeMillis[0]; + sizePerSecond += readCount; + + if(sizePerSecond >= bufferArr.length){ + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 990 sec, readCount["+readCount+"]sizePerSecond["+sizePerSecond+"]readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]"); + Thread.sleep(990); + sizePerSecond = 0; + sizeStartTime = 0; + } else { + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 0 sec, readCount["+readCount+"]sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]"); + } + continue; + } + + if ( readCount < bufferArr.length || sizePerSecond> 0){ + if(sizeStartTime==0)sizeStartTime = timeMillis[0]; + sizePerSecond += readCount; + + if(sizePerSecond>0 && sizePerSecond < bufferArr.length){ + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] SLEEP 0 sec readCount["+readCount+"] sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]"); + continue; + } + } + + if (sizePerSecond > 0){ + realBandWidth = (long) (sizePerSecond * 8 * 1000 / rtt); + } else { + realBandWidth = (long) (bufferSize * 8 * 1000 / rtt); + } + + //min, max, sum + rttSum += rtt; + if (rtt > rttMax)rttMax = rtt; + else if (rtt < rttMin)rttMin = rtt; + + realBandWidthSum += realBandWidth; + if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth; + else if(realBandWidth 0 && sizePerSecond>bufferSize){ + sleepTimeCriteria = (int) (sleepTimeCriteria*sizePerSecond/bufferSize); + } + + if(rtt < sleepTimeCriteria){ + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(sleepTimeCriteria-rtt)+"]sleepTimeCriteria["+sleepTimeCriteria+"]"); + Thread.sleep((long) (sleepTimeCriteria-rtt)); + } else { + logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]sleepTimeCriteria["+sleepTimeCriteria+"]"); + } + + sizePerSecond = 0; + sizeStartTime = 0; + } + + realBandWidthAve = realBandWidthSum/lootCnt; + rttAve = rttSum/lootCnt; + + logger.info("SFTPAdaptor] ####Statistics : bufferSize["+bufferSize + +"] loopCnt["+lootCnt + +"] readCountSum["+readByteSum + +"] rttAve["+rttAve + +"] rttMax["+rttMax + +"] rttMin["+rttMin + +"] bandWidthLimit["+bandWidthLimit + +"] realBandWidthAve["+realBandWidthAve + +"] realBandWidthMax["+realBandWidthMax + +"] realBandWidthMin["+realBandWidthMin + +"]"); + + } finally { + try { + if (bos != null) { + bos.flush(); + bos.close(); + } + + if (bis != null) bis.close(); + if (os != null) os.close(); + } catch (Throwable e) { + logger.error("Closing Error:" + e.getMessage()); + } + } + } else { + channelSftp.get(remoteFileName, os); + fileReceived = true; + + try {// 20250910 obl + if (os != null) os.close(); + } catch (Throwable e) { + logger.error("os Closing Error:" + e.getMessage()); + } + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw e; + } finally { + batchDoc.setSftpChannel(null); + if (!fileReceived && receiveFile != null && receiveFile.exists()) { + try { + Files.delete(receiveFile.toPath()); + } catch (Exception e) { + logger.error("fail to delete {}", localFileName, e); + } + } + } + return 0; + } + + /** + * 경로를 ls 한 결과를 얻는다. + * @param channelSftp + * @param remotePath + * @param remoteFileName + * @param logger + * @return + * @throws SftpException + */ + public static FTPFile[] lsJSCH(ChannelSftp channelSftp, String remotePath, String remoteFileName, + Logger logger) throws SftpException { + logger.debug("remotePath --> {"+ remotePath+"}"); + logger.debug("remoteFileName --> {"+ remoteFileName+"}"); + + FTPFile[] files = null; + Vector list = channelSftp.ls(remotePath + remoteFileName); + files = new FTPFile[list.size()]; + for (int inx = 0; inx < list.size(); inx++) { + LsEntry info = list.get(inx); + logger.debug("{"+"info.getFilename()"+"} " +"{"+"info.getAttrs().toString()"+"}"); + + FTPFile file = new FTPFile(); + file.setName(info.getFilename()); + file.setSize(info.getAttrs().getSize()); + if (info.getAttrs().isReg()) + file.setType(FTPFile.FILE_TYPE); + else if (info.getAttrs().isDir()) + file.setType(FTPFile.DIRECTORY_TYPE); + else + file.setType(FTPFile.UNKNOWN_TYPE); + + files[inx] = file; + } + return files; + } + + /** + * lstat 결과를 얻는다. + * + * @param channelSftp + * @param remotePath + * @param remoteFileName + * @return lstat 결과 + * @throws SftpException + */ + public static SftpATTRS lstatJSCH(ChannelSftp channelSftp, String remotePath, String remoteFileName) throws SftpException { + return channelSftp.lstat(remotePath + remoteFileName); + } + + /** + * 경로를 remotePath로 변경한다. + * + * @param channelSftp + * @param remotePath + * @throws SftpException + */ + public static void cdJSCH(ChannelSftp channelSftp, String remotePath) throws SftpException { + channelSftp.cd(remotePath); + } + + + + protected static FTPFileObject[] listFilesJSCH(String server, int port, String username, String password, String path, Logger logger, String authType) throws IOException { + logger.debug("[SFHT connect]server -->" + server); + logger.debug("[SFHT connect]port -->" + port); + logger.debug("[SFHT connect]username-->" + username); + logger.debug("[SFHT connect]password-->" + password); + logger.debug("[SFHT listFiles2]path-->" + path); + + Session session = null; + ChannelSftp sftpChannel = null; + String[] serverList = server.split(","); + try { + + for (int inx = 0; inx < serverList.length; inx++) { + try { + JSch jsch = new JSch(); + + //JSch.setLogger(new SFTPLogger()); + + session = jsch.getSession(username, serverList[inx], port); + session.setPassword(password); + session.setConfig("StrictHostKeyChecking", "no"); + session.setConfig("PreferredAuthentications","password"); + session.setTimeout(300 * 1000); + session.connect(); + break; + + } catch (JSchException e) { + if ( inx == serverList.length -1) + throw e; + } + } + sftpChannel = (ChannelSftp) session.openChannel("sftp"); + sftpChannel.connect(300 * 1000); + + try { + sftpChannel.ls(path); + }catch(SftpException e) { + return null; + } + FTPFile[] files = null; + + @SuppressWarnings("unchecked") + Vector v = sftpChannel.ls(path); + files = new FTPFile[v.size()]; + int inx = 0; + for (Iterator iterator = v.iterator(); iterator.hasNext();) { + LsEntry object = (LsEntry) iterator.next(); + FTPFile file = new FTPFile(); + SftpATTRS att = object.getAttrs(); + file.setName(object.getFilename()); + if (!att.isDir() && !att.isLink()) + file.setType(FTPFile.FILE_TYPE); + else if(att.isDir()) + file.setType(FTPFile.DIRECTORY_TYPE); + else + file.setType(FTPFile.UNKNOWN_TYPE); + + file.setSize(att.getSize()); + Calendar cal = new GregorianCalendar(); + cal.setTime(new Date(att.getMTime())); + files[inx++] = file; + } + + ArrayList oFiles = new ArrayList(); + FTPFileObject[] rFiles = new FTPFileObject[files.length]; + FTPFileObject nFile; + for(FTPFile file :files){ + nFile = new FTPFileObject(); + nFile.setFile(file.isFile()); + nFile.setName(file.getName()); + nFile.setSize(file.getSize()); + oFiles.add(nFile); + } + oFiles.toArray(rFiles); + + return rFiles; + + } catch (JSchException e) { + logger.error(e.getMessage(), e); + throw new IOException(e.getMessage()); + } catch (SftpException e) { + logger.error(e.getMessage(), e); + throw new IOException(e.getMessage()); + } finally { + if (sftpChannel != null) + sftpChannel.disconnect(); + if (session != null) + session.disconnect(); + } + + } +} diff --git a/src/com/eactive/eai/batch/job/jobComm/OutboundFTPHandle.java b/src/com/eactive/eai/batch/job/jobComm/OutboundFTPHandle.java new file mode 100644 index 0000000..3d0424e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobComm/OutboundFTPHandle.java @@ -0,0 +1,134 @@ +package com.eactive.eai.batch.job.jobComm; + +import java.io.File; + +import com.eactive.eai.batch.job.jobHandle.JobFinishHandler; + +import com.eactive.eai.adapter.ftp.Transfer; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class OutboundFTPHandle { + + private BatchDoc batchDoc; + private String logHeader; + private String strUUID; + private Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public void proc( BatchDoc recvBatchDoc ){ + batchDoc = recvBatchDoc; + logger = recvBatchDoc.getLogger(); + init(); + try { + callScript(); + closeAndRemove(); + } catch (Exception e) { + handleException(e); + } + + } + private void init() + { + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + + logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+ + batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+ + batchDoc.getBatchMsg().getHeader().getFileName() +" / "+ + batchDoc.getBatchMsg().getHeader().getRuleCode() +"] [OutboundFTPHandle] "; + + strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + + logger.info("{"+logHeader+"} start OutboundFTPHandle ... " ); + logger.info("{"+logHeader+"} [JUNGFOX]################ 요구송수신 FTP 핸들러 시작 BatchMessageDoc: \n"+ batchDoc.toString()); + logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록시작 "); + BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, null, batchDoc); + logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록완료 "); + + } + + public void callScript() throws Exception { + logger.info("[OutboundFTPHandle] ========================================================================="); + String dirPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String processType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( processType.equalsIgnoreCase("RS") ){ + File file = new File( dirPath + File.separatorChar + renamedFileName); + if ( !file.exists()){ + throw new Exception(); + } + long fileLen = file.length(); + batchDoc.getBatchMsg().getHeader().setFileSize( fileLen ); + logger.info("[OutboundFTPHandle] ※ 송신 디렉토리 : [" + dirPath +"]"); + logger.info("[OutboundFTPHandle] ※ 송신 파일명 : [" + fileName +"]"); + logger.info("[OutboundFTPHandle] ※ 송신 파일크기 : [" + fileLen +"]"); + logger.info("[OutboundFTPHandle] ========================================================================="); + + //VAN사 제공 모듈을 이용하여 로컬의 송신_Arch 에 있는 파일을 해당 밴사로 전송 + try { + logger.info("FTP 스크립트가 호출되었습니다."); + Transfer.sendFileByEvent(batchDoc); + } catch (Throwable t) { + String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIFJC008" ); + throw new Exception(errMsg); //VAN사 송수신 모듈 이용 전송 시 오류가 발생하였습니다. + } + new JobFinishHandler(batchDoc).handleSuccessEnd(); + } else if ( processType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE) ){ + logger.info("[OutboundFTPHandle] ※ 수신 디렉토리 : [" + dirPath +"]"); + logger.info("[OutboundFTPHandle] ※ 수신 파일명 : [" + fileName +"]"); + logger.info("[OutboundFTPHandle] ========================================================================="); + + //VAN사 제공 모듈을 이용하여 로컬의 송신_Arch 에 있는 파일을 해당 밴사로 전송 + try { + logger.info("FTP 스크립트가 호출되었습니다."); + Transfer.recvFileByEvent(batchDoc); + } catch (Throwable t) { + String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIFJC008" ); + throw new Exception(errMsg); //VAN사 송수신 모듈 이용 전송 시 오류가 발생하였습니다. + } + new JobFinishHandler(batchDoc).handleSuccessEnd(); + } else { + } + + } + private void closeAndRemove() throws Exception + { + logger.info("{"+logHeader+"} >> BatchRunningJobManager 에서 Socket 연결정보 제거 시작......"); + BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + logger.info("{"+logHeader+"} >> BatchRunningJobManager Socket 연결정보 제거 완료."); + } + + private void handleException(Exception ex) + { + try { + if (BatchRunningJobManager.getInstance().isSocketClosed(strUUID) == false) BatchRunningJobManager.getInstance().closeRunningSocket(strUUID); + + } catch (Exception e) { + logger.error("{"+logHeader+"} ★★★★★ OutboundFTPHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n"+ e.getMessage()); + } + try { + if (BatchRunningJobManager.getInstance().isJobRunning(strUUID) == true) BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + + } catch (Exception e) { + logger.error("{"+logHeader+"} ★★★★★ OutboundFTPHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n" + e.getMessage()); + } + + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC005"); + logger.error("{"+errMsg+"} {"+logHeader+"} \r\n"+ex.getMessage()); + + // DB로그 처리 + new JobFinishHandler(batchDoc).handleErrorEnd(errMsg); + + } catch (Exception e) { + logger.error("{"+logHeader+"} ★★★★★ OutboundFTPHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n" + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobComm/OutboundSocketHandle.java b/src/com/eactive/eai/batch/job/jobComm/OutboundSocketHandle.java new file mode 100644 index 0000000..e3dc918 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobComm/OutboundSocketHandle.java @@ -0,0 +1,148 @@ +package com.eactive.eai.batch.job.jobComm; + +import java.net.Socket; +import java.net.UnknownHostException; + +import com.eactive.eai.batch.job.jobHandle.FlowController; +import com.eactive.eai.batch.job.jobHandle.JobFinishHandler; + +import com.eactive.eai.adapter.socket.outbound.OutboundSocketClient; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class OutboundSocketHandle { + + private BatchDoc batchDoc; + private String logHeader; + private String strUUID; + private Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public void proc( BatchDoc recvBatchDoc ){ + batchDoc = recvBatchDoc; + init(); + try { + connect(); + FlowController flowController = new FlowController(); + batchDoc = flowController.clientRequestwithReturn(batchDoc); + closeAndRemove(); + } catch (Exception e) { + handleException(e); + } + + } + private void init() + { + batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + + logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+ + batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+ + batchDoc.getBatchMsg().getHeader().getFileName() +" / "+ + batchDoc.getBatchMsg().getHeader().getRuleCode() +"] [OutboundSocketHandle] "; + + strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + + logger = batchDoc.getLogger(); + + logger.info("{"+logHeader+"} start OutboudnSocketHandle ... " ); + logger.info("{"+logHeader+"} [JUNGFOX]################ 요구송신 소켓연결 JPD 시작 BatchMessageDoc: \n"+ batchDoc.toString()); + } + + private void connect() throws Exception{ + // 새로운 connection 만들기 + // *** 소켓연결은 상대방 서버 소켓의 IP+PORT 당 하나의 연결만을 가지는 것을 가정한다. + + // 2. 연결 가능 IP 주소 구하기 + // 조건 : 현재 사용중이 아니고, 장애통보 혹은 장애 상태가 아닌 경우... + // + // 사용가능한 소켓 자원이 구해졌으면 + // + logger.info("{"+logHeader+"} SOCKET TARGET IP = [" + batchDoc.getBatchMsg().getHeader().getRemoteIP()+"]" ); + logger.info("{} SOCKET PORT = [" + batchDoc.getBatchMsg().getHeader().getPort()+"]"); + // 소켓을 만들고 + logger.info("{"+logHeader+"} Socket connection try to the ["+batchDoc.getBatchMsg().getHeader().getRemoteIP()+"] starting"); + int nPortNum = -1; + try { + nPortNum = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort()); + + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC002", new String[] {batchDoc.getBatchMsg().getHeader().getPort()}); + throw new Exception(errMsg); + } + + Socket socket = socketInit(batchDoc.getBatchMsg().getHeader().getRemoteIP(), nPortNum); + if (socket == null) { + // String errMsg = "setSocketConnection : SocketClientControl socketInit return null"; + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJC003"); + throw new Exception(errMsg); + } + + logger.info("{"+logHeader+"} Socket connection success"); + + + logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록시작 "); + OutboundSocketClient socketClient = new OutboundSocketClient(socket); + BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, socketClient, batchDoc); + logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록완료 "); + } + + private Socket socketInit(String remoteIP, int remotePort) throws Exception + { + try { + return new Socket(remoteIP, remotePort); + + } catch (UnknownHostException ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC001", new String[] {remoteIP, Integer.toString(remotePort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다. + + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC002", new String[] {remoteIP, Integer.toString(remotePort)}); + throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), I/O Exception이 발생했습니다. + } + } + private void closeAndRemove() throws Exception + { + //Outbound Socket Close + BatchRunningJobManager.getInstance().closeRunningSocket(strUUID); + + logger.info("{"+logHeader+"} >> BatchRunningJobManager 에서 Socket 연결정보 제거 시작......" ); + BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + logger.info("{"+logHeader+"} >> BatchRunningJobManager Socket 연결정보 제거 완료."); + } + + private void handleException(Exception ex) + { + try { + if (BatchRunningJobManager.getInstance().isSocketClosed(strUUID) == false) BatchRunningJobManager.getInstance().closeRunningSocket(strUUID); + + } catch (Exception e) { + logger.error("{"+logHeader+"} ★★★★★ OutboundSocketHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n" + e.getMessage()); + } + try { + if (BatchRunningJobManager.getInstance().isJobRunning(strUUID) == true) BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID); + + } catch (Exception e) { + logger.error("{"+logHeader+"} ★★★★★ OutboundSocketHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n"+ e.getMessage()); + } + + try { + // = this.context.getExceptionInfo().getException(); + + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC005"); + logger.error("{"+logHeader+"}"+" {"+errMsg+"}"+ ex.getMessage()); + + // DB로그 처리 + new JobFinishHandler(batchDoc).handleErrorEnd(errMsg); + + } catch (Exception e) { + logger.error("{} ★★★★★ OutboundSocketHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n", logHeader, e); + } + } + + +} diff --git a/src/com/eactive/eai/batch/job/jobConstant/ErrorKeys.java b/src/com/eactive/eai/batch/job/jobConstant/ErrorKeys.java new file mode 100644 index 0000000..fe60794 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobConstant/ErrorKeys.java @@ -0,0 +1,32 @@ +package com.eactive.eai.batch.job.jobConstant; + +public class ErrorKeys +{ + public static final String ERROR_UNEXPECTED_TELEGRAM_IGNORE = "BWCEAIFJM001"; //Rule에 정의되지 않은 전문종별코드[{1}] 가 도착하였습니다. 당 전문을 무시하고 다음 전문을 수신합니다. + public static final String ERROR_NO_SOCKET = "BECEAIFJM001"; //해당 배치 작업의 전문 송수신 시 필요한 Socket 정보를 BatchRunningJobManager에서 찾을 수 없습니다. 내부 로직 검토가 필요합니다. (UUID:{1}) + public static final String ERROR_NO_PROCDATA = "BECEAIFJM002"; //해당 배치 작업의 진행 정보를 JobProcessData 에서 찾을 수 없습니다. 내부 로직 검토가 필요합니다. (UUID:{1}) + public static final String ERROR_NO_NEXTSTAGE = "BECEAIFJM003"; //해당 배치 작업의 진행 정보 중 현재 단계 정보를 찾을 수 없습니다. TSEAIBR02 테이블에 해당 단계 정보를 등록하세요. (RuleCode:{1}, PhaseCode:{2}) + public static final String ERROR_NO_TELEGRAM_ID = "BECEAIFJM004"; //수행 중인 단계의 텔레그램ID 정보를 텔레그램 정의 테이블(TSEAIBR05) 에서 찾을 수 없습니다. TSEAIBR05 테이블에 해당 텔레그램 정보를 등록하세요. (RuleCode:{1}, PhaseCode:{2}, TelegramID:{3}) + public static final String ERROR_NO_CLASS_DEFINITION = "BECEAIFJM005"; //텔레그램 클래스를 동적으로 생성시 실패하였습니다. 해당 클래스 파일이 존재하는지 확인하세요. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_RECV_PRE_LENGTH = "BECEAIFJM006"; //(전문 송수신 전) 텔레그램 클래스의 수행 전처리 실행이 실패하였습니다. 해당 클래스의 doPreExecute 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_ERR_TELEGRAM_META = "BECEAIFJM007"; //전문헤더 수신 시 비정형 전문필드(길이가 XX) 가 존재합니다. 전문헤더 텔레그램ID 의 비정형 전문필드를 제거하세요. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_TIMEOUT_OVER = "BECEAIFJM008"; //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초] + public static final String ERROR_RECV_ERROR = "BECEAIFJM009"; //대외기관으로부터 전문 수신 시 오류가 발생하였습니다.(소켓 IOException) 파일로그의 상세오류 검토가 필요합니다. (ClassName:{1}) + public static final String ERROR_END_OF_STREAM = "BECEAIFJM010"; //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + public static final String ERROR_EXCEPTION = "BECEAIFJM011"; //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + public static final String ERROR_RECV_SHORT_LENGTH = "BECEAIFJM012"; //대외기관으로부터 전문 수신 시 전체 전문을 수신하지 못했습니다. 파일로그에서 읽어 들인 전문필드 확인 후 해당 대외기관에 연락바랍니다. + public static final String ERROR_UNEXPECTED_TELEGRAM = "BECEAIFJM013"; //수신전문의 '전문종별코드' 값({1})에 해당하는 단계 정보를 JobProcessData 에서 찾을 수 없습니다. TSEAIBR02 테이블에서 해당 단계의 'CndnTelgmPtrnCd' 값을 확인하세요. (RuleCode:{1}, PhaseCode:{2}) + public static final String ERROR_EXECUTION = "BECEAIFJM014"; //(전문 송수신 전) 텔레그램 클래스의 전문조립 또는 전문해체(doExecute) 함수 실행이 실패하였습니다. 해당 클래스의 doExecute 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_RECV_VALIDATION = "BECEAIFJM015"; //대외기관으로부터 수신된 전문의 Validatioin 체크가 실패하였습니다. 오류전문을 보내지 않고 작업을 종료합니다. + public static final String ERROR_POST_EXECUTION = "BECEAIFJM016"; //(전문 송수신 후) 텔레그램 클래스의 수행 후처리 실행이 실패하였습니다. 해당 클래스의 doPostExecute 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_INFORMAL_FIELD_LENGTH = "BECEAIFJM017"; //데이터 전문의 송수신 시 비정형 전문필드의 길이 계산이 실패하였습니다. 해당 클래스의 getCalculatedLength 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_INFORMAL_ACTION = "BECEAIFJM018"; //데이터 수신전문의 비정형 전문필드 수신 중 수신 데이터 처리가(doInformalField) 실패하였습니다. 파일로그에서 상세오류 확인 후 로직 검토가 필요합니다. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_NOTFOUND_NEXTSTAGE = "BECEAIFJM019"; //다음 원인에 의해 다음 단계 정보를 찾을 수 없습니다. (하위 원인이 없을경우 TSEAIBR02 테이블에서 해당 Rule 정보가 올바른지 확인이 필요합니다.) (RuleCode:{1}, PhaseCode:{2}) + public static final String ERROR_SEND_VALIDATION = "BECEAIFJM020"; //대외기관으로 전송할 송신전문의 Validation 체크가 실패하였습니다. + public static final String ERROR_READ_FILE = "BECEAIFJM021"; //데이터 송신전문의 비정형 전문필드 데이터를 읽어오는데 실패하였습니다. 해당 클래스의 doInformalFieldSendData 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2}) + public static final String ERROR_WRITE_ERROR = "BECEAIFJM022"; //대외기관에 전문 송신 시 오류가 발생하였습니다. 해당 대외기관에서 소켓 연결을 종료하였거나 파일로그 확인 후 로직 수정이 필요합니다. + public static final String ERROR_SHORT_WRITE_ERROR = "BECEAIFJM023"; //대외기관에 송신할 전문의 사이즈가 다릅니다. 파일로그 확인 후 로직 수정이 필요합니다. (TelegramID:{1}, ClassName:{2}, 보낼Size:{3}, 실제Size:{4}) + + public static final String ERROR_RECV_PRE_AFTER_COPY = "BECEAIFJM024"; //전문 Body 수신 전에 텔레그램 클래스의 수행 전처리 실행이 실패하였습니다. 해당 클래스의 doPreExecuteAfterCopy 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2}) + +} diff --git a/src/com/eactive/eai/batch/job/jobConstant/TelegramKeys.java b/src/com/eactive/eai/batch/job/jobConstant/TelegramKeys.java new file mode 100644 index 0000000..b943a9f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobConstant/TelegramKeys.java @@ -0,0 +1,641 @@ +package com.eactive.eai.batch.job.jobConstant; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +public class TelegramKeys +{ + + /** + * 자료구분 + */ + public static final String RPS_HBD_DAT_GBN_TEST = "T"; //테스트데이터 + public static final String RPS_HBD_DAT_GBN_REAL = "R"; //실데이터 + public static final String RPS_HBD_DAT_GBN_PASS = "B"; //ByPass데이터 + + public static String getRPS_HDB_DAT_GBN(String s) + { + if (s.equals("test")) // Test Data + return "T"; + else if (s.equals("real")) // Real Data + return "R"; + else if (s.equals("pass")) // By Pass + return "B"; + else + return "E"; // Error: 위의 문자가 아닌 경우 + } + + /** + * 송수신 Flag (HDB_TRA_FLAG) + */ + public static final String RPS_HDB_TRA_FLAG_CLIENT = "1"; // Client --> Server 1, Server --> Client 2 + public static final String RPS_HDB_TRA_FLAG_SERVER = "2"; + + /** + * 응답코드 (HDB_RET_CODE), 3자리 + */ + public static final String RPS_HDB_RET_CODE_SUCCESS = "000"; //정상 + public static final String RPS_HDB_RET_CODE_ALREADY_RECEIVED = "101"; //기수신완료 + public static final String RPS_HDB_RET_CODE_FORMAT_ERROR = "201"; //Format오류 + public static final String RPS_HDB_RET_CODE_CODE_ERROR = "202"; //기관코드오류 + public static final String RPS_HDB_RET_CODE_FILENAME_ERROR = "203"; //파일명오류 + public static final String RPS_HDB_RET_CODE_UNCOMPLETED_ERROR = "901"; //파일전송미완료 + public static final String RPS_HDB_RET_CODE_OTHER_ERROR = "999"; //기타오류 + + public static String getName_RPS_HDB_RET_CODE(String code) { + return code==null ? "null" : + code.equals(RPS_HDB_RET_CODE_SUCCESS )? "정상" : + code.equals(RPS_HDB_RET_CODE_ALREADY_RECEIVED )? "기수신완료" : + code.equals(RPS_HDB_RET_CODE_FORMAT_ERROR )? "Format오류" : + code.equals(RPS_HDB_RET_CODE_CODE_ERROR )? "기관코드오류" : + code.equals(RPS_HDB_RET_CODE_FILENAME_ERROR )? "파일명오류" : + code.equals(RPS_HDB_RET_CODE_UNCOMPLETED_ERROR)? "파일전송미완료" : + code.equals(RPS_HDB_RET_CODE_OTHER_ERROR )? "기타오류" : code; + } + + /** + * 응답코드 (KFB_RET_CODE), 3자리 + */ + public static final String KFB_RET_CODE_SUCCESS = "000"; //정상 + public static final String KFB_RET_CODE_NO_FILE = "101"; //해당일자 전송자료 없음 + public static final String KFB_RET_CODE_ALREADY_RECEIVED = "102"; //해당일자 정보 기수신 완료 + public static final String KFB_RET_CODE_ORGN_CODE_ERROR = "401"; //참가기관코드 Error + public static final String KFB_RET_CODE_TGRAM_CODE_ERROR = "402"; //전문종별코드 Error + public static final String KFB_RET_CODE_TRX_GBN_CODE_ERROR = "403"; //거래구분코드 Error + public static final String KFB_RET_CODE_SND_RCV_FLAG_ERROR = "404"; //송수신 Flag Error + public static final String KFB_RET_CODE_FILE_TRANS_NO_END = "610"; //파일전송 미완료 + + public static String getName_KFB_RET_CODE(String code) { + return code==null ? "null" : + code.equals(KFB_RET_CODE_SUCCESS )? "정상" : + code.equals(KFB_RET_CODE_NO_FILE )? "해당일자 전송자료 없음" : + code.equals(KFB_RET_CODE_ALREADY_RECEIVED )? "해당일자 정보 기수신 완료" : + code.equals(KFB_RET_CODE_ORGN_CODE_ERROR )? "참가기관코드 Error" : + code.equals(KFB_RET_CODE_TGRAM_CODE_ERROR )? "전문종별코드 Error" : + code.equals(KFB_RET_CODE_TRX_GBN_CODE_ERROR)? "거래구분코드 Error" : + code.equals(KFB_RET_CODE_SND_RCV_FLAG_ERROR)? "송수신 Flag Error" : + code.equals(KFB_RET_CODE_FILE_TRANS_NO_END )? "파일전송 미완료" : code; + } + + /** + * 응답코드 (BOKJJ_RET_CODE), 3자리 + */ + public static final String BOKJJ_RET_CODE_SUCCESS = "000"; //정상 + public static final String BOKJJ_RET_CODE_PROTO = "210"; //전문흐름순서 오류 + public static final String BOKJJ_RET_CODE_ALREADY_RECEIVED = "220"; //기수신 자료임 + public static final String BOKJJ_RET_CODE_DATE_ERROR = "230"; //헤더 전문 내 날짜 오류 + public static final String BOKJJ_RET_CODE_REC_COUNT_ERROR = "240"; //수신건수와 헤더 또는 트레일러건수 불일치 + public static final String BOKJJ_RET_CODE_ID_ERROR = "310"; //참가기관ID 오류 + public static final String BOKJJ_RET_CODE_PASSWORD_ERROR = "320"; //비밀번호 오류 + public static final String BOKJJ_RET_CODE_OPCODE_ERROR = "330"; //업무관리정보 오류 + public static final String BOKJJ_RET_CODE_HDTLER_ERROR = "340"; //헤더/트레일러 구분 코드 오류 + public static final String BOKJJ_RET_CODE_JOBCODE_ERROR = "910"; //업무구분코드 오류 + public static final String BOKJJ_RET_CODE_TEL_CODE_ERROR = "920"; //전문종별코드 오류 + public static final String BOKJJ_RET_CODE_TRX_GBN_CODE_ERROR = "930"; //거래구분코드 오류 + public static final String BOKJJ_RET_CODE_SND_RCV_FLAG_ERROR = "940"; //송수신 FLAG 오류 + public static final String BOKJJ_RET_CODE_RTN_CODE_ERROR = "950"; //응답코드 오류 + public static final String BOKJJ_RET_CODE_SND_RCV_JOBCODE_ERROR = "960"; //송수신 업무구분 코드 오류 + public static final String BOKJJ_RET_CODE_FILE_TRANS_DUP_ERROR = "630"; //파일중복 수신 오류 + + public static String getName_BOKJJ_RET_CODE(String code) { + return code==null ? "null" : + code.equals(BOKJJ_RET_CODE_SUCCESS )? "정상" : + code.equals(BOKJJ_RET_CODE_PROTO )? "전문흐름순서 오류 " : + code.equals(BOKJJ_RET_CODE_ALREADY_RECEIVED )? "기수신 자료임 " : + code.equals(BOKJJ_RET_CODE_DATE_ERROR )? "헤더 전문 내 날짜 오류 " : + code.equals(BOKJJ_RET_CODE_REC_COUNT_ERROR )? "수신건수와 헤더 또는 트레일러건수 불일치" : + code.equals(BOKJJ_RET_CODE_ID_ERROR )? "참가기관ID 오류 " : + code.equals(BOKJJ_RET_CODE_PASSWORD_ERROR )? "비밀번호 오류 " : + code.equals(BOKJJ_RET_CODE_OPCODE_ERROR )? "업무관리정보 오류 " : + code.equals(BOKJJ_RET_CODE_HDTLER_ERROR )? "헤더/트레일러 구분 코드 오류 " : + code.equals(BOKJJ_RET_CODE_JOBCODE_ERROR )? "업무구분코드 오류 " : + code.equals(BOKJJ_RET_CODE_TEL_CODE_ERROR )? "전문종별코드 오류 " : + code.equals(BOKJJ_RET_CODE_TRX_GBN_CODE_ERROR )? "거래구분코드 오류 " : + code.equals(BOKJJ_RET_CODE_SND_RCV_FLAG_ERROR )? "송수신 FLAG 오류 " : + code.equals(BOKJJ_RET_CODE_RTN_CODE_ERROR )? "응답코드 오류 " : + code.equals(BOKJJ_RET_CODE_SND_RCV_JOBCODE_ERROR)? "송수신 업무구분 코드 오류 " : + code.equals(BOKJJ_RET_CODE_FILE_TRANS_DUP_ERROR )? "파일중복 수신 오류 " : code; + } + public static final long BOKJJ_DELAY_MILISEC = 1000; + + /** + * 응답코드 (BOKNG_RET_CODE), 3자리 + */ + public static final String BOKNG_RET_CODE_000 = "000"; //정상 + public static final String BOKNG_RET_CODE_210 = "210"; //거래구분코드 불일치 오류 + public static final String BOKNG_RET_CODE_220 = "220"; //블록번호 오류 + public static final String BOKNG_RET_CODE_230 = "230"; //중복수신 오류 + public static final String BOKNG_RET_CODE_240 = "240"; //데이터 시퀀스 오류 / 데이터 건수 오류 + public static final String BOKNG_RET_CODE_250 = "250"; //데이터 수신 Timeout 오류 + public static final String BOKNG_RET_CODE_260 = "260"; //결번확인 오류 + public static final String BOKNG_RET_CODE_270 = "270"; //업무 개시전 오류 + public static final String BOKNG_RET_CODE_280 = "280"; //집계 응답전문 미수신(한은망 집계 처리시) + public static final String BOKNG_RET_CODE_310 = "310"; //송신자 ID 오류 + public static final String BOKNG_RET_CODE_320 = "320"; //송신자 Password 오류 + public static final String BOKNG_RET_CODE_330 = "330"; //수신구분 오류 + public static final String BOKNG_RET_CODE_340 = "340"; //전문전송일시 오류 + public static final String BOKNG_RET_CODE_350 = "350"; //파일명 오류 + public static final String BOKNG_RET_CODE_360 = "360"; //Data구분 오류 + public static final String BOKNG_RET_CODE_370 = "370"; //처리기준일 오류 + public static final String BOKNG_RET_CODE_910 = "910"; //업무코드 오류 + public static final String BOKNG_RET_CODE_920 = "920"; //기관코드 오류 + public static final String BOKNG_RET_CODE_930 = "930"; //전문종별코드 오류 + public static final String BOKNG_RET_CODE_940 = "940"; //수신FLAG 오류 + public static final String BOKNG_RET_CODE_950 = "950"; //응답코드 오류 + + public static String getName_BOKNG_RET_CODE(String code) { + return code==null ? "null" : + code.equals(BOKNG_RET_CODE_000)? "정상" : + code.equals(BOKNG_RET_CODE_210)? "거래구분코드 불일치 오류" : + code.equals(BOKNG_RET_CODE_220)? "블록번호 오류" : + code.equals(BOKNG_RET_CODE_230)? "중복수신 오류" : + code.equals(BOKNG_RET_CODE_240)? "데이터 시퀀스 오류 / 데이터 건수 오류" : + code.equals(BOKNG_RET_CODE_250)? "데이터 수신 Timeout 오류" : + code.equals(BOKNG_RET_CODE_260)? "결번확인 오류" : + code.equals(BOKNG_RET_CODE_270)? "업무 개시전 오류" : + code.equals(BOKNG_RET_CODE_280)? "집계 응답전문 미수신(한은망 집계 처리시)" : + code.equals(BOKNG_RET_CODE_310)? "송신자 ID 오류" : + code.equals(BOKNG_RET_CODE_320)? "송신자 Password 오류" : + code.equals(BOKNG_RET_CODE_330)? "수신구분 오류" : + code.equals(BOKNG_RET_CODE_340)? "전문전송일시 오류" : + code.equals(BOKNG_RET_CODE_350)? "파일명 오류" : + code.equals(BOKNG_RET_CODE_360)? "Data구분 오류" : + code.equals(BOKNG_RET_CODE_370)? "처리기준일 오류" : + code.equals(BOKNG_RET_CODE_910)? "업무코드 오류" : + code.equals(BOKNG_RET_CODE_920)? "기관코드 오류" : + code.equals(BOKNG_RET_CODE_930)? "전문종별코드 오류" : + code.equals(BOKNG_RET_CODE_940)? "수신FLAG 오류" : + code.equals(BOKNG_RET_CODE_950)? "응답코드 오류" : code; + } + + + /******************************************************************************* + * 금융정보분석원 사용 코드 + *******************************************************************************/ + + public static final String FIUSC_RES_CODE_SUCESS = "00"; //정상, 시퀀스와 크기 둘다 일치 + public static final String FIUSC_RES_CODE_ERROR = "11"; //오류, 시퀀그와 크기 둘다 불일치 + public static final String FIUSC_RES_CODE_ERROR_SEQ = "01"; //오류, 시퀀스 불일치 + public static final String FIUSC_RES_CODE_ERROR_SIZE = "10"; //오류, 크기 불일치 + + public static final String FIUSC_DATA_FLAG_BIN = "B"; //바이너리 모드 + public static final String FIUSC_RESUME_YN = "N"; //이어받기 사용안함 + public static final String FIUSC_EAI_CD = "eai.cd"; //중계기관코드 + + /** + * 전문전송일 (HDB_SND_DATE): YYYYMMDD 형태의 값을 전달하여야 한다. + */ + public static String getYYYYMMDD() + { + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); + String curDate = formatter.format(Calendar.getInstance().getTime()); + return curDate; + } + + /** + * 전문전송일 (HDB_SND_DATE): YYYYMMDD 형태의 값을 전달하여야 한다. + */ + public static String getYYYYMMDD( int days ) + { + Calendar temp = Calendar.getInstance ( ); + StringBuffer sbDate = new StringBuffer ( ); + temp.add ( Calendar.DAY_OF_MONTH, days ); + int nYear = temp.get ( Calendar.YEAR ); + int nMonth = temp.get ( Calendar.MONTH ) + 1; + int nDay = temp.get ( Calendar.DAY_OF_MONTH ); + + sbDate.append ( nYear ); + if ( nMonth < 10 ) + sbDate.append ( "0" ); + sbDate.append ( nMonth ); + if ( nDay < 10 ) + sbDate.append ( "0" ); + sbDate.append ( nDay ); + + return sbDate.toString ( ); + } + + /** + * 전문전송시간 (HDB_SND_TIME): HHMMSS 형태의 값을 전달하여야 한다. + */ + public static String getHHMMSS() + { + SimpleDateFormat formatter = new SimpleDateFormat("hhmmss"); + String curDate = formatter.format(Calendar.getInstance().getTime()); + return curDate; + } + + /** + * 수신기관 전문 번호 (HDB_RSV_DOCSEQ) 8자리, 송신측에서는 null이나 0으로 채워서 보낼 수 있다. + */ + public static final String RPS_HDB_RSV_DOCSEQ = "00000000"; + + /** + * 전체 파일 수 (HDB_TOT_FILE), 사용안함, 여기서는 00으로 세팅 + */ + public static final String RPS_HDB_TOT_FILE = "00"; + + /** + * 현재 파일 순번(HDB_CUR_FILE), 사용안함, 여기서는 00으로 세팅 + */ + public static final String RPS_HDB_CUR_FILE = "00"; + + /** + * 현재 파일명 (HDB_DOC_NAME), 30자리, --> 실행시간에 만들어짐. + */ + + /** + * 현재파일전체전문수 (HDB_CUR_TOT), 사용안함, 여기서는 00으로 세팅 + */ + public static final String RPS_HDB_CUR_TOT = "00"; + /** + * 현재파일현재순번 (HDB_CUR_NOW), 사용안함, 여기서는 00으로 세팅 + */ + public static final String RPS_HDB_CUR_NOW = "00"; + + /** + * 전문CASE명 (HDB_DOC_CASE), 사용안함, 여기서는 000000으로 세팅 + */ + public static final String RPS_HDB_DOC_CASE = "000000"; + + /** + * 송신자 추가정의 (HDB_SND_EXT), FILLER, 여기서는 공백으로 채움 + */ + public static final String RPS_HDB_SND_EXT = " "; + + /** + * 수신자 추가정의 (HDB_RSV_EXT), FILLER, 여기서는 공백으로 채움 + */ + public static final String RPS_HDB_RSV_EXT = " "; + + public static final String CMS_BIZ_GBN = ""; + + public static final String CMS_TRA_FLAG_BANK = ""; + + /** + * CMS에서 사용되는 응답코드 + **/ + public static final String RES_CODE_SUCESS = "000"; //정상 + public static final String RES_CODE_SYSTEM_ERROR = "090"; //시스템장애 + public static final String RES_CODE_SENDER_NAME_ERROR = "310"; //송신자명오류 + public static final String RES_CODE_SENDER_PWD_ERROR = "320"; //송신자암호오류 + public static final String RES_CODE_ALREADY_RECEIVED = "630"; //기전송 완료 + public static final String RES_CODE_NOT_REGISTERED = "631"; //해당은행 미등록 업무 + public static final String RES_CODE_FILENAME_ERROR = "632"; //비정상 화일명 + public static final String RES_CODE_BYTE_ERROR = "633"; //비정상전문 BYTE수 + public static final String RES_CODE_FILE_ORDER_ERROR = "634"; //파일 전송 순서 오류 + public static final String RES_CODE_FORMAT_ERROR = "800"; //FORMAT 오류 + + public static String getCmsRetDescription(String code) { + return code==null ? "null" : + code.equals(RES_CODE_SUCESS )? "정상" : + code.equals(RES_CODE_SYSTEM_ERROR )? "시스템장애" : + code.equals(RES_CODE_SENDER_NAME_ERROR )? "송신자명오류" : + code.equals(RES_CODE_SENDER_PWD_ERROR )? "송신자암호오류" : + code.equals(RES_CODE_ALREADY_RECEIVED )? "기전송 완료" : + code.equals(RES_CODE_NOT_REGISTERED )? "해당은행 미등록 업무" : + code.equals(RES_CODE_FILENAME_ERROR )? "비정상 화일명" : + code.equals(RES_CODE_BYTE_ERROR )? "비정상전문 BYTE수" : + code.equals(RES_CODE_FILE_ORDER_ERROR )? "파일 전송 순서 오류" : + code.equals(RES_CODE_FORMAT_ERROR )? "FORMAT 오류" :code; +} + + /** + * + * CMS에서 사용되는 전문 전송 일시 : MMDDhhmmss 형태의 값을 전달하여야 한다. + */ + public static String getMMddHHmmss() + { + SimpleDateFormat formatter = new SimpleDateFormat("MMddHHmmss"); + String curDate = formatter.format(Calendar.getInstance().getTime()); + return curDate; + } + + /** + * + * 신한은망에서 사용되는 전문 전송 일시 : YYYYMMDDhhmmss 형태의 값을 전달하여야 한다. + */ + public static String getYYYYMMddHHmmss() + { + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); + String curDate = formatter.format(Calendar.getInstance().getTime()); + return curDate; + } + + /** + * 1. 기능 : 현재 요일을 숫자로 리턴하는 Method + * 2. 처리 개요 : + * - 현재 요일을 숫자로 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 요일 숫자 + * @exception + **/ + public static int getDayOfWeekNum() { + Calendar c = Calendar.getInstance(); + return c.get ( Calendar.DAY_OF_WEEK ); + } + + /** + * 트랜잭션 코드 + */ + public static final String TRANSACTION_CODE = "transaction_code"; + + /** + * 업무구분코드 + */ + public static final String BIZ_GBN = "biz.gbn"; + + /** + * 자료구분코드 + */ + public static final String DAT_GBN = "data.gbn"; + + /** + * 은행/센타 코드 + */ + public static final String BANK_CODE = "bank.code"; //은행코드 + public static final String CENTER_CODE = "center.code"; //센타코드 + + /** + * 송수신 플래그 + * "C" - 센터에서 전문을 발생할 시, "B" - 은행 및 기관 에서 전문을 발생할 시 + */ + public static final String TRA_FLAG_CENTER = "tra.flag.center"; + public static final String TRA_FLAG_BANK = "tra.flag.bank"; + + public static final String TRA_FLAG_SEND = "tra.flag.send"; + public static final String TRA_FLAG_RECV = "tra.flag.recv"; + + /** + * 퇴직연금 송신 기관 관련 + * 송신기관 구분 (HDB_SND_CLS) : 1:운영, 2:기록, 3:자산, 4:상품, 5:자산운영 + * 송신기관 코드 (HDB_SND_ID) + */ + public static final String HDB_SND_CLS = "send.class"; + public static final String HDB_SND_ID = "send.id"; + public static final String HDB_RCV_CLS = "rcv.cls"; + + /** + * CMS 방식의 다양한 TR code, 기관코드, ll 필드등을 위해 다음을 추가함. + */ + public static final String ORGN_CD_LEN = "bank.code.len"; + public static final String TRCD_LEN = "tr.code.len"; + public static final String FILE_NAME_LEN = "file.name.len"; + public static final String CMS_CIPHER_USE = "cipher.yn"; + public static final String TRAN_GBN_SEND = "send.tran.gbn"; + public static final String TRAN_GBN_RECV = "recv.tran.gbn"; + public static final String SLEEP_TIME = "sleep.time"; + public static final String SLEEP_TIME_0620 = "sleep.time.0620"; + public static final String SLEEP_TIME_POST = "sleep.time.post"; + public static final String LENGTH_OFFSET = "length.offset"; + public static final String IGNORE_DATA_LEN = "ignore.data.len"; + + public static final String FILLER_LEN_0600 = "fill.len.0600"; + public static final String APPEND_LL_LEN = "append.ll.len"; + + public static final String SKIP_LF = "skip.lf"; + + public static final String SKIP_SUMMARY = "skip.sum"; + public static final String DEBUG = "debug.yn"; + + + // 여신금융협회 + public static final String BLOCKING_COUNT = "blocking.count"; // 파일별로 블러킹 개수가 정해져 있음 + public static final String PADDING_LEN = "padding.len"; // 파일별로 블러킹 하고 나서 추가 패딩하는 길이 + public static final String RECV_REC_LEN = "recv.rec.len"; // 해당 파일의 수신시 레코드 크기 + + /** + * 프로퍼티 그룹을 가져오기 위한 PREFIX + * 프로퍼티 그룹은 REFIX+배치 업무 코드 + */ + public static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + + /** + * 조건문장 + */ + public final static String BLOCKEND = "BLOCKEND"; + public final static String COMPARE = "COMPARE"; + public final static String LOSS = "LOSS"; + public final static String EOF = "EOF"; + public final static String LOSSEND = "LOSSEND"; + public final static String TIMEOUT = "TIMEOUT"; + public final static String ERROR = "ERROR"; + public final static String SEND = "SEND"; + public final static String RECV = "RECV"; + public final static String NOFILE = "NOFILE"; + public final static String NOBODY = "NOBODY"; + public final static String DUP = "DUP"; + public final static String IGNORE = "IGNORE"; + + /** + * 어음이미지 시스템에서 사용되는 응답코드 + **/ + public static final String BI_RES_CODE_SUCESS = "000"; //정상 + public static final String BI_RES_CODE_SYSTEM_ERROR = "090"; //시스템장애 + public static final String BI_RES_CODE_BEFORE_FILE = "110"; //작업시작파일 처리전 수신요청 + public static final String BI_RES_CODE_AFTER_FILE = "120"; //작업시작파일 처리후 수신요청 + public static final String BI_RES_CODE_SENDER_NAME_ERROR = "210"; //송신자명오류 + public static final String BI_RES_CODE_SENDER_PWD_ERROR = "220"; //송신자암호오류 + public static final String BI_RES_CODE_ALREADY_RECEIVED = "410"; //기전송 완료 + public static final String BI_RES_CODE_NOT_REGISTERED = "420"; //해당은행 미등록 업무 + public static final String BI_RES_CODE_FILENAME_ERROR = "430"; //비정상 화일명 + public static final String BI_RES_CODE_BYTE_ERROR = "440"; //비정상전문 BYTE수 + public static final String BI_RES_CODE_FILE_SIZE_ERROR = "710"; //파일 사이즈 오류 + public static final String BI_RES_CODE_FORMAT_ERROR = "800"; //FORMAT 오류 + public static final String BI_RES_CODE_ETC_ERROR = "900"; //기타 오류 + + public static final String BI_TR_CLASS_RECV = "R"; + public static final String BI_TR_CLASS_SEND = "S"; + + public static String[] BIIMG_RES_CODES ={"000", "101", "102", "401", "402", "403", "404", "610", "800", "900"}; + public static boolean isDefinedBiImgResCode (String code){ + int len = BIIMG_RES_CODES.length; + for (int i=0; i> Node Manager (TSEAIBR03) 에서 해당 Node 정보 조회...\r\n"+logHeader); + NodeInfoVO nvo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, execPhaseCode); + if (nvo == null) { + //실행대상 단계코드를 TSEAIBR03 테이블에서 찾을 수 없음 (RuleCode:{1}, PhaseCode:{2}) + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJH002", new String[] {strRuleCode, execPhaseCode}); + throw new Exception(errMsg); + //setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정 + } + String execPhaseClassName = nvo.getFlowComp(); + logger.debug("{} => [RuleCode: "+ nvo.getRuleCode() +"] "+ + "[PhaseCode: "+ nvo.getPhaseCode() +"] "+ + "[PhaseType: "+ nvo.getPhaseType() +"] "+ + "[ClassName: "+ nvo.getFlowComp() +"] "+ + "[TelegramID: "+ nvo.getTelegramID() +"]"+ logHeader); + + //Flow Component 클래스명 값이 있는지 체크 + if (execPhaseClassName==null || execPhaseClassName.equals("")) { + // 실행대상 단계코드의 해당 FlowComponent 클래스이름이 지정되어 있지 않음 (RuleCode:{1}, PhaseCode:{2}) + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJH003", new String[] {strRuleCode, execPhaseCode}); + throw new Exception(errMsg); + //setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정 + + } else { + // body 쪽 NEXT 설정 + batchDoc.getBatchMsg().getBody().setFlowPhaseCode(execPhaseCode); + batchDoc.getBatchMsg().getBody().setPhaseType(nvo.getPhaseType()); //단계 타입 (SEND, RECV, END, EEND 중 하나) + + // PhaseInfo 설정 by Node Info + batchDoc.getBatchMsg().getPhaseinfo().setRuleCode (strRuleCode); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseCode (execPhaseCode); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseType (nvo.getPhaseType()); + batchDoc.getBatchMsg().getPhaseinfo().setFlowClassName (nvo.getFlowComp()); + batchDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (nvo.getLengthField()); + batchDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (nvo.getTelegramID()); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName (""); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (""); + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (""); + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue (""); + } + + + // 1. JobProcessData와 관련된 작업 수행 + // 1-1 JobProcessData에서 이전단계에서 사용했던 '다음단계'결정용 Stage변환룰 정보를 삭제해준다. + HashMap curr_job_data = JobProcessData.getInstance().getBatchStageData(strUUID); + //Flow 최초 단계 수행시 해당 UUID의 HashMap 생성함 + if (curr_job_data == null) curr_job_data = new HashMap(); + curr_job_data.remove(JobProcessData.PROCDATA_NEXTSTAGE); + + // 1-2 TSEAIBR02 테이블에서 현재 Node의 가능 Stage를 모두 구해서 JobProcessData에 할당 + // Next Possible Stage 가 없으면, 현재 지정된 단계가 최종이라는 뜻. + logger.debug("{} >> Phase Manager (TSEAIBR02) 에서 해당 Node의 수행 가능 Phase 목록 조회... [RuleCode: " + strRuleCode + "] [PhaseCode: "+ execPhaseCode +"]"+ logHeader); + ArrayList al = PhaseInfoManager.getInstance().getPhaseInfo(strRuleCode, execPhaseCode); + if (al.size() > 0) { + //NEXT Stage 목록 debug logging... + for (int i=0; i< al.size(); i++) { + PhaseInfoVO pvo = (PhaseInfoVO) al.get(i); + logger.debug("{} => "+ (i+1) +". [PhaseCode: "+ pvo.getPhaseCode() +"] [PhaseSeq: "+ pvo.getPhaseSeq() +"] [TelegramID: "+ pvo.getTelegramID() +"] [NextPahseCode: "+ pvo.getNextPhaseCode() +"]"+ logHeader); + } + + // END, EEND 단계인 경우 TSEAIBR02 테이블에 단계 정보가 없어도 해당 단계를 수행함 + //} else if (execPhaseCode.trim().equalsIgnoreCase("END") || execPhaseCode.trim().equalsIgnoreCase("EEND")) { + // logger.debug("{} => 'END' 또는 'EEND' 단계임. 해당 종료 단계를 수행 후 배치 작업을 종료함.", logHeader); + + // NEXT Stage가 없고, "END" 나 "EEND" 가 아닌 경우에는 에러 처리함 + } else { + //실행대상 단계코드를 TSEAIBR02 (Phase) 테이블에서 찾을 수 없음 (RuleCode:{1}, PhaseCode:{2}) + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJH004", new String[] {strRuleCode, execPhaseCode}); + throw new Exception(errMsg); + //setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정 + } + + curr_job_data.put(JobProcessData.PROCDATA_NEXTSTAGE, al); + JobProcessData.getInstance().setBatchStageData(strUUID, curr_job_data); + + // 2. 클래스 생성 + logger.info("{} >> 수행할 단계 클래스 생성 및 execute() 호출...\r\n"+ logHeader); + JobComponentService phaseStage = (JobComponentService)Class.forName(execPhaseClassName).newInstance(); + phaseStage.setEAIBatchMessage(batchDoc); + + // 3. 해당 클래스를 호출한다. + logger.info("{} => ############################ ClassName: [" + execPhaseClassName + "] ############################"+ logHeader); + //======================================================================== + batchDoc = phaseStage.execute(); + //======================================================================== + logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+ + batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+ + batchDoc.getBatchMsg().getHeader().getFileName() +" / "+ + batchDoc.getBatchMsg().getHeader().getRuleCode() +"] "; + + //단계 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + //현 단계 DB 로깅 + LogUtil.setLog(batchDoc); + + logger.debug("{} ■ 단계 Logging 종료 !! [RuleCode: " + strRuleCode + "] [PhaseCode: "+ execPhaseCode +"]"+ logHeader); + + + } catch (Exception ex) { + //FlowController 에서 해당 단계 수행시 Exception 발생. (RuleCode:{1}, PhaseCode:{2}) + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJH001", new String[] {strRuleCode, execPhaseCode}); + throw new Exception(errMsg); + //setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정 + } + } + + public void end() throws Exception + { + logger.info("{} ================================================================================================="+ logHeader); + logger.info("{} ▷▷▷▷▷ FlowController 종료 : "+ batchDoc.getBatchMsg().getHeader().getRuleCode() +" ("+ batchDoc.getBatchMsg().getHeader().getRuleDesc() +")"+ logHeader); + logger.info("{} ================================================================================================="+ logHeader); + //logger.info("{} ▷ Batch Socket Count : " + BatchRunningJobManager.getInstance().getRunningJobCount(), logHeader); + //logger.info("{} ▷ Job Process Data Count : " + JobProcessData.getInstance().getBatchStageDataCount(), logHeader); + //logger.info("{} =================================================================================================", logHeader); + } + + public void handleException(Exception ex) + { + try { + //Exception ex = this.context.getExceptionInfo().getException(); + + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJH006"); + logger.error("{"+logHeader+"}" + " {"+"logHeader"+"}" + errMsg, ex); + + // DB로그 처리 + new JobFinishHandler(batchDoc).handleErrorEnd(errMsg); + + } catch (Exception e) { + logger.error("{"+logHeader+"} ★★★★★ FlowController JPD 예외 처리 중 에러 !! ★★★★★\r\n"+ e.getMessage()); + } + + } + +/* + private void setNextPhaseAsError(String strRuleCode, String strErrMsg) throws Exception + { + NodeInfoVO err_nvo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, this.PHASECODE_ERROR_END); + // body 쪽 NEXT 설정 + batchDoc.getEAIBatchMessage().getBody().setFlowPhaseCode(this.PHASECODE_ERROR_END); + batchDoc.getEAIBatchMessage().getBody().setPhaseType(""); + // PhaseInfo 설정 by Node Info + batchDoc.getEAIBatchMessage().getPhaseinfo().setRuleCode (strRuleCode); + batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseCode (this.PHASECODE_ERROR_END); + batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseType (err_nvo.getPhaseType()); + batchDoc.getEAIBatchMessage().getPhaseinfo().setFlowClassName (err_nvo.getFlowComp()); + batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthFieldIndex (err_nvo.getLengthField()); + batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthTelegramID (err_nvo.getTelegramID()); + batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthClassName (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthMsgCode (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseSeq (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseTelegramID (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseClassName (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseMsgCode (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setTelegramTypeValue (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setBizCodeValue (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setControlCodeValue (""); + batchDoc.getEAIBatchMessage().getPhaseinfo().setResponseCodeValue (""); + + Logging(ERROR, strErrMsg); + batchDoc.getEAIBatchMessage().getBody().setErrorMsg(strErrMsg); + } +*/ + + + public void procFileEvent(String recvdirPath, String recvfileName, String lines) + throws Exception { + } + +} diff --git a/src/com/eactive/eai/batch/job/jobHandle/JobFinishHandler.java b/src/com/eactive/eai/batch/job/jobHandle/JobFinishHandler.java new file mode 100644 index 0000000..dca2dca --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobHandle/JobFinishHandler.java @@ -0,0 +1,185 @@ +package com.eactive.eai.batch.job.jobHandle; + +//import com.eactive.eai.batch.running.BatchRunningJobManager; +//import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.batch.job.jobModule.Component.JobComponentService; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.common.util.Logger; + +public class JobFinishHandler +{ + protected Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + private String logHeader = ""; + + private BatchDoc batchMsgDoc; + private String gUUID = ""; + private String subUUID = ""; + private String gRuleCode = ""; + + public JobFinishHandler(BatchDoc batchMsgDoc) { + this.batchMsgDoc = batchMsgDoc; + this.gUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID(); + this.subUUID = batchMsgDoc.getBatchMsg().getBody().getSubUUID(); + this.gRuleCode = batchMsgDoc.getBatchMsg().getHeader().getRuleCode(); + + logger = batchMsgDoc.getLogger(); + + logHeader = "["+ batchMsgDoc.getBatchMsg().getHeader().getUUID() +" / "+ + batchMsgDoc.getBatchMsg().getHeader().getProcessCode() +" / "+ + batchMsgDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+ + batchMsgDoc.getBatchMsg().getHeader().getProcessType() +" / "+ + batchMsgDoc.getBatchMsg().getHeader().getFileName() +" / "+ + batchMsgDoc.getBatchMsg().getHeader().getRuleCode() +"] "; + } + + + //FlowController 관련 JPD 에서 오류 발생시 오류를 처리한다. + public void handleErrorEnd(String errMsg) { + try { + //1. 에러메시지 설정 + if (errMsg != null && !errMsg.equals("")) { + if (!batchMsgDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchMsgDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + //2. 에러종료 단계 수행 + executeFlowErrorEndPhase(); + + //3. 작업 진행정보 제거 + deleteProcessingInfo(); + + //4. 에러종료 DB Log + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchMsgDoc, batchMsgDoc.getBatchMsg().getBody().getErrorMsg()); + + } catch (Exception e) { + logger.error("[handleErrorEnd]처리 중 오류 발생 -" + e.getMessage(),e ); + } + } + + public void handleSuccessEnd() { + try { + //1. 정상종료 단계 수행 + executeFlowSuccessEndPhase(); + //2. 작업 진행정보 제거 + deleteProcessingInfo(); + + //3. 정상종료 DB Log + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLog(batchMsgDoc); + LogUtil.setEndLog(batchMsgDoc); + + } catch (Exception e) { + logger.error("[handleSuccessEnd]처리 중 오류 발생 -" + e.getStackTrace() ); + } + } + + /** + * Exception을 throw 하지 않는다. + */ + private void executeFlowErrorEndPhase() { + logger.info("{"+logHeader+"}"+" ▷ 에러종료 단계("+ FlowController.PHASECODE_ERROR_END +") 수행......"); + NodeInfoVO nodeInfo = null; + try { + nodeInfo = NodeInfoManager.getInstance().getNodeInfo(gRuleCode, FlowController.PHASECODE_ERROR_END); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + //해당 RuleCode에 에러종료 단계가 없으면 디폴트 에러종료 단계 설정 + try { + if (nodeInfo == null) { + logger.info("{"+logHeader+"}"+ " => 해당 Rule 정보에 에러종료 단계 없음. 디폴트 에러종료 단계를 설정함."); + nodeInfo = new NodeInfoVO(); + nodeInfo.setRuleCode(gRuleCode); + nodeInfo.setPhaseCode(FlowController.PHASECODE_ERROR_END); + nodeInfo.setPhaseType(FlowController.PHASECODE_ERROR_END); + nodeInfo.setDesc("디폴트 에러종료 단계"); + nodeInfo.setLengthField(0); + nodeInfo.setTelegramID(""); + nodeInfo.setFlowComp("com.eactive.eai.batch.job.jobModule.Component.EEND"); + } + setPhaseInfoToBatchMsgDoc(nodeInfo); + executeFlowPhase(nodeInfo.getFlowComp()); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } + + /** + * Exception을 throw 하지 않는다. + */ + private void executeFlowSuccessEndPhase() { + logger.info("{"+"logHeader"+"}"+" ▷ 정상종료 단계("+ FlowController.PHASECODE_NORMAL_END +") 수행......"); + NodeInfoVO nodeInfo = null; + try { + nodeInfo = NodeInfoManager.getInstance().getNodeInfo(gRuleCode, FlowController.PHASECODE_NORMAL_END); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + //해당 RuleCode에 에러종료 단계가 없으면 디폴트 에러종료 단계 설정 + try { + if (nodeInfo == null) { + logger.info("{"+"logHeader"+"}"+" 해당 Rule 정보에 정상종료 단계 없음. 디폴트 정상종료 단계를 설정함."); + nodeInfo = new NodeInfoVO(); + nodeInfo.setRuleCode(gRuleCode); + nodeInfo.setPhaseCode(FlowController.PHASECODE_NORMAL_END); + nodeInfo.setPhaseType(FlowController.PHASECODE_NORMAL_END); + nodeInfo.setDesc("디폴트 정상종료 단계"); + nodeInfo.setLengthField(0); + nodeInfo.setTelegramID(""); + nodeInfo.setFlowComp("com.eactive.eai.batch.job.jobModule.Component.END"); + } + setPhaseInfoToBatchMsgDoc(nodeInfo); + executeFlowPhase(nodeInfo.getFlowComp()); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } + + private void setPhaseInfoToBatchMsgDoc(NodeInfoVO nodeInfo) { + //body 쪽 단계정보 설정 + batchMsgDoc.getBatchMsg().getBody().setFlowPhaseCode(nodeInfo.getPhaseCode()); + batchMsgDoc.getBatchMsg().getBody().setPhaseType(nodeInfo.getPhaseType()); + //Phase 쪽 단계정보 설정 + batchMsgDoc.getBatchMsg().getPhaseinfo().setRuleCode (nodeInfo.getRuleCode()); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseCode (nodeInfo.getPhaseCode()); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseType (nodeInfo.getPhaseType()); + batchMsgDoc.getBatchMsg().getPhaseinfo().setFlowClassName (nodeInfo.getFlowComp()); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (nodeInfo.getLengthField()); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (nodeInfo.getTelegramID()); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue (""); + } + + private void executeFlowPhase(String className) throws Exception { + JobComponentService phaseExecuteObj = (JobComponentService) Class.forName(className).newInstance(); + phaseExecuteObj.setEAIBatchMessage(batchMsgDoc); + + //해당 클래스를 수행 + logger.info("{"+"logHeader"+"} => ############################ ClassName: [" + className + "] ############################"); + batchMsgDoc = phaseExecuteObj.execute(); + } + + private void deleteProcessingInfo() throws Exception { + logger.info("{"+logHeader+"} ▷ JobProcessData 에서 해당 UUID 정보 삭제... [UUID: "+ gUUID +"]" ); + JobProcessData.getInstance().delBatchStageData(gUUID); + + logger.info("{"+logHeader+"} ▷ Schedule Processing 테이블 (TSEAIBS04) 에서 해당 UUID 정보 삭제... [UUID: "+ gUUID +"]"); + SchedulerMessageManager.getInstance().deleteJobFromProcessing(gUUID, subUUID); + } +} diff --git a/src/com/eactive/eai/batch/job/jobHandle/JobProcessData.java b/src/com/eactive/eai/batch/job/jobHandle/JobProcessData.java new file mode 100644 index 0000000..304ad06 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobHandle/JobProcessData.java @@ -0,0 +1,65 @@ +package com.eactive.eai.batch.job.jobHandle; + +//import com.eactive.eai.batch.doc.BatchDoc; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.common.util.Logger; + + +public class JobProcessData +{ + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + private static JobProcessData instance = new JobProcessData(); + public static final String PROCDATA_PRE_TELEGRAM = "PRE_TELEGRAM"; + public static final String PROCDATA_NEXTSTAGE = "NEXT_STAGE"; + public static final String PROCDATA_BLOCKDATA = "PROCDATA_BLOCKDATA"; + public static final String PROCDATA_MISSDATA = "PROCDATA_MISSDATA"; + public static final String PROCDATA_FIRST_MISS = "PROCDATA_FIRST_MISS"; + public static final String PROCDATA_LAST_MISS = "PROCDATA_LAST_MISS"; + + private HashMap hm_batchData; + + private JobProcessData() { + hm_batchData = new HashMap(); + } + + public static JobProcessData getInstance() { + return instance; + } + + public synchronized void addBatchStageData(String strUUID, HashMap> hmData) + { + Object obj = hm_batchData.get(strUUID); + if (obj != null) { + logger.warn("[JobProcessData] addBatchMsgDoc >> UUID["+strUUID+"] 에 이미 데이터가 있습니다." + obj); + hm_batchData.remove(strUUID); + } + hm_batchData.put(strUUID, hmData); + } + + @SuppressWarnings("unchecked") + public synchronized HashMap getBatchStageData(String strUUID) + { + return (HashMap)hm_batchData.get(strUUID); + } + + public synchronized void setBatchStageData(String strUUID, HashMap hm) + { + hm_batchData.remove(strUUID); + hm_batchData.put(strUUID, hm); + } + + public synchronized void delBatchStageData(String strUUID) + { + this.hm_batchData.remove(strUUID); + } + + public synchronized int getBatchStageDataCount() { + return hm_batchData.size(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/DefaultTelegram.java b/src/com/eactive/eai/batch/job/jobItem/DefaultTelegram.java new file mode 100644 index 0000000..52c85cd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/DefaultTelegram.java @@ -0,0 +1,955 @@ +package com.eactive.eai.batch.job.jobItem; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; + +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + +public class DefaultTelegram implements TelegramService +{ + + //Telegram 전문구조를 나타내는 MsgMetaDstcd + protected String TELEGRAM_META_CODE = ""; + + protected BatchDoc batchDoc; + + // FileLoger + protected Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public String logHeader; + public String logNodeCount; + + public String ErrorMsg = ""; + + public int nFileHeadTailLogSize = 500; + + /** + * Stage 변경 참조용 ArrayList : 실제 FlowComponent에서 조회해서 텔레그램쪽으로 지정해 줘야 한다. + */ + public ArrayList al_NextStage = new ArrayList(); + /** + * 필드를 저장한 Array List : 각각은 Byte Array로 이루어진다. + */ + public ArrayList al_Field = new ArrayList(); + /** + * 필드의 Property를 String배열로 가진다. 각 필드 처리시 alignment결정을 위한 것이다. + * TSEAIBM02의 각 필드에 대한 필드 특성치 (TSEAIBM01참조) 에 대한 배열이다. + * EX> AN : 좌측정렬, NN : 우측정렬 + */ + public String[] al_FieldProps ; + /** + * 문자열로 각 필드의 실질적인 길이를 나타낸다. + * 길이값으로 'XX'가 들어 있는 경우가 비정형 필드가 된다. + */ + public String[] al_FieldLength; + public String[] al_FieldIDs; + public String[] al_FieldNames; + + /** + * Telegram Class의 상태에 따른 KEY WORD 저 + */ + public String conditionTxt = ""; + /** + * 모든 Send/Recv 에 사용될 공통 필드 선언 --> SEND TelegramClass 에서 전문 조립시 사용 + * DB에서 읽어들인 값... + */ + // 전문 종별 : 룰 DB (TSEAIBR02) 의 SEND 단계에 들어 있는 해당 전문 송신에 사용될 전문종별 값이다. + public String fldTelegramType = ""; + // 업무관리 코드 : 룰 DB (TSEAIBR02) 의 SEND 단계에 들어 있는 해당 전문 송신에 사용될 업무관리코드 값이다. + public String fldOpCode = ""; + // 거래구분코드 : 룰 DB (TSEAIBR02) 의 SEND 단계에 들어 있는 해당 전문 송신에 사용될 거래구분코드 값이다. + public String fldTrClass = ""; + + //이전 단계 RECV 텔레그램 전문 해석 후 응답코드 값 저장. + //기본값은 TelegramKeys.RPS_HDB_RET_CODE_SUCCESS (000) 값을 가짐. + public String resolveResponseCode = TelegramKeys.RPS_HDB_RET_CODE_SUCCESS; + + public String telegramType = ""; + + /** + * SEND 단계에서 사용될 함수 : 룰에 있던 값 + */ + public String getFldTelegramType() + { + return this.fldTelegramType; + } + /** + * SEND 단계에서 사용될 함수 : 룰에 있던 값 + */ + public void setFldTelegramType(String strTelegramType) + { + this.fldTelegramType = strTelegramType; + } + /** + * SEND 단계에서 사용될 함수 : 룰에 있던 값 + */ + public String getFldOpCode() + { + return this.fldOpCode; + } + /** + * SEND 단계에서 사용될 함수 : 룰에 있던 값 + */ + public void setFldOpCode(String strOpCode) + { + this.fldOpCode = strOpCode; + } + /** + * SEND 단계에서 사용될 함수 : 룰에 있던 값 + */ + public String getFldTrClass() + { + return this.fldTrClass; + } + /** + * SEND 단계에서 사용될 함수 : 룰에 있던 값 + */ + public void setFldTrClass(String strTrClass) + { + this.fldTrClass = strTrClass; + } + + /** + * BatchDoc 인스탄스 지정 + */ + public void setEAIBatchMessage(BatchDoc pBatchDoc) + { + batchDoc = pBatchDoc; + logger = batchDoc.getLogger(); + } + + public BatchDoc getEAIBatchMessage() + { + return batchDoc; + } + + /** + * Telegram 전문별 특별한 수행기능 처리 + */ + + /** + * boolean doPreExecution + * 지정된 전문의 구성 필드 배열 선언 + */ + public boolean doPreExecute() + { + try { + /* 1. 단계 기본 정보 추출*/ + TelegramManager telegramManager = TelegramManager.getInstance(); + /* 2. 전문 입력값 생성 + * - [0]에서 [7]까지는 공통부 (CMS은행 기준) + * - 나머지는 개별부 + * - 주의사항: 전문의 길이를 정의하는 필드는 모든 값을 입력한 다음에 정의되어야 한다. + * 예, CMS은행의 경우 제일 첫 필드가 전문의 길이를 저장하는 필드이이다. objs[0] 참조 + */ + // 전문필드의 갯수만큼 임시변수 생성 + this.al_FieldLength = telegramManager.getTelegramFieldLengthsArray(this.TELEGRAM_META_CODE); + this.al_FieldProps = telegramManager.getTelegramFieldTypesArray (this.TELEGRAM_META_CODE); + this.al_FieldIDs = telegramManager.getTelegramFieldIDsArray (this.TELEGRAM_META_CODE); + this.al_FieldNames = telegramManager.getTelegramFieldNamesArray (this.TELEGRAM_META_CODE); + + logger.info("{"+logHeader+"} 전문 [" + TELEGRAM_META_CODE + "] 의 필드 수 = " + this.al_FieldLength.length ); + + this.al_Field = new ArrayList(); + for (int i=0; i> ", logHeader, e); + } + return false; + } + + public boolean doPreExecuteAfterCopy() + { + return true; + } + + /** + * 전문 조립하기 / 헤체하기 + */ + public boolean doExecute() + { + return true; + } + + /** + * 전문 Validation : 송신할 전문, 수시한 전문 Validation + */ + public boolean doValidation() + { + return true; + } + + /** + * SEND 단계 : doPreExecute -> doExecute -> dePostExecute 순서로 호출 + * RECV 단계 : doPreExecute -> doExecute -> doPostExecute 순서로 호출 + */ + public boolean doPostExecute() + { + return true; + } + + /** + * 해당 전문의 총 길이값을 리턴해주는 함수 : 비정형 필드에 대한 고려를 하지 못했다. + * 사용안함. + */ + public int getTelegramLength() + { + int nTotalLength =0; + for (int i=0; i< al_Field.size(); i++) { + byte[] t_field = (byte[]) al_Field.get(i); + nTotalLength = nTotalLength + t_field.length; + } + + return nTotalLength; + } + + /** + * byte 배열로 받은 데이터를 한꺼번에 필드에 지정해 줄때 사용하는 함수. 비정형필드에 대한 고려가 없다. + * RECV 방식이 바뀌면서 사용안함. + * 단순 byte 배열보다는 각 필드별로 데이터를 사용함. + */ + public void setReceiveData(byte[] recvByteArray) + { + ByteArrayInputStream bin = new ByteArrayInputStream(recvByteArray); + + for (int i=0; i idx) { + byte[] aField = (byte[]) al_Field.get(idx); + return aField; + } + return null; + } + + /** + * byte[] getSendData() + * 각 필드 byte배열을 한꺼번에 조립하여 하나의 byte 배열로 리턴해주는 함수. 비정형 필드에 대해 고려하지 못했다. + * 사용안함. + */ + public byte[] getSendData() + { + ByteArrayOutputStream ba_out = new ByteArrayOutputStream(); + try { + for (int i=0; i < al_Field.size(); i++) + { + byte[] aField = (byte[]) al_Field.get(i); + ba_out.write(aField); + } + return ba_out.toByteArray(); + } catch (Exception ex) { + logger.debug("{"+logHeader+"} getSendData : Exception >> " + ex.getMessage()); + return null; + } + } + + /** + * Field Array ( al_Field )에서 지정된 인덱스의 값을 교체해 준다. + * + * 지정된 필드의 값을 변경해 준다. + */ + public void setFieldDataByIndex(int idx, byte[] buf) + { + if (this.al_Field.size() > idx) { + byte[] aField = (byte[]) al_Field.get(idx); + int len = aField.length; + if ( ( len == 1 ) && buf.length > 1) { + // XX인 경우 + len = (buf.length > 100) ? 100: buf.length; + aField = new byte[len]; + } else { + len = (len < buf.length)? len : buf.length; + } + for (int i=0; i stageList) + { + this.al_NextStage = stageList; + } + + /** + * SEND/RECV 단계에서 사용될 getNextStage 함수구현 ( Child Telegram Class 에서 공통으로 사용 ) + * + * 다섯개의 조건으로 다음 단계를 결정한다. + * 1. 전문종별 조건 : RECV단계에서 수신한 전문종별 조건값 + * 2. 업무관리코드 조건 : RECV단계에서 수신한 전문의 업무관리 코드 조건값 + * 3. 거래구분코드 조건 : RECV단계에서 수신한 전문의 거래구분코드 조건값 + * 4. 응답코드 조건 : RECV단계에서 수신한 전문의 응답코드 조건 값 + * 5. KeyWord 조건 : SEND/RECV 단계의 ConditionTxt로 지정되어 있는 KEY 조건 문장 + * + * 단계(Phase)변환 룰(TSEAIBR02)의 각 레코드에 위의 조건 필드값이 지정되어 있지 않는 경우, 해당 조건은 당연 TRUE 처리한다. + * KEYWORD 조건 값 중, 'TIMEOUT' 과 'ERROR'는 SEND/RECV의 단계 처리 중, 이미 처리된 부분이므로 여기에서는 고려대상이 안된다. + * 따라서 이 두 (TIMEOUT, ERROR)에 대한 부분은 무조건 false를 리턴할 것이다. + * + * 주의>> 조건이 지정되는 않은 레코드가 PhaseSeq상 앞에 있다면, 항상 해당 레코드의 다음 단계(Phase)가 다음 단계로 결정될 것이다. + * + * SEND 단계 : + * SEND 단계의 룰정보는 조건전문종별값,조건업무관리코드값,조건거래구분코드값,조건응답코드값 이 지정되어 있으면 안된다. + * SEND단계에서 상대방에게 통보하는 응답코드에 따른 룰분기를 할 경우, 상태변환 룰을 적용하고, 해당 텔레그래에서 getResCode를 구현하도록 한다. + * KeyWord 조건 값 사용 : + * RECV 단계 : + * 위의 다섯 가지 조건이 다 지정될 수도 있다. + */ + public PhaseInfoVO getNextStage() { + String strRecvTelegramType = this.getTelegramType(); + String strRecvOpCode = this.getOpCode(); + String strRecvTrClass = this.getTrClass(); + String strRecvResCode = this.getResCode(); + + boolean bCondition_TelegramType = false; //전문종류 + boolean bCondition_OpCode = false; //업무관리코드 + boolean bCondition_TrClass = false; //거래구분코드 + boolean bCondition_ResCode = false; //응답코드 + boolean bCondition_ConditionText= false; //배치 일괄처리 KEY WORD 처리용 + + logger.debug("{"+logHeader+"} getNextStage - strRecvTelegramType : "+strRecvTelegramType); + logger.debug("{"+logHeader+"} getNextStage - strRecvOpCode : "+strRecvOpCode); + logger.debug("{"+logHeader+"} getNextStage - strRecvTrClass : "+strRecvTrClass); + logger.debug("{"+logHeader+"} getNextStage - strRecvResCode : "+strRecvResCode); + logger.debug("{"+logHeader+"} getNextStage - ConditionTxt : " + this.getConditionTxt()); + logger.debug("{"+logHeader+"} this.al_NextStage.size() : " + this.al_NextStage.size()); + + //일단 상태변경 규칙 DB Table에 값이 없으면 해당 조건은 true로 처리해 준다. + int i; + for (i=0; i < this.al_NextStage.size(); i++) { + PhaseInfoVO phase_vo = this.al_NextStage.get(i); + // 1 전문종별 비교 + if (phase_vo.getCTelegramType().trim().length() == 0) { + bCondition_TelegramType = true; + } else { + if (phase_vo.getCTelegramType().trim().equalsIgnoreCase(strRecvTelegramType.trim())) + bCondition_TelegramType = true; + else + bCondition_TelegramType = false; + } + // 2 업무관리코드 비교 + if (phase_vo.getCOpCode().trim().length() == 0) { + bCondition_OpCode = true; + } else { + if (phase_vo.getCOpCode().trim().equalsIgnoreCase(strRecvOpCode)) + bCondition_OpCode = true; + else + bCondition_OpCode = false; + } + // 3 거래구분코드 비교 + if (phase_vo.getCTrClass().trim().length() == 0) { + bCondition_TrClass = true; + } else { + if (phase_vo.getCTrClass().trim().equalsIgnoreCase(strRecvTrClass)) + bCondition_TrClass = true; + else + bCondition_TrClass = false; + } + // 4 응답코드 비교 + if (phase_vo.getCResCode().trim().length() == 0) { + bCondition_ResCode = true; + } else { + if (phase_vo.getCResCode().trim().equalsIgnoreCase(strRecvResCode)) + bCondition_ResCode = true; + else + bCondition_ResCode = false; + } + // 5 CondtionTxt (KeyWord) 조건 비교 + if (phase_vo.getConditionTxt().trim().compareToIgnoreCase(this.getConditionTxt().trim()) == 0) + bCondition_ConditionText = true; + else + bCondition_ConditionText = false; + + // 네가지 모든 조건이 일치하면 .. 다시 Condition Text를 체크해 보아야 한다. + if (bCondition_TelegramType && bCondition_OpCode && bCondition_TrClass && bCondition_ResCode + && bCondition_ConditionText ) + { + break; + } + } + + if (i < this.al_NextStage.size()) { + logger.info("{"+logHeader+"} 다음 단계를 찾았습니다.-->" + (PhaseInfoVO)this.al_NextStage.get(i)); + return (PhaseInfoVO)this.al_NextStage.get(i); + } else { + logger.debug("{"+logHeader+"} 다음 단계를 찾을 수 없습니다.-->["+this.al_NextStage.size()+"]"); + for (i=0; i < this.al_NextStage.size(); i++) { + PhaseInfoVO phase_vo = (PhaseInfoVO) this.al_NextStage.get(i); + String strRuleCTelegramType = phase_vo.getCTelegramType().trim(); + String strRuleCOpCode = phase_vo.getCOpCode().trim(); + String strRuleCTrClass = phase_vo.getCTrClass().trim(); + String strRuleCResCode = phase_vo.getCResCode().trim(); + String strRuleConditionTxt = phase_vo.getConditionTxt().trim(); + logger.debug("{"+logHeader+"} index =["+ ( i + 1 ) +"]["+ phase_vo.getPhaseSeq()+"]strRuleCTelegramType-->[" + + strRuleCTelegramType+ "]strRuleCOpCode-->[" + +strRuleCOpCode + "]strRuleCTrClass-->["+strRuleCTrClass+"]strRuleCResCode-->[" + +strRuleCResCode+ "]strRuleConditionTxt-->["+strRuleConditionTxt+ "]"); + } + return null; + } + } + + /** + * RULE의 TelegramType만 가지고, 다음 텔레그램의 ID를 결정한다. + */ + public String getRealRecvTelegram() { + + //전문헤더의 {전문종별코드} 값 + String strRecvTelegramType = this.getTelegramType(); + + //일단 상태변경 규칙 DB Table에 값이 없으면 해당 조건은 true로 처리해 준다. + for (int i=0; i 다음 진행 Stage 결정을 위해서 + * + * 각 Telegram Class에서 오버라이드 구현 할 수도 있다. + */ + public boolean checkNextStageConditionTxt(String pConditionTxt) + { + logger.info("{"+logHeader+"} Function called : checkNextStageConditionTxt "); + if (pConditionTxt.equalsIgnoreCase(TelegramKeys.TIMEOUT) || + pConditionTxt.equalsIgnoreCase(TelegramKeys.ERROR) ) + { + // 이 두가지 경우는 이미 RECV단계에서 처리되므로 별도 처리하지 않는다. + return false; + } + return true; + } + + /** + * 상대방에게 보낼 응답코드값을 계산하도록 한다. + * 이전단계의 텔레그램을 찾아 이전 단계의 응답코드를 반환한다. + * + */ + public String getSendResponseCode() throws Exception + { + try { + //처음 업무개시 텔레그램이면 TelegramKeys.RPS_HDB_RET_CODE_SUCCESS (000)을 반환 + if (this.batchDoc.getBatchMsg().getBody().getNodeCount() == 1 ) + { + return resolveResponseCode; + } else + { + // 이전 전문을 구한다. + String strUUID = this.batchDoc.getBatchMsg().getHeader().getUUID(); + + HashMap hm_job = JobProcessData.getInstance().getBatchStageData(strUUID); + TelegramService prevTelegram = (TelegramService) hm_job.get(JobProcessData.PROCDATA_PRE_TELEGRAM); + if (prevTelegram == null) { + throw new Exception("not found previous telegram instance : needed in compiling of response telegram"); + } + return prevTelegram.getResolveResponseCode(); + } + } catch (Exception ex) { + throw new Exception(ex); + } + } + + + public String getConditionTxt() + { + return this.conditionTxt; + } + + public void setConditionTxt(String strConsitionTxt) + { + this.conditionTxt = strConsitionTxt; + } + + /** + * SEND 단계에서 전체 송신 전문의 길이를 구할 때 사용 + * 전문에 따라, 전체 전문의 길이를 포함하는 경우(퇴직연금)도 있고, 특정필드 이후 (길이값 필드 미포함) 의 + * 필드 길이에 대한 것만 전문길이로 표시하는 경우도 있으나, + * 이 함수는 실질적으로 통신 IO를 일으킬 때, 대상 송신 Bytes수를 리턴하도록 한다. + * + * 각 SEND Telegram 에서 개별 구현하도록 한다. + */ + public int getSendLength() + { + return 0; + } + + public String toString() + { + StringBuffer sb = new StringBuffer(); + // 여기서 텔레그램 클래스 인스탄스로 스트링으로 만들어준다. + + return sb.toString(); + } + /** + * 수신받은 전문구조에서 '전문종별' 값을 리턴한다. + * 각 TelegramClass에서 오버라이드 구현하도록 한다. + * RECV telegram 에서 구현 + */ + public String getTelegramType() + { + return this.telegramType; + } + + public void setTelegramType(String telegramType) + { + this.telegramType = telegramType; + } + + /** + * 수신받은 전문구조에서 '거래구분코드' 값을 리턴한다. + * 각 TelegramClass에서 오버라이드 구현하도록 한다. + * RECV telegram 에서 구현 + */ + public String getTrClass() + { + return ""; + } + /** + * 수신받은 전문구조에서 '응답코드' 값을 리턴한다. + * 각 TelegramClass에서 오버라이드 구현하도록 한다. + * RECV telegram 에서 구현 + */ + public String getResCode() + { + return ""; + } + /** + * 수신받은 전문구조에서 '업무관리코드' 값을 리턴한다. + * 각 TelegramClass에서 오버라이드 구현하도록 한다. + * RECV telegram 에서 구현 + */ + public String getOpCode() + { + return ""; + } + /** + * Default 구현으로 사용가능한 함수 + * + * 지정된 필드(idx)에 파라미터 값 (strValue)을 저장해 준다. + * 세번째 파라미터 Alignment 의 값이 ALIGNMENT_RIGHT("NN") 이면, 오른쪽정렬을 해주고 + * 아니면 왼쪽 정렬 해준다. + * + * 오른쪽 정렬일때는 필드값이 필드길이보다 짧을때 '0'을 채워넣어주고 + * 왼쪽 정렬일때 필드값이 필드길이보다 짧을때 ' '(SPACE)를 채워넣어준다. + */ + public void compileField(int idx, String strValue, String Alignment) throws Exception { + if (this.al_Field.size() > idx) { + int aFieldLength = ((byte[])this.al_Field.get(idx)).length; + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + try { + if ( strValue == null ) strValue = ""; + byte[] bValue = strValue.getBytes("KSC5601"); + + if (!Alignment.equalsIgnoreCase(ALIGNMENT_RIGHT)) { + if (aFieldLength> bValue.length) { + int n= aFieldLength - bValue.length; + for (int i=0; i bValue.length) { + int n = aFieldLength - bValue.length; + for (int i=0; i idx) { + return this.al_FieldLength[idx]; + } else { + return null; + } + } + + /** + * 특정필드 (idx)의 필드 property (AN, NN, ...)를 리턴해 준다. + * default 구현으로 사용가능 + */ + public String getFieldProperty(int idx) + { + if (this.al_Field.size() > idx) { + return this.al_FieldProps[idx]; + } else { + return null; + } + } + + /** + * 비정형 필드에 대한 송수신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) + { + return -1; + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드를 가지는 송신전문 처리 Telegram Class 에서 오버라이드 되어야 한다. + * SEND/RECV 단계에서, 각 비정형 필드(idx) 의 실질적인 처리대상 길이를 getCalculatedLength() 로 구한 다음, + * 이 함수를 반복적을 호출하여 해당 비정형필드 처리완료를 위한 데이터를 얻어낸다. + * 파라미터 data에 매번 호출 될 때, 비정형 필드 처리를 위한 적절한 데이터를 실어 주도록 한다. + * 리턴값은 실질적으로 파라미터 data에 실린 데이터의 길이 이다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + return 0; + } + + /** + * RECV단계에서 비정형 필드(idx)의 값을 통신 IO 를 통해 읽고, 그 결과를 텔레그램클래스로 넘겨주는 함수이다. + * 비정형 필드를 가지는 개별 Telegram Class 는 이 함수를 통해 각각 클래스가 가지는 비정형 필드(예> 파일 내용 등...)에 대한 + * 처리를 완료해 줘야 한다. + * + * 비정형 필드를 가지는 개별 Telegram Class에서 오버라이드 필요 + */ + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + // 전문 해체 후 응답코드 + public String getResolveResponseCode() + { + return resolveResponseCode; + } + //전문 해체 후 응답코드 + public void setResolveResponseCode(String code) + { + this.resolveResponseCode = code; + } + + //파일 송수신 시 파일의 헤더, 트레일러 값을 배치메시지에 설정 + public void setFileHeaderAndTrailer(File f) { + + //파일이 존재하지 않거나 디렉토리면 리턴 + if (f == null || !f.exists() || f.isDirectory()) { + logger.info("{"+logHeader+"} ["+ (f==null? "": f.getAbsolutePath()) +"]: 파일이 존재하지 않거나 디렉토리입니다. 파일헤더,트레일러 설정안함."); + return; + } + + FileInputStream fin = null; + try { + long fileHeaderSize = 500; //파일헤더 로그 디폴트 사이즈 + long fileTrailerSize = 500; //파일트레일러 로그 디폴트 사이즈 + BatchJobInfoVO jobInfo = DirInfoManager.getInstance().getFileInfo(batchDoc.getBatchMsg().getHeader().getJobCode()); + if (jobInfo != null) { + fileHeaderSize = jobInfo.getFileHeaderLogSize(); + fileTrailerSize = jobInfo.getFileTrailerLogSize()+2; + } + + if (fileHeaderSize == 0 && fileTrailerSize == 0) return; + + fin = new FileInputStream(f); + long fileSize = f.length(); + + //DB값, 파일사이즈, 4000Byte(로그저장 varchar 최대값) 중 최소값 설정 + fileHeaderSize = Math.min(Math.min(fileHeaderSize , fileSize), 4000L); + fileTrailerSize = Math.min(Math.min(fileTrailerSize, fileSize), 4000L); + + byte[] bufHeader = new byte[(int)fileHeaderSize ]; + byte[] bufTrailer = new byte[(int)fileTrailerSize]; + int readSize = 0; + + //파일 헤더 값 READ + if (fileHeaderSize > 0) { + readSize = fin.read(bufHeader, 0, bufHeader.length); + } + + //파일 트레일러 값 READ + if (fileTrailerSize > 0 && readSize >= 0 && readSize <= fileSize) { + int overlapSize = 0; //헤더와 트레일러의 겹치는 Byte 사이즈 + long skipSize = (fileSize - readSize) - fileTrailerSize; + + if (skipSize > 0) { //헤더와 트레일러가 겹치지 않음 -> 트레일러까지 위치 이동 + fin.skip(skipSize); + + } else if (skipSize < 0) { //헤더와 트레일러가 겹침 -> 오버랩핑되는 헤더의 뒷부분을 트레일러의 앞부분으로 카피 + overlapSize = Math.abs((int)skipSize); + System.arraycopy(bufHeader, readSize - overlapSize, bufTrailer, 0, overlapSize); + } + if (readSize < fileSize) { + readSize = fin.read(bufTrailer, overlapSize, bufTrailer.length - overlapSize); + } + } + byte[] bufTrailer2 = new byte[(int)fileTrailerSize-2]; + int startIndex = 0; + if ( bufTrailer[bufTrailer.length-2] == '\r' && bufTrailer[bufTrailer.length-1] == '\n'){ + startIndex = 0; + }else if ( bufTrailer[bufTrailer.length-1] == '\r' || bufTrailer[bufTrailer.length-1] == '\n'){ + startIndex = 1; + }else{ + startIndex = 2; + } + + System.arraycopy(bufTrailer, startIndex, bufTrailer2, 0, bufTrailer2.length); + + batchDoc.getBatchMsg().setFileHeader(new String(bufHeader)); + batchDoc.getBatchMsg().setFileTrailer(new String(bufTrailer2)); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 파일내용 헤더, 트레일러 DB로그 설정시 오류 발생 !! ★★★★★", logHeader, ex); + } finally { + try { if (fin != null) fin.close(); } catch (Exception e) {} + } + } + + /** + * 전문결정용 텔레그램에서 사용하도록 한다. + * 전문결정용 텔레그램 클래스를 이용하여, 수신단계 처리시에 예상치 못한 전문종별 수신시 남아있는 전문을 받아 통신 자원에서 + * 없애기 위해 사용하는 함수이다. --> RECV2 에서 사용 + */ + public int getRemainDataLength() + { + return -1; + } + + protected boolean checkType(String type, String value) + { + return (type.equalsIgnoreCase("AA") || type.equalsIgnoreCase("A"))? StringUtil.isAlpha(value) : + (type.equalsIgnoreCase("NN") || type.equalsIgnoreCase("N"))? StringUtil.isNumeric(value) : + (type.equalsIgnoreCase("AN"))? true : false; + } + + //특정 필드 Index (base 0) 의 값을 문자열로 리턴 + protected String getFieldValueString(int columnIndex) { + if (al_Field.size() <= columnIndex) return ""; + return new String( (byte[]) al_Field.get(columnIndex) ); + } + + protected String getFieldValueString(String fieldID){ + int inx = 0; + for ( inx=0; inx < al_FieldIDs.length; inx++){ + if ( al_FieldIDs[inx].equals(fieldID) ) + break; + } + return getFieldValueString(inx); + } + + /** + * 총길이에 맞게 String 앞을 0으로 채워주는 함수
+ * (예) makeFSpace("1234",6) --> "001234"
+ * @param String String Source + * @param int 총길이 + * @return String + */ + protected String makeZero(String Str, int totlen) + { + String retStr = ""; + + if(Str == null) return ""; + byte[] b_data = Str.getBytes(); + int slen = b_data.length; + + if( (totlen < 1) || (slen >= totlen) ) return Str; + for(int i=0; i< (totlen-slen); i++) { + retStr += "0"; + } + retStr += Str; + + return retStr; + } + + /** + * 총길이에 맞게 String 앞을 Space로 채워주는 함수
+ * (예) makeFSpace("1234",6) --> " 1234"
+ * @param String String Source + * @param int 총길이 + * @return String + */ + protected String makeSpace(String Str, int totlen) + { + String retStr = ""; + if(Str == null) return ""; + byte[] b_data = Str.getBytes(); + int slen = b_data.length; + + if( (totlen < 1) || (slen >= totlen) ) return Str; + for(int i=slen; i< (totlen); i++) { + retStr += " "; + } + retStr = Str + retStr; + return retStr; + } + + protected String substring(byte[] src, int offset, int len){ + try { + byte[] temp = new byte[len]; + System.arraycopy(src, offset, temp, 0, len); + return new String(temp); + } catch (Exception e) { + return null; + } + } + + protected Properties getTelegramInfo() throws Exception { + //BATCH작업구분코드 (processCode)와 기관코드(institutionCode)에 따른 프로퍼티 정보 가져오기 + String propName = TelegramKeys.PROP_GROUP_NAME_PREFIX + + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getInstitutionCode() + + "}"; + + PropManager pmanager = PropManager.getInstance(); + return pmanager.getProperties(propName); + } + + protected Properties getJobInfo() throws Exception { + //BATCH작업구분코드 (processCode)와 업무구분코드(BizCode)에 따른 프로퍼티 정보 가져오기 + String propName = TelegramKeys.PROP_GROUP_NAME_PREFIX + + "{" + + batchDoc.getBatchMsg().getHeader().getProcessCode() + + "_" + + batchDoc.getBatchMsg().getHeader().getBizCode() + + "}"; + + PropManager pmanager = PropManager.getInstance(); + return pmanager.getProperties(propName); + } + + public String getSeparator() { + return File.separator; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/TelegramService.java b/src/com/eactive/eai/batch/job/jobItem/TelegramService.java new file mode 100644 index 0000000..ae4f919 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/TelegramService.java @@ -0,0 +1,102 @@ +package com.eactive.eai.batch.job.jobItem; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; + +import java.util.ArrayList; + +public interface TelegramService +{ + public final String ALIGNMENT_RIGHT = "NN"; + public final String FIELD_NO_LENGTH = "XX"; + public void setEAIBatchMessage(BatchDoc pBatchDoc) ; + public BatchDoc getEAIBatchMessage(); + + /** + * Telegram 전문별 특별한 수행기능 처리 + */ + + public boolean doPreExecute(); + + public boolean doPreExecuteAfterCopy(); + + public boolean doPostExecute(); + + public boolean doExecute(); + + public boolean doValidation(); + + + + + public int getTelegramLength(); + + public void setReceiveData(byte[] recvByteArray); + + public byte[] getFieldDataByIndex(int idx); + + public byte[] getSendData(); + + public void setFieldDataByIndex(int idx, byte[] buf); + + public int getFieldCount(); + + public String getFieldLength(int idx); + + /** + * parameter로 전달되는 인덱스가 비정형 필드인지 체크하고, + * SEND : 해당 비정형 필드의 송신 길이를 리턴 + * RECV : 해당 비정형 필드의 수신 길이를 리턴 + */ + public int getCalculatedLength(int idx); + + public String getFieldProperty(int idx); + + public void setTelegramCode(String strTelegramCode); + + public void setNextStageInfo(ArrayList stageList); + + public PhaseInfoVO getNextStage() ; + public String getRealRecvTelegram(); + + public boolean doInformalField(int idx, byte[] data, int length); + + public int getSendLength(); + + public int getInformalFieldSendData(int idx, byte[] data); + + public String getConditionTxt() ; + public void setConditionTxt(String strConsitionTxt); + /** + * 각 전문이 응답전문일 때, 전문에 조립된 응답코드를 구하는 함수 + * 각 Telegram 클래스에서 구현되어야 함. 기본은 '000'으로 정상처리 응답코드를 리턴해주도록 한다. + */ + public String getSendResponseCode() throws Exception ; + + public String toString(); + + //------------------------------------------------------------------------------------ + public int getRemainDataLength(); //<-- 전문결정용 텔레그램에서 통신 자원상에 남아있는 전문의 남아있는 데이터 수를 계산한다. + + //-------------------------------------------------- 실제전문 내용을 읽어들이는 곳... + public String getFldTelegramType(); + public void setFldTelegramType(String strTelegramType); + public String getFldOpCode(); + public void setFldOpCode(String strOpCode); + public String getFldTrClass(); + public void setFldTrClass(String strTrClass); + + // 전문종별 + public String getTelegramType(); + public void setTelegramType(String telegramType); + // 거래 구분코드 + public String getTrClass() ; + // 응답코드 + public String getResCode(); + // 업무관리코드 + public String getOpCode(); + // 전문 해체 후 응답코드 + public String getResolveResponseCode(); + //전문 해체 후 응답코드 + public void setResolveResponseCode(String code); +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0200.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0200.java new file mode 100644 index 0000000..e8d0297 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0200.java @@ -0,0 +1,139 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class RECV_BI0200 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + + public RECV_BI0200() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + try{ + //송신자 암호 유효성 확인 + String sendPwd = new String ((byte[]) al_Field.get(10)); + if (sendPwd == null || sendPwd.length() <= 0) { + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_SENDER_PWD_ERROR); + + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI010"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + //요구송수신 테스트를 위해 암호 복호화 + //결재원과 테스트시에는 해당 클래스는 실행되지 않음. + Properties telegramInfo = getTelegramInfo(); + + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + //전송자명은 앞에서 7자리이며 7자리 미만은 Z로 채움.. + String passwd = EncryptManager.getInstance().getDeEncryptPwd(sendPwd, + telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3), + TelegramKeys.getYYYYMMddHHmmss().substring(2,8), + (batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8) + ); + logger.debug("{"+logHeader+"} RECV_BI0200 ] PASSWD : ["+passwd+"], getUserPassword : ["+batchDoc.getBatchMsg().getHeader().getUserPassword()+"]"); + + if (!passwd.startsWith(batchDoc.getBatchMsg().getHeader().getUserPassword())){ + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_SENDER_PWD_ERROR); + + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI010"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + + } + } + }catch(Exception e){ + String errMsg = ExceptionUtil.getErrorCode ("RECV_BI0200] occure exception at doValidation "); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0210.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0210.java new file mode 100644 index 0000000..881a641 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0210.java @@ -0,0 +1,90 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_BI0210 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_BI0210() { + // 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0220.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0220.java new file mode 100644 index 0000000..6c0b935 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0220.java @@ -0,0 +1,92 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_BI0220 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_BI0220() { + //업무종료 지시 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0230.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0230.java new file mode 100644 index 0000000..58c5c7f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0230.java @@ -0,0 +1,90 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_BI0230 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_BI0230() { + //업무종료보고 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0400.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0400.java new file mode 100644 index 0000000..fb6e066 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0400.java @@ -0,0 +1,210 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.util.ArrayList; +import java.util.HashMap; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.io.File; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BI0400 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_BI0400() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + + //파일구분 (6)+은행코드(3)+블럭번호(3)+전송일자(8) + //파일명 파싱해서 유효성 검사가 필요한 경우 ..... + //해당 내용 추가할것 by kscheon + String fName = new String ((byte[]) al_Field.get(6)); + long fSize = Long.parseLong(new String ((byte[]) al_Field.get(8))); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_BI0400][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_NOT_REGISTERED); + return true; + } + long recLen = bJobInfo.getFileRecSize(); + + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + //파일이 1024(byte)xn으로 구성되므로 + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{"+logHeader+"} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+fName+">>"); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + fName; + + File f = new File(fileFullName); + if (f.exists() && f.length() > 0) { + long file_size = f.length(); + if (file_size >= fSize ){ + //기수신완료 + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ALREADY_RECEIVED); + batchDoc.getBatchMsg().getBody().setCurFileSize(file_size); + } else { + int seq_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int seq_no = (int)file_size/seq_size; + + if (seq_no > 0){ + batchDoc.getBatchMsg().getBody().setCurFileSize(file_size); + batchDoc.getBatchMsg().getBody().setSeqNum(seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap miss_data = (HashMap) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장.. + if (miss_data == null) { + miss_data = new HashMap(); + } + + for (int i=0; i= batchDoc.getBatchMsg().getHeader().getFileSize()){ + logger.debug("{"+logHeader+"} doExecute ] recive file size is bigger than current file size "); + this.batchDoc.getBatchMsg().getBody().setErrorMsg("RECV_BI0410 - doExecute ] recive file size is bigger than current file size"); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + if (rSize > 0) { //기 송신된 파일이면서 미완료 파일이면 + totSeqSizeOffSize = (int)(rSize / seqSize); + if (totSeqSizeOffSize > 0 ) { // + + batchDoc.getBatchMsg().getBody().setSeqNum(totSeqSizeOffSize); + batchDoc.getBatchMsg().getBody().setCurFileSize(rSize); + byte[] fileData = new byte[seqSize]; + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(i) , fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + } + else {//기전송된 파일의 사이즈가 seqSize보다 작으면 처음부터 다시 송신 + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + String fName = new String ((byte[]) al_Field.get(6)); + + if (fName == null || fName.length() <= 0) { + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FILENAME_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fName; + String errCode = "BECEAIFJI007"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + +// String filegbn = fName.substring(0, 6).trim(); +// String fbankcd = fName.substring(6, 9).trim(); +// int fblockno = Integer.parseInt(fName.substring(9, 12)); +// String senddate = fName.substring(12, 20); + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + + + private boolean createFile () + { + + try { + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if (bis == null){ + logger.warn("FILE정보가 NULL입니다."); + return false; + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0420.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0420.java new file mode 100644 index 0000000..9f53636 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0420.java @@ -0,0 +1,176 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.util.HashMap; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_BI0420 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + private int recv_seq_no=0; + + public RECV_BI0420() { + // 결번확인지시 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + String _seq_no = new String ((byte[]) al_Field.get(8)); + recv_seq_no = Integer.parseInt(_seq_no); + + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_seq_no < seq_no){ + // 0410으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{"+logHeader+"} current block_no is bigger than received block_no"); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _seq_no; + msgArgs[2] = ""+seq_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + + if (recv_seq_no > seq_no){ + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + +// HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); //결번이후에 수신된 데이터 보관.. +// if (block_data == null) { +// block_data = new HashMap(); +// } + + + @SuppressWarnings("unchecked") + HashMap miss_data = (HashMap) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장.. + if (miss_data == null) { + miss_data = new HashMap(); + } + + @SuppressWarnings("unchecked") + HashMap first_miss_field = (HashMap) hm.get(JobProcessData.PROCDATA_FIRST_MISS); //첫번째 결번 + @SuppressWarnings("unchecked") + HashMap last_miss_field = (HashMap) hm.get(JobProcessData.PROCDATA_LAST_MISS); //마지막 결번 위치 저장 + + int missCount = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + if (first_miss_field == null){ + first_miss_field = new HashMap(); + first_miss_field.put(JobProcessData.PROCDATA_FIRST_MISS, new Integer(seq_no+1)); + hm.put(JobProcessData.PROCDATA_FIRST_MISS, first_miss_field); + + for (int i=seq_no; i(); + last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i)); + hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field); + + missCount = missCount+1; + } + + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount); + + } else { //이전에 miss_field가 있으면 + for (int i=seq_no; i(); + last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i)); + hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field); + + missCount = missCount+1; + } + + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount); + } + } + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0430.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0430.java new file mode 100644 index 0000000..c135e1e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0430.java @@ -0,0 +1,193 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.util.HashMap; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_BI0430 extends DefaultTelegram implements TelegramService +{ + private int INFORMALFIELD_INDEX = 10; + private ByteArrayOutputStream bout; + /** + * 생성자 + */ + public RECV_BI0430() { + // 결번확인지시 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + + String _missing_count = new String ((byte[]) al_Field.get(9)); + String missing_field = bout.toString(); + al_Field.set(INFORMALFIELD_INDEX, missing_field.getBytes()); + + int recv_migging_count = Integer.parseInt(_missing_count); + + if (recv_migging_count == 0 ) { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) {//마지막 결번확인 부분은 로그로 남기지 않는다. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + //logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + setConditionTxt(TelegramKeys.ERROR); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + String byte_size = new String ((byte[]) al_Field.get(8)); // 최종 seqquence-no가 결번확인 길이임. + logger.info("{"+logHeader+"} the sum of definite field length [" + byte_size + "]"); + + try { + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + setConditionTxt(TelegramKeys.ERROR); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + setConditionTxt(TelegramKeys.ERROR); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + logger.debug("{"+logHeader+"} 결번 데이터 : [" + new String(data) + "]"); + bout.write(data, 0, length); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + setConditionTxt(TelegramKeys.ERROR); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0440.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0440.java new file mode 100644 index 0000000..d52b371 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0440.java @@ -0,0 +1,92 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BI0440 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public RECV_BI0440() { + //화일송신완료지시 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0450.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0450.java new file mode 100644 index 0000000..5ed2d79 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0450.java @@ -0,0 +1,112 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BI0450 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_BI0450() { + //화일송신완료보고 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + + String dirDelimiter = StringUtil.getDirDelimiter(strFullPathName); + strFullPathName = strFullPathName+dirDelimiter+fileName; + File rcvRealFile = null; + + try { + rcvRealFile = new File( strFullPathName ); + if (rcvRealFile.exists()) { + super.setFileHeaderAndTrailer(rcvRealFile); + } + } catch (Exception ex) { + batchDoc.getBatchMsg().getBody().setErrorMsg("해당경로에 파일이 존재하지 않습니다. - "+strFullPathName); + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR); //기타 에러 999 + return false; + } + LogUtil.setLogFileEnd(batchDoc); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0700.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0700.java new file mode 100644 index 0000000..bab0311 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0700.java @@ -0,0 +1,335 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.util.HashMap; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_BI0700 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + private int INFORMALFIELD_INDEX = 10; + private ByteArrayOutputStream bout; + private int recv_seq_no = 0; + private int seq_no = 0; + + private File f; + private FileOutputStream fout; + + public RECV_BI0700() { + //data 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _seq_no = new String ((byte[]) al_Field.get(8)); + recv_seq_no = Integer.parseInt(_seq_no); + + seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + //지금까지 수신한 시퀀스의 크기가 현재 받은 시퀀스의 크기보다 크면 Error + if ((recv_seq_no - seq_no) < 0 ){ + logger.debug("{"+logHeader+"} doExecute >> current seq_no is bigger than recived seq_no"); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _seq_no; + msgArgs[2] = ""+seq_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + + } + + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + this.setConditionTxt(TelegramKeys.ERROR); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); //결번이후에 수신된 데이터 보관.. + if (block_data == null) { + block_data = new HashMap(); + } + + + @SuppressWarnings("unchecked") + HashMap miss_data = (HashMap) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장.. + if (miss_data == null) { + miss_data = new HashMap(); + } + + @SuppressWarnings("unchecked") + HashMap first_miss_field = (HashMap) hm.get(JobProcessData.PROCDATA_FIRST_MISS); //첫번째 결번 + @SuppressWarnings("unchecked") + HashMap last_miss_field = (HashMap) hm.get(JobProcessData.PROCDATA_LAST_MISS); //마지막 결번 위치 저장 + + int missCount = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + if (first_miss_field == null){ + if ((recv_seq_no - seq_no)==1){ //순차적인 seq를 수신하면.. 파일에 write + if (!createFile()) { + return false; + } + fout.write(bout.toByteArray()); + + miss_data.put(new Integer(recv_seq_no-1), "1"); + hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data); + + }else { //결번이 발생한 경우이면 메모리에 저장. + first_miss_field = new HashMap(); + first_miss_field.put(JobProcessData.PROCDATA_FIRST_MISS, new Integer(seq_no+1)); + hm.put(JobProcessData.PROCDATA_FIRST_MISS, first_miss_field); + + last_miss_field = new HashMap(); + last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(seq_no+1)); + hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field); + + for (int i=seq_no+1; i= this.getFieldCount()) { + logger.debug("{"+logHeader+"} getCalculatedLength> parameter is bigger than field count"); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + this.setConditionTxt(TelegramKeys.ERROR); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + String byte_size = new String ((byte[]) al_Field.get(9)); //실 DATA Byte수 + logger.info("{"+logHeader+"} the sum of definite field length [" + byte_size + "]"); + + try { + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + this.setConditionTxt(TelegramKeys.ERROR); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + this.setConditionTxt(TelegramKeys.ERROR); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + + //전송상태처리 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + } else { + logger.debug("{"+logHeader+"} doInformalField >> index of informal action error : " + idx); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + this.setConditionTxt(TelegramKeys.ERROR); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex ); + this.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + + private boolean createFile () { + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{"+logHeader+"} getCalculatedLength >> File full-path [" + strFullPath + "]"); + f = new File(strFullPath); + fout = new FileOutputStream(f, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + this.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0710.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0710.java new file mode 100644 index 0000000..0c9180d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BI0710.java @@ -0,0 +1,316 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.lang.String; +import java.util.HashMap; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_BI0710 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + private int INFORMALFIELD_INDEX = 10; + private int recv_seq_no; + private ByteArrayOutputStream bout; + + private File f; + private FileOutputStream fout; + + public RECV_BI0710() { + //data 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _seq_no = new String ((byte[]) al_Field.get(8)); + recv_seq_no = Integer.parseInt(_seq_no); + + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + @SuppressWarnings("unchecked") + HashMap miss_data = (HashMap) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장.. + if (miss_data == null) { + miss_data = new HashMap(); + } + @SuppressWarnings("unchecked") + HashMap last_miss_field = (HashMap) hm.get(JobProcessData.PROCDATA_LAST_MISS); //마지막 결번 위치 저장 + @SuppressWarnings("unchecked") + HashMap first_miss_field = (HashMap) hm.get(JobProcessData.PROCDATA_FIRST_MISS); //첫번째 결번 + Integer firstMiss = (Integer) first_miss_field.get(JobProcessData.PROCDATA_FIRST_MISS); + + int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + logger.info("{"+logHeader+"} doPostExecute> RECV recv_seq_no [" + recv_seq_no + "] "); + byte[] _missing_field = new byte[miss_data.size()]; + for (int j = 0; j(); + last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i+1)); + hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field); + + for (int n = recv_seq_no; n> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + } + + logger.info("{} doPostExecute> RECV missing telegram [" + recv_seq_no + "] missing field - [" + new String(_missing_field), logHeader); + + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + + for (int i=0; i<8; i++) { //어음이미지 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (fout != null) { + fout.close(); + } + + return true; + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + }finally{ + try{ + if (fout != null) { + fout.close(); + } + }catch(Exception e){ + + } + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + String byte_size = new String ((byte[]) al_Field.get(9)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + + try { + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + + //전송상태처리 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + + private boolean createFile () { + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + f = new File(strFullPath); + fout = new FileOutputStream(f, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e ); + return false; + } + return true; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BILLIMG.java b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BILLIMG.java new file mode 100644 index 0000000..26cadb9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/RECV_BILLIMG.java @@ -0,0 +1,319 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_BILLIMG extends DefaultTelegram implements TelegramService +{ + private final int MAX_TCP_BYTES = 8232; //업무구분코드 이후의 송신할 전문길이의 최대값은 8232 BYTES이다. + + private Properties telegramInfo; + + /** + * 생성자 : 어음이미지 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_BILLIMG() { + } + + public boolean doValidation() + { + if (!super.doValidation()) return false; + + try { + int currFiledIndex = 0; + String currFieldValue = ""; + + //1. 어음이미지수신 전문의 전문필드 개수 체크 + logger.info("{} >>>>> 수신 전문의 전문필드 개수 Checking......", logHeader); + if (al_FieldProps == null || al_Field == null || al_FieldProps.length != al_Field.size()) { + String errMsg = "전문필드 값 Validation 체크를 위한 데이터 불량."; + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + + //2. 어음이미지수신 전문의 전체 전문필드 타입 체크 + logger.info("{} >>>>> 수신 전문의 전체 전문필드 타입 Checking......", logHeader); + for(int i=1; i>>>> TCP/IP 전문 송신 BYTE 수 Checking......", logHeader); + String tcpBytes = new String ((byte[]) al_Field.get(1)); + try{ + int bytes = Integer.parseInt(tcpBytes); + + if (bytes > MAX_TCP_BYTES){ + String errMsg = "TCPIP 전문 송신 BYTES는 8232 를 초과할 수 없습니다. - ["+bytes+"]"; + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_BYTE_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + + }catch (NumberFormatException ne){ + logger.error( ne.getMessage(), ne); + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_BYTE_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + + logger.info("{} >>>>> 업무구분코드 Checking......", logHeader); + currFiledIndex = 2; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(telegramInfo.getProperty(TelegramKeys.BIZ_GBN))) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR006", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, telegramInfo.getProperty(TelegramKeys.BIZ_GBN)}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 이 아닙니다. + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + + logger.info("{} >>>>> 거래구분코드 Checking......", logHeader); + currFiledIndex = 4; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!(currFieldValue.equals(TelegramKeys.BI_TR_CLASS_RECV) + || currFieldValue.equals(TelegramKeys.BI_TR_CLASS_SEND))) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR007", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, + TelegramKeys.BI_TR_CLASS_RECV, TelegramKeys.BI_TR_CLASS_SEND}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 값들 중 하나이어야 합니다. + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + + logger.info("{} >>>>> 송수신 FLAG Checking......", logHeader); + currFiledIndex = 5; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!(currFieldValue.equals(telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK)) + || currFieldValue.equals(telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER)))) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR007", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, + telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER)}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 값들 중 하나이어야 합니다. + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + + logger.info("{} >>>>> 응답코드 Checking......", logHeader); + currFiledIndex = 7; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!(currFieldValue.equals(TelegramKeys.BI_RES_CODE_SUCESS) || currFieldValue.equals(TelegramKeys.BI_RES_CODE_ALREADY_RECEIVED))) { + String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getBiImgRetDescription(currFieldValue); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); // + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + + + + }catch (Exception e){ + logger.error( e.getMessage(), e); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString()); + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=2; i= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + this.setConditionTxt(TelegramKeys.ERROR); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + this.setConditionTxt(TelegramKeys.ERROR); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + this.setConditionTxt(TelegramKeys.ERROR); + return -1; + } + } + + + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0200.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0200.java new file mode 100644 index 0000000..b8fde0c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0200.java @@ -0,0 +1,292 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0200 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BI0200() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, " ", this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //전문 전송 일시 (MMddhhmmss) + compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]); + //송신자명 (어음이미지시스템의 책임자 ID) + compileField(9, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[9]); + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + //compileField(10, batchDoc.getEAIBatchMessage().getHeader().getUserPassword(), this.al_FieldProps[10]); + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + //전송자명은 앞에서 8자리이며 8자리 미만은 Z로 채움.. + String passwd = EncryptManager.getInstance().getEncryptPwd((batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8), + (batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6), + telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3), + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(10, passwd, this.al_FieldProps[10]); + logger.debug("{} SEND_BI0200 ] PASSWD : "+passwd, logHeader); + }else{ + compileField(10, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[10]); + } + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0210.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0210.java new file mode 100644 index 0000000..08a4f21 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0210.java @@ -0,0 +1,333 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0210 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BI0210() { + //업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + +// if (CommonKeys.PROCESS_RESPONSE_SEND.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ +// // 응답송신 이면 +// String strPathName = BatchDirUtil.getResSendRealDir(); +// if ( strPathName.charAt(strPathName.length()-1) != '/' ) { +// strPathName = strPathName + '/'; +// } +// +// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(this.batchDoc.getBatchMsg().getHeader().getProcessCode(), this.batchDoc.getBatchMsg().getHeader().getInstitutionCode()); +// StringBuffer sb = new StringBuffer(); +// +// sb.append(btVO.getProcessCode()); +// sb.append("/"); +// sb.append(btVO.getOrganCode()); +// strPathName = strPathName + sb.toString(); +// Logging(INFO, "[응답송신] PATH NAME = [" + strPathName + "]"); +// +// File ff = new File(strPathName); +// if (!ff.exists()) { +// Logging(WARN, "응답송신용 디렉토리 [" + strPathName + "] 이 없습니다."); +// String[] msgArgs = new String [2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ff.getName(); +// String errCode = "BECEAIFJI022"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return false; +// } +// File[] fileList = ff.listFiles(); +// String strFileName = ""; +// this.setConditionTxt(TelegramKeys.NOFILE); +// if (fileList.length> 0) { +// for (int i1=0; i1= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0220.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0220.java new file mode 100644 index 0000000..ad9c913 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0220.java @@ -0,0 +1,293 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0220 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BI0220() { + //업무종료지시 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, " ", this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //전문 전송 일시 (MMddhhmmss) + compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]); + //송신자명 (어음이미지시스템의 책임자 ID) + compileField(9, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[9]); + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + //compileField(10, batchDoc.getEAIBatchMessage().getHeader().getUserPassword(), this.al_FieldProps[10]); + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + //전송자명은 앞에서 8자리이며 8자리 미만은 Z로 채움.. + String passwd = EncryptManager.getInstance().getEncryptPwd((batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8), + (batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6), + telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3), + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(10, passwd, this.al_FieldProps[10]); + logger.debug("{} SEND_BI0220 ] PASSWD : "+passwd, logHeader); + }else{ + compileField(10, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[10]); + } + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0230.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0230.java new file mode 100644 index 0000000..1b19ebd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0230.java @@ -0,0 +1,294 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0230 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BI0230() { + //업무종료보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, " ", this.al_FieldProps[6]); + //응답코드 + compileField(7, super.getSendResponseCode(), this.al_FieldProps[7]); + //전문 전송 일시 (MMddhhmmss) + compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]); + //송신자명 (어음이미지시스템의 책임자 ID) + compileField(9, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[9]); + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + //compileField(10, batchDoc.getEAIBatchMessage().getHeader().getUserPassword(), this.al_FieldProps[10]); + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + //전송자명은 앞에서 8자리이며 8자리 미만은 Z로 채움.. + String passwd = EncryptManager.getInstance().getEncryptPwd((batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8), + (batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6), + telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3), + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(10, passwd, this.al_FieldProps[10]); + logger.debug("{} SEND_BI0230 ] PASSWD : "+passwd, logHeader); + }else{ + compileField(10, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[10]); + } + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0400.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0400.java new file mode 100644 index 0000000..73e878b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0400.java @@ -0,0 +1,339 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0400 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private BufferedInputStream bis; + /** + * 생성자 + */ + public SEND_BI0400() { + //화일정보수신지시 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //화일 사이즈 + compileField(8, ""+calculateFileSize(), this.al_FieldProps[8]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private long calculateFileSize () { + createFile(); + long length = this.batchDoc.getBatchMsg().getHeader().getFileSize(); + if (length < 0) { + return 0; + } + + return length; + } + + private void createFile () + { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + + bis = new BufferedInputStream (new FileInputStream (file)); + if (bis == null){ + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] 을 읽기 위한 객체 생성에 실패했습니다.", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + //BatchOpenFileManager.getInstance().addFbr(batchDoc.getEAIBatchMessage().getHeader().getUUID() , fileName, fbr); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + this.batchDoc.getBatchMsg().getHeader().setFileSize(file.length()); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0410.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0410.java new file mode 100644 index 0000000..6d45362 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0410.java @@ -0,0 +1,282 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0410 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BI0410() { + //화일정보수신보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, super.getSendResponseCode(), this.al_FieldProps[7]); + //화일 사이즈 - RECV_BI0400에서 계산된 현재 화일 크기를 설정한다.. + compileField(8, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[8]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //수신 파일 Start DB로그 + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0420.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0420.java new file mode 100644 index 0000000..778d985 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0420.java @@ -0,0 +1,280 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0420 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BI0420() { + //결번확인지시 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //최종 SEQUENCE-NO + compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0430.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0430.java new file mode 100644 index 0000000..6196d66 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0430.java @@ -0,0 +1,416 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0430 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private File f; + private FileOutputStream fout; + + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BI0430() { + //결번확인지시 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //최종 SEQUENCE-NO + compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]); + //결번갯수 + compileField(9, ""+MISSING_COUNT, this.al_FieldProps[9]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + boolean result = calculateMissingCount(); + if (!result) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + + if (MISSING_COUNT==0 && fout != null) { + fout.close(); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< (this.al_Field.size()-1); i++) { //마지막은 비정형 필드이므로 제외 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + + REAL_SEND_LENGTH +=getCalculatedLength(0); //트랜잭션코드의 길이를 더함. + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + @SuppressWarnings("unchecked") + HashMap miss_data = (HashMap) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장.. + + @SuppressWarnings("unchecked") + HashMap last_miss_field = (HashMap)hm.get(JobProcessData.PROCDATA_LAST_MISS); + + MISSING_COUNT = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + if (seq_no==miss_data.size()){ + byte[] _missingNm = new byte[seq_no]; + + if (block_data == null ){//block_data는 결번이 발생할 경우에만 저장하므로, null이면 결번없음. + + for (int n = 0; n> File full-path [" + strFullPath + "]", logHeader); + f = new File(strFullPath); + fout = new FileOutputStream(f, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 10: + return MISSING_FIELD.length(); + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 10: + //mod by khs data = MISSING_FIELD.getBytes(); + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0440.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0440.java new file mode 100644 index 0000000..91d59e1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0440.java @@ -0,0 +1,278 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0440 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BI0440() { +// 화일송신완료지시 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //화일 사이즈 + compileField(8, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[8]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0450.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0450.java new file mode 100644 index 0000000..0bfe6f5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0450.java @@ -0,0 +1,347 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0450 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private File rcvRealFile = null; + + /** + * 생성자 + */ + public SEND_BI0450() { +// 화일송신완료보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, super.getSendResponseCode(), this.al_FieldProps[7]); + //화일 사이즈 + compileField(8, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[8]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + + String dirDelimiter = StringUtil.getDirDelimiter(strFullPathName); + strFullPathName = strFullPathName+dirDelimiter+fileName; + rcvRealFile = new File( strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + + try { + + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //DB로그에 남길 파일 사이즈 설정 + //batchDoc.getEAIBatchMessage().getHeader().setFileSize(rcvRealFile.length()); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + + //수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + File rcvRootFile = new File( StringUtil.realToRootDir(strFullPathName) ); + File rcvArchFile = new File( StringUtil.realToArchDir(strFullPathName) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(strFullPathName) ); + + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR); + return false; + } + + if ( !super.getResolveResponseCode().equals(TelegramKeys.BI_RES_CODE_SUCESS) ) { + //수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n] caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(방카슈랑스 서버에 자동 송신하도록 수신 File Event 발생)", logHeader); + + isSuccessMoveFile = rcvRootFile.createNewFile(); + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR);//기타 에러 999 + return false; + } + } + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR); //기타 에러 999 + return false; + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0700.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0700.java new file mode 100644 index 0000000..6c7f44c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0700.java @@ -0,0 +1,455 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0700 extends DefaultTelegram implements TelegramService +{ + + private BufferedInputStream bis; + private int SEQUENCE_NO; + + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BI0700() { + //data송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //SEQUENCE-NO + compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]); + //실 data byte수 + compileField(9, ""+REAL_BYTE, this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + case 10: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< (this.al_Field.size()-1); i++) { //마지막 필드는 비정형 필드이므로 제외 시킴. + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH = SEND_LENGTH + REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + break; + case 10: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE ; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + logger.debug("lnCurSize-->" + lnCurSize); + break; + default: + break; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + this.batchDoc.getBatchMsg().getHeader().getRecLen(); + + + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + +// for 결번 테스트 -- start +/* + if (SEQUENCE_NO==4 || SEQUENCE_NO==14 || SEQUENCE_NO==24){ +// for 결번 테스트 + //seq_no 4의 데이터 값 설정.. + int seq_size = this.batchDoc.getEAIBatchMessage().getHeader().getSequenceSize(); + StringBuffer seqBuffer = new StringBuffer(); + + long curLength = batchDoc.getEAIBatchMessage().getBody().getCurFileSize(); + long fileLength = batchDoc.getEAIBatchMessage().getHeader().getFileSize(); + + int readBufferSize = seq_size; + + if (seq_size > (fileLength - curLength) ){ + readBufferSize = (int)(fileLength - curLength); + } + fileData = new byte[readBufferSize]; + + + REAL_BYTE = bis.read(fileData); + + // 파일을 다 읽었으면... + if ( curLength + REAL_BYTE >= fileLength) { + this.setConditionTxt(TelegramKeys.EOF); + bis.close(); + BatchOpenFileManager.getInstance().removeBis(batchDoc.getEAIBatchMessage().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getEAIBatchMessage().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1) , fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + this.batchDoc.getEAIBatchMessage().getBody().setSeqNum(SEQUENCE_NO); + + long lnCurSize = batchDoc.getEAIBatchMessage().getBody().getCurFileSize() + REAL_BYTE ; + batchDoc.getEAIBatchMessage().getBody().setCurFileSize(lnCurSize); + + this.SEQUENCE_NO = this.batchDoc.getEAIBatchMessage().getBody().getSeqNum()+1; + this.setConditionTxt(""); + + }*/ +// for 결번 테스트 - end + int seq_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize(); +// StringBuffer seqBuffer = new StringBuffer(); + + long curLength = batchDoc.getBatchMsg().getBody().getCurFileSize(); + long fileLength = batchDoc.getBatchMsg().getHeader().getFileSize(); + + int readBufferSize = seq_size; + + if (seq_size > (fileLength - curLength) ){ + readBufferSize = (int)(fileLength - curLength); + } + fileData = new byte[readBufferSize]; + + + REAL_BYTE = bis.read(fileData); + + // 파일을 다 읽었으면... + if ( curLength + REAL_BYTE >= fileLength) { + this.setConditionTxt(TelegramKeys.EOF); + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1) , fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + private boolean createFile () + { + + try { + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if (bis == null){ + logger.warn("FILE정보가 NULL입니다."); + return false; + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0710.java b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0710.java new file mode 100644 index 0000000..0e47011 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/billimg/SEND_BI0710.java @@ -0,0 +1,360 @@ +package com.eactive.eai.batch.job.jobItem.billimg; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BI0710 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BI0710() { + //data송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + // TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET + //compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + compileField(4, this.getFldTrClass(), this.al_FieldProps[4]); + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + //응답코드 + compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + //SEQUENCE-NO + compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]); + //실 data byte수 + compileField(9, ""+REAL_BYTE, this.al_FieldProps[9]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + //return REAL_BYTE; + + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + case 10: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + return fieldLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< (this.al_Field.size()-1); i++) { //마지막 필드는 비정형 타입이라 제외 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=1; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH +=getCalculatedLength(0); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean setBlockAndSeqNO () + { + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug("{"+logHeader+"}"+" {"+ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")+"}"); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = block_data.get( new Integer(i) ); + fileData = new byte[data.length]; + System.arraycopy( data, 0, fileData, 0, data.length); + this.REAL_BYTE = data.length; + + break; + } + } + + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + case 10: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + default: + break; + } + + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + + // return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX.java b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX.java new file mode 100644 index 0000000..6dc34b5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX.java @@ -0,0 +1,67 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BOKEX extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 한은외환망 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_BOKEX() { + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + int llLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + llLength = ((byte[])this.al_Field.get(idx-1)).length; + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_seq_no = Integer.parseInt(_seq_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + + // 20060419 add by khs for 전송상태처리 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03000040.java b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03000040.java new file mode 100644 index 0000000..df85392 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03000040.java @@ -0,0 +1,81 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BOKEX_03000040 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_BOKEX_03000040() { + //파일 확인 요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03000050.java b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03000050.java new file mode 100644 index 0000000..8ce905d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03000050.java @@ -0,0 +1,81 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BOKEX_03000050 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_BOKEX_03000050() { + //파일 확인 요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100010.java b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100010.java new file mode 100644 index 0000000..5d94c0d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100010.java @@ -0,0 +1,87 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BOKEX_03100010 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKEX_03100010() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + String rtn_yn = new String ((byte[]) al_Field.get(10)); + if ( rtn_yn.equalsIgnoreCase("N")){ + this.setConditionTxt(TelegramKeys.NOFILE); + } + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100020.java b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100020.java new file mode 100644 index 0000000..dcfb50a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100020.java @@ -0,0 +1,84 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BOKEX_03100020 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKEX_03100020() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + //응답수신 파일 Start DB로그 + LogUtil.setLogFileStart(batchDoc); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100040.java b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100040.java new file mode 100644 index 0000000..b251dfb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/RECV_BOKEX_03100040.java @@ -0,0 +1,109 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.util.HashMap; +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BOKEX_03100040 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_BOKEX_03100040() { + //파일 확인 응답 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + String rtn_cd = new String ((byte[]) al_Field.get(9)); + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + if (rtn_cd.equals("00")) { + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() <= batchDoc.getBatchMsg().getBody().getCurFileSize()){ + this.setConditionTxt(TelegramKeys.EOF); + } + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + + } else { + // 이전에 송신한 최초 시퀀스 찾아 내어 시퀀스 번호 다시 세팅 + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + for ( int inx=0;inx -1 ) || ( renamedFileName.indexOf(".zip_")) > -1 ){ + compGb = "2"; + } + if ( renamedFileName.indexOf(".Z_") > -1 ){ + compGb = "1"; + } + compileField(++i, compGb, this.al_FieldProps[i]); + + //파일 전체 크기 + compileField(++i, ""+ calculateFileSize(), this.al_FieldProps[i]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private long calculateFileSize () { + +// long length = 0L; + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + try { + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } +// length = file.length(); + super.setFileHeaderAndTrailer(file); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } +// if (length < 0) { +// return 0; +// } +// this.batchDoc.getBatchMsg().getHeader().setFileSize(length); +// return length; + return this.batchDoc.getBatchMsg().getHeader().getFileSize(); + + } + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength(){ + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute(){ + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000030.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000030.java new file mode 100644 index 0000000..2b0e536 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000030.java @@ -0,0 +1,413 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileReader; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_03000030 extends DefaultTelegram implements TelegramService +{ + + private BufferedReader fbr ; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BOKEX_03000030() { + //파일 데이터 송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setData(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + if ( this.getConditionTxt().equals(TelegramKeys.BLOCKEND) ){ + compileField(++i, "N", this.al_FieldProps[i]); + }else { + compileField(++i, "Y", this.al_FieldProps[i]); + } + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //SEQUENCE-NO + compileField(++i, ""+SEQUENCE_NO, this.al_FieldProps[i]); + + //기송신 크기 + compileField(++i, ""+(batchDoc.getBatchMsg().getBody().getCurFileSize()- REAL_BYTE), this.al_FieldProps[i]); + + //실 DATA BYTE 수 + compileField(++i, ""+REAL_BYTE, this.al_FieldProps[i]); + + //<< XX를 제외한 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + //data = fileData; + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean createFile () + { + + fbr = BatchOpenFileManager.getInstance().getFbr(batchDoc.getBatchMsg().getHeader().getUUID() ); + + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( fbr == null) { + fbr = new BufferedReader(new FileReader(file)); + BatchOpenFileManager.getInstance().addFbr(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fbr); + } + + logger.info("{} File [" + file.getName() + "] Size =" + file.length(), logHeader); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean setData () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int sequence_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + this.SEQUENCE_NO = seq_no + 1; + + if (( this.SEQUENCE_NO % block_size) == 0 ) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 03000040전문으로 넘어가게 함 + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + if (batchDoc.getBatchMsg().getBody().getCurFileSize() + sequence_size >= batchDoc.getBatchMsg().getHeader().getFileSize()) { + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + + // 저장된 메모리 정보 참조 하기 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + fileData = block_data.get(new Integer(SEQUENCE_NO-1)); + + if ( fileData == null ){ + fileData = new byte[sequence_size]; + int offset = 0; + byte[] temp_buffer = batchDoc.getBatchMsg().getBody().getSendBuffer(); + if ( temp_buffer != null ){ + System.arraycopy(temp_buffer, 0, fileData, offset, temp_buffer.length); + offset = temp_buffer.length; + } + batchDoc.getBatchMsg().getBody().setSendBuffer(null); + while ( offset < sequence_size) { + String tempLine = fbr.readLine(); + if ( tempLine == null ) + break; + + temp_buffer = tempLine.getBytes(); + System.arraycopy(temp_buffer, 0, fileData, offset, Math.min(temp_buffer.length, sequence_size-offset)); + int remains_size = temp_buffer.length + offset - sequence_size; + offset += Math.min(temp_buffer.length, sequence_size-offset); + if ( sequence_size == offset ){ + byte [] remains = new byte[remains_size]; + System.arraycopy(temp_buffer, temp_buffer.length-remains_size, remains, 0, remains_size); + batchDoc.getBatchMsg().getBody().setSendBuffer(remains); + } + } + REAL_BYTE = offset; + block_data.put( new Integer(SEQUENCE_NO-1) , fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + // 전송 상태 처리 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + } else { + REAL_BYTE = fileData.length; + } + + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000040.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000040.java new file mode 100644 index 0000000..270c932 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000040.java @@ -0,0 +1,172 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_03000040 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKEX_03000040() { + //파일 확인 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "N", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //SEQUENCE-NO + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //기송신 크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000050.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000050.java new file mode 100644 index 0000000..f5f98f9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03000050.java @@ -0,0 +1,184 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_03000050 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKEX_03000050() { + //파일 종료 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "N", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //SEQUENCE-NO + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //기송신 크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + + //종료 일시 + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + BufferedReader fbr = BatchOpenFileManager.getInstance().getFbr(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fbr != null ){ + fbr.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100020.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100020.java new file mode 100644 index 0000000..6c0e330 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100020.java @@ -0,0 +1,201 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_03100020 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKEX_03100020() { + //파일 시작 응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "N", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //문서명 + compileField(++i, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[i]); + + //문서 버젼 + compileField(++i, batchDoc.getBatchMsg().getTelegramBody().substring(6,8), this.al_FieldProps[i]); + + //레코드 길이 + compileField(++i, "0001", this.al_FieldProps[i]); + + //압축사용여부 + compileField(++i, batchDoc.getBatchMsg().getTelegramBody().substring(12,13), this.al_FieldProps[i]); + + //파일전체크기 + compileField(++i, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[i]); + + //이어받기 사용여부 + compileField(++i, telegramInfo.getProperty(TelegramKeys.RESUME_YN), this.al_FieldProps[i]); + + //수신한 길이 + compileField(++i, "", this.al_FieldProps[i]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //응답수신 파일 Start DB로그 + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100040.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100040.java new file mode 100644 index 0000000..5af91b2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100040.java @@ -0,0 +1,283 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_03100040 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + private String RTN_CD; + + /** + * 생성자 + */ + public SEND_BOKEX_03100040() { + //결번확인통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = compareSeqNSize(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "N", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //결과 + compileField(++i, RTN_CD, this.al_FieldProps[i]); + + //시퀀스 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //수신크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if ( fout != null ){ + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean compareSeqNSize() { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + long cur_size = this.batchDoc.getBatchMsg().getBody().getCurFileSize(); + + // 이전 전문에서 저장한 전문 내용을 꺼내어 본다. 17 자리라고 가정 + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + int recv_seq_no = Integer.parseInt(recvTelegramBody.substring(0, 7)); + long recv_cur_size = Integer.parseInt(recvTelegramBody.substring(7,17)); + + if ( cur_size == recv_cur_size){ + if ( seq_no == recv_seq_no ){ + RTN_CD = "00"; + } else { + RTN_CD = "01"; + } + } else { + if ( seq_no == recv_seq_no ){ + RTN_CD = "10"; + } else { + RTN_CD = "11"; + } + } + + HashMap hm = JobProcessData.getInstance().getBatchStageData(uuid); + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug("{"+logHeader+"}"+" {"+ExceptionUtil.getErrorCode("RECIVED FILE DATA IS NULL")+"}"); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if (RTN_CD.equals("00")) { + if (!createFile()) { + return false; + } + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100050.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100050.java new file mode 100644 index 0000000..5d8ffa5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_03100050.java @@ -0,0 +1,282 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_03100050 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + private FileOutputStream fout; + private String RTN_CD; + + /** + * 생성자 + */ + public SEND_BOKEX_03100050() { + //파일 종료 응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = compareSeqNSize(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //결과 + compileField(++i, RTN_CD, this.al_FieldProps[i]); + + //시퀀스 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //수신크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + + //종료 일시 + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + //서버관리번호 + compileField(++i, "", this.al_FieldProps[i]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if ( fout != null ){ + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + batchDoc.getBatchMsg().getHeader().setBizCode(""); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean compareSeqNSize() { + try { + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + long cur_size = this.batchDoc.getBatchMsg().getBody().getCurFileSize(); + + // 이전 전문에서 저장한 전문 내용을 꺼내어 본다. 17 자리라고 가정 + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + int recv_seq_no = Integer.parseInt(recvTelegramBody.substring(0, 7)); + long recv_cur_size = Integer.parseInt(recvTelegramBody.substring(7,17)); + + if ( cur_size == recv_cur_size){ + if ( seq_no == recv_seq_no ){ + RTN_CD = "00"; + } else { + RTN_CD = "01"; + } + } else { + if ( seq_no == recv_seq_no ){ + RTN_CD = "10"; + } else { + RTN_CD = "11"; + } + } + + if (RTN_CD.equals("00")) { + // 수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if (rcvRealFile.exists()) { + // DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + // DB로그에 남길 파일 사이즈 설정 + //batchDoc.getEAIBatchMessage().getHeader().setFileSize(rcvRealFile.length()); + + // 수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("UNDEFINED_CD", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + + RTN_CD = "99"; + }else{ + rcvRootFile.createNewFile(); + } + + // DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + + // 수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI027"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_0600.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_0600.java new file mode 100644 index 0000000..b4c9f78 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_0600.java @@ -0,0 +1,227 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKEX_0600() { + //업무개시요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "N", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //전문 전송일시 YYYYMMDDHHMMSS + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + if (this.getFldOpCode().endsWith("4")){ + return true; + } + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(++i, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[i]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(++i, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[i]); + + //파일 확인 요구 간격 + compileField(++i, ""+batchDoc.getBatchMsg().getHeader().getBlockSize(), this.al_FieldProps[i]); + + //전송방법 + compileField(++i, telegramInfo.getProperty(TelegramKeys.DATA_FLAG), this.al_FieldProps[i]); + + //압축사용여부 + String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String compGb = "0"; + if ( ( renamedFileName.indexOf(".ZIP_") > -1 ) || ( renamedFileName.indexOf(".zip_")) > -1 ){ + compGb = "2"; + } + if ( renamedFileName.indexOf(".Z_") > -1 ){ + compGb = "1"; + } + compileField(++i, compGb, this.al_FieldProps[i]); + + //이어받기 사용여부 + compileField(++i, telegramInfo.getProperty(TelegramKeys.RESUME_YN), this.al_FieldProps[i]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + + String filename = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( filename.length() == 14){ // 스케쥴 관리 화면에서 기동 된 경우 + batchDoc.getBatchMsg().getHeader().setBaseDate( filename.substring(6)); + } else { + batchDoc.getBatchMsg().getHeader().setBaseDate( TelegramKeys.getYYYYMMDD() ); + } + try { + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE)) { + batchDoc.getBatchMsg().getHeader().setScheduleCode(" "); + batchDoc.getBatchMsg().getHeader().setBizCode(""); + batchDoc.getBatchMsg().getHeader().setFileName(""); + } + + } catch (Exception e) {} // 에러 시 무시 + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_0610.java b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_0610.java new file mode 100644 index 0000000..22aa080 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokex/SEND_BOKEX_0610.java @@ -0,0 +1,208 @@ +package com.eactive.eai.batch.job.jobItem.bokex; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKEX_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BOKEX_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //업무구분코드 - FXB + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "N", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //전문 전송일시 YYYYMMDDHHMMSS + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + if (this.getFldOpCode().endsWith("4")){ + return true; + } + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(++i, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[i]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(++i, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[i]); + + //파일 확인 요구 간격 + compileField(++i, ""+batchDoc.getBatchMsg().getHeader().getSequenceSize(), this.al_FieldProps[i]); + + //전송방법 + compileField(++i, telegramInfo.getProperty(TelegramKeys.DATA_FLAG), this.al_FieldProps[i]); + + //압축사용여부 + String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String compGb = "0"; + if ( ( renamedFileName.indexOf(".ZIP_") > -1 ) || ( renamedFileName.indexOf(".zip_")) > -1 ){ + compGb = "2"; + } + if ( renamedFileName.indexOf(".Z_") > -1 ){ + compGb = "1"; + } + compileField(++i, compGb, this.al_FieldProps[i]); + + //이어받기 사용여부 + compileField(++i, telegramInfo.getProperty(TelegramKeys.RESUME_YN), this.al_FieldProps[i]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(4); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG.java new file mode 100644 index 0000000..a30a01b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG.java @@ -0,0 +1,101 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +public class RECV_BOKGG extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 한국은행 국고망 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_BOKGG() { + } + + public boolean doValidation() + { + if (!super.doValidation()) return false; + + try { + logger.info("{} >>>>> 응답코드 Checking......", logHeader); + int currFiledIndex = 6; + String currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.BOKGG_RES_CODE_SUCESS)) { + String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getBokGGRetDescription(currFieldValue); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); // + super.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + }catch (Exception e){ + logger.error( e.getMessage(), e); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString()); + super.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(3).equalsIgnoreCase("0600") ||super.getFieldValueString(3).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(9); + } + else { + return super.getOpCode(); + } + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of recv data length [" + byte_size + "]", logHeader); + int tot_byte_size = Integer.parseInt(byte_size); + + int read_byte_size = 0; + + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + logger.info("{} he sum of definite field length [" + (tot_byte_size- read_byte_size) + "]", logHeader); + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0310.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0310.java new file mode 100644 index 0000000..cf7b657 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0310.java @@ -0,0 +1,239 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKGG_0310 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + + public RECV_BOKGG_0310() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); + //int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (((recv_block_no - block_no) > 1 ) || ((recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; + //missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + return false; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0320.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0320.java new file mode 100644 index 0000000..b0b1443 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0320.java @@ -0,0 +1,386 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKGG_0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; + + /** + * 생성자 + */ + public RECV_BOKGG_0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + String fName = new String ((byte[]) al_Field.get(4)); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (( recv_block_no != 9999 ) && ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + try { + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode); + batchDoc.getBatchMsg().getHeader().setRecLen((int)info.getFileRecSize()); + } catch (Exception e) { // 에러가 나도 아무것도 안함 + // do nothing + } + + long totRecCnt = 0; + try { + totRecCnt = Integer.parseInt(batchDoc.getBatchMsg().getFileHeader().substring(18, 25)); + } catch (Exception e) { + // do nothing + } + + batchDoc.getBatchMsg().getHeader().setFileSize ( (totRecCnt + 2 ) * batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().getHeader().setTotRecCnt( totRecCnt + 2 ); + + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ + // 강제 결번 세팅 +// } else if ((recv_block_no > 0) && ( recv_seq_no%30 != 5 ) ){ + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.KFB_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0330.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0330.java new file mode 100644 index 0000000..d16f68e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0330.java @@ -0,0 +1,144 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class RECV_BOKGG_0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKGG_0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(8).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + + } else if (super.getFieldValueString(8).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0600.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0600.java new file mode 100644 index 0000000..bc681b0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0600.java @@ -0,0 +1,173 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKGG_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_BOKGG_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setRecvUserID(super.getFieldValueString(10)); + batchDoc.getBatchMsg().getHeader().setRecvUserPassword(super.getFieldValueString(11)); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(4)); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0610.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0610.java new file mode 100644 index 0000000..64cef86 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0610.java @@ -0,0 +1,161 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKGG_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_BOKGG_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKJJ_RET_CODE_TEL_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0620.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0620.java new file mode 100644 index 0000000..e87fe84 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/RECV_BOKGG_0620.java @@ -0,0 +1,115 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKGG_0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKGG_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(9)); // 0 base 인덱스 + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0300.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0300.java new file mode 100644 index 0000000..03ccc81 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0300.java @@ -0,0 +1,389 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKGG_0300 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_BOKGG_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 지로코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘C' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, "" + batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, "" + this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[9]); + + //결번갯수 + compileField(10, "" + MISSING_COUNT, this.al_FieldProps[10]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return MISSING_FIELD.length(); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0310.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0310.java new file mode 100644 index 0000000..c65ff68 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0310.java @@ -0,0 +1,328 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKGG_0310 extends DefaultTelegram implements TelegramService { + + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BOKGG_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 지로코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+SEQUENCE_NO , this.al_FieldProps[9]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug("{"+logHeader+"}"+" {"+ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")+"}"); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0320.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0320.java new file mode 100644 index 0000000..467f900 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0320.java @@ -0,0 +1,459 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_BOKGG_0320 extends DefaultTelegram implements TelegramService { + + private FileInputStream fin; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BOKGG_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 지로코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num == 0 || block_num == 9999) { + recCnt = 1; + } + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + if ( block_num > 0 && block_num < 9999) { + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num == 0 || block_num == 9999) { + lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + batchDoc.getBatchMsg().getHeader().getRecLen(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (fin != null ) { + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean createFile () + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int BLOCK_NO = 0; + int SEQUENCE_NO = 0; + int sequence_size = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + + this.setConditionTxt(""); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[33]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + fileData = new byte[25]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + BLOCK_NO = block_no+1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( sequence_size / recLen ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / recLen; + + if ( seqCnt < remainCnt - 1){ + REAL_BYTE = seqCnt * recLen; + }else{ + REAL_BYTE = (int)(remainCnt - 1) * recLen; + } + int readCnt = REAL_BYTE / recLen; + if ( remainCnt - readCnt <= 1 ) { + this.setConditionTxt(TelegramKeys.EOF); + } + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + REAL_BYTE = fileData.length; + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0330.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0330.java new file mode 100644 index 0000000..f14728c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0330.java @@ -0,0 +1,293 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKGG_0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKGG_0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + recvTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + + REAL_BYTE = recvTelegramBody.getBytes().length - 11; + + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 지로코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, recvTelegramBody.substring(1,5), this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, recvTelegramBody.substring(5,8), this.al_FieldProps[9]); + + //Record 수 + compileField(10, recvTelegramBody.substring(8,11), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(8)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ batchDoc.getBatchMsg().getHeader().getRecLen(); + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + } else if ( recv_block_no == 9999 ) { + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + System.arraycopy(recvTelegramBody.getBytes(), 11, data, 0, REAL_BYTE ); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0600.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0600.java new file mode 100644 index 0000000..eec190b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0600.java @@ -0,0 +1,312 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKGG_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + //private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //개별업무 종료 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKGG_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + if ( OpCode_start.equals(getFldOpCode()) ) { + if (!setIdPass()) return false; + } + + //전문송신 Byte 수 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 지로코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, TelegramKeys.BOKGG_RES_CODE_SUCESS, this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //전문 전송일시 YYYYMMDDHHMMSS 기관에서 수신 시간 이후에 미수신자료를 수신코자 할 때는 전송일자와 상수(YYYYMMDD999999)를 SET한다. + compileField(8, TelegramKeys.getYYYYMMddHHmmss().substring(0,12), this.al_FieldProps[8]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(10, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[10]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(11, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[11]); + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size() - 1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += this.getCalculatedLength(this.al_Field.size() - 1); + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < 8) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + String summary = "01" + batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( summary.getBytes(), 0, data, 0, 8); + return 8; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + else return 8; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setIdPass(){ + try { + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String instiCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + String userID = hdrInfo.substring(38,58); + String passWord = hdrInfo.substring(58,66); + batchDoc.getBatchMsg().getHeader().setUserID(userID); + batchDoc.getBatchMsg().getHeader().setUserPassword(passWord); + try { + OutsideManager.getInstance().updateOsdIdPassword(procCode, instiCode, userID, passWord); + } catch (Exception e) { + logger.warn("ID와 비밀번호 수정 실패"); + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0610.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0610.java new file mode 100644 index 0000000..f6351e0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0610.java @@ -0,0 +1,288 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKGG_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + private final String OpCode_all_end = "004"; //개별업무 종료 + + /** + * 생성자 + */ + public SEND_BOKGG_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 지로코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //전문 전송일시 YYYYMMDDHHMMSS 기관에서 수신 시간 이후에 미수신자료를 수신코자 할 때는 전송일자와 상수(YYYYMMDD999999)를 SET한다. + compileField(8, TelegramKeys.getYYYYMMddHHmmss().substring(0,12), this.al_FieldProps[8]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(10, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[10]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(11, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[11]); + + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < 8) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + + String summary = "01" + batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( summary.getBytes(), 0, data, 0, 8); + return 8; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += this.getCalculatedLength(this.al_Field.size() - 1); + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + else return 8; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0620.java b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0620.java new file mode 100644 index 0000000..9e3bdeb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokgg/SEND_BOKGG_0620.java @@ -0,0 +1,184 @@ +package com.eactive.eai.batch.job.jobItem.bokgg; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKGG_0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKGG_0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 지로코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ.java new file mode 100644 index 0000000..32c1bb1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ.java @@ -0,0 +1,75 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_BOKJJ extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 신한은망 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_BOKJJ() { + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(3).equalsIgnoreCase("0600") ||super.getFieldValueString(3).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(9); + } + else { + return super.getOpCode(); + } + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of recv data length [" + byte_size + "]", logHeader); + int tot_byte_size = Integer.parseInt(byte_size); + + int read_byte_size = 0; + + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + logger.info("{} he sum of definite field length [" + (tot_byte_size- read_byte_size) + "]", logHeader); + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0310.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0310.java new file mode 100644 index 0000000..74fdfd4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0310.java @@ -0,0 +1,239 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKJJ_0310 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + + public RECV_BOKJJ_0310() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (((recv_block_no - block_no) > 1 ) || ((recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + return false; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0320.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0320.java new file mode 100644 index 0000000..ab0fa77 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0320.java @@ -0,0 +1,384 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKJJ_0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; + + /** + * 생성자 + */ + public RECV_BOKJJ_0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + String fName = new String ((byte[]) al_Field.get(4)); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (( recv_block_no != 9999 ) && ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + try { + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode); + batchDoc.getBatchMsg().getHeader().setRecLen((int)info.getFileRecSize()); + } catch (Exception e) { // 에러가 나도 아무것도 안함 + // do nothing + } + + long totRecCnt = 0; + try { + totRecCnt = Integer.parseInt(batchDoc.getBatchMsg().getFileHeader().substring(19, 26)); + } catch (Exception e) { + // do nothing + } + + batchDoc.getBatchMsg().getHeader().setFileSize ( (totRecCnt + 2 ) * batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().getHeader().setTotRecCnt( totRecCnt + 2 ); + + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.BOKJJ_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0330.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0330.java new file mode 100644 index 0000000..c82692e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0330.java @@ -0,0 +1,190 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class RECV_BOKJJ_0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKJJ_0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(8).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + + } else if (super.getFieldValueString(8).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + if ( checkMoreFile() ) { + this.setConditionTxt(""); + } else { + this.setConditionTxt(TelegramKeys.NOFILE); + } + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + private boolean checkMoreFile(){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return false; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + String hdrInfoName = info.getHdrInfoName(); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt()); + + } catch ( Exception e){ + return false; + + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0600.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0600.java new file mode 100644 index 0000000..5ad3517 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0600.java @@ -0,0 +1,122 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKJJ_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_BOKJJ_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKJJ_RET_CODE_TEL_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(4)); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0610.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0610.java new file mode 100644 index 0000000..3e52671 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0610.java @@ -0,0 +1,118 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKJJ_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_BOKJJ_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKJJ_RET_CODE_TEL_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0620.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0620.java new file mode 100644 index 0000000..02bdf9f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/RECV_BOKJJ_0620.java @@ -0,0 +1,115 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKJJ_0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKJJ_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(9)); // 0 base 인덱스 + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0300.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0300.java new file mode 100644 index 0000000..04695cd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0300.java @@ -0,0 +1,392 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKJJ_0300 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_BOKJJ_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : 공통부 중 1 ~ 6번 길이(21)와 개별부 길이의 합 (전체 전문 길이 ? 5 ) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 『기본설계서(온라인)』 <별첨3> 참조 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : 한국은행 송신, O : 참가기관 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (한국은행 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 한국은행) + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, "" + batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, "" + this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[9]); + + //결번갯수 + compileField(10, "" + MISSING_COUNT, this.al_FieldProps[10]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return MISSING_FIELD.length(); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0310.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0310.java new file mode 100644 index 0000000..9f46249 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0310.java @@ -0,0 +1,331 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKJJ_0310 extends DefaultTelegram implements TelegramService { + + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BOKJJ_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : 공통부 중 1 ~ 6번 길이(21)와 개별부 길이의 합 (전체 전문 길이 ? 5 ) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 『기본설계서(온라인)』 <별첨3> 참조 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : 한국은행 송신, O : 참가기관 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (한국은행 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 한국은행) + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+SEQUENCE_NO , this.al_FieldProps[9]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug("{"+logHeader+"} {"+ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")+"}"); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0320.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0320.java new file mode 100644 index 0000000..fb261ea --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0320.java @@ -0,0 +1,490 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_BOKJJ_0320 extends DefaultTelegram implements TelegramService { + + private FileInputStream fin; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BOKJJ_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : 공통부 중 1 ~ 6번 길이(21)와 개별부 길이의 합 (전체 전문 길이 ? 5 ) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 『기본설계서(온라인)』 <별첨3> 참조 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : 한국은행 송신, O : 참가기관 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (한국은행 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 한국은행) + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + if ( !this.getFldOpCode().equals("999") ){ + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + }else{ + compileField(8, "9999", this.al_FieldProps[8]); + } + + //Sequence-NO + if ( !this.getFldOpCode().equals("999") ){ + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + }else{ + compileField(9, "999", this.al_FieldProps[9]); + } + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num > 0 && block_num < 9999) { + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + Thread.sleep(TelegramKeys.BOKJJ_DELAY_MILISEC); + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (fin != null ) { + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean createFile () + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int BLOCK_NO = 0; + int SEQUENCE_NO = 0; + int sequence_size = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + + this.setConditionTxt(""); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[recLen]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + fileData = new byte[recLen]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + + // 전송내역 추가 + String sendSum = batchDoc.getBatchMsg().getBody().getSendSummary(); + if (sendSum == null ){ + sendSum = "01" + + batchDoc.getBatchMsg().getHeader().getBizCode().substring(4,6) + + makeZero( "" + ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() - 2 ), 7 ) ; + } else { + int sendedFileCnt = Integer.parseInt(sendSum.substring(0,2)); + sendSum = makeZero( "" + ( sendedFileCnt + 1), 2 ) + + sendSum.substring(2, 2 + 9*sendedFileCnt) + + batchDoc.getBatchMsg().getHeader().getBizCode().substring(4,6) + + makeZero( "" + ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() - 2 ), 7 ) ; + } + batchDoc.getBatchMsg().getBody().setSendSummary(sendSum); + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + BLOCK_NO = block_no+1; + SEQUENCE_NO = 1; + setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( sequence_size / recLen ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / recLen; + + if ( seqCnt < remainCnt - 1){ + REAL_BYTE = seqCnt * recLen; + }else{ + REAL_BYTE = (int)(remainCnt - 1) * recLen; + } + int readCnt = REAL_BYTE / recLen; + if ( remainCnt - readCnt <= 1 ) { + this.setConditionTxt(TelegramKeys.EOF); + } + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + // 이후 0600 전문 송신시에는 최종 block, seq를 보내 줘야 하기 때문에 헤더트레일러인 경우는 다음을 셋하지 않는다. + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + } + + REAL_BYTE = fileData.length; + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0330.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0330.java new file mode 100644 index 0000000..fa24433 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0330.java @@ -0,0 +1,291 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKJJ_0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKJJ_0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + recvTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + + REAL_BYTE = recvTelegramBody.getBytes().length - 11; + + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : 공통부 중 1 ~ 6번 길이(21)와 개별부 길이의 합 (전체 전문 길이 ? 5 ) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 『기본설계서(온라인)』 <별첨3> 참조 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : 한국은행 송신, O : 참가기관 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (한국은행 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 한국은행) + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, recvTelegramBody.substring(1,5), this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, recvTelegramBody.substring(5,8), this.al_FieldProps[9]); + + //Record 수 + compileField(10, recvTelegramBody.substring(8,11), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(8)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + } else if ( recv_block_no == 9999 ) { + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + System.arraycopy(recvTelegramBody.getBytes(), 11, data, 0, REAL_BYTE ); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0600.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0600.java new file mode 100644 index 0000000..b36bdf0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0600.java @@ -0,0 +1,281 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKJJ_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //개별업무 종료 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKJJ_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + if ( this.getFldOpCode().equals("001") ){ + try { + long sleepTime = Long.parseLong(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.debug(e.getMessage(), e); + } + } + + if ( OpCode_start.equals(getFldOpCode()) || OpCode_resume.equals(getFldOpCode())) { + this.batchDoc.getBatchMsg().getBody().setBlockNum(0); + this.batchDoc.getBatchMsg().getBody().setSeqNum(0); + if (!setIdPass()) return false; + } + + //전문송신 Byte 수 : 공통부 중 1 ~ 6번 길이(21)와 개별부 길이의 합 (전체 전문 길이 - 5 ) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 『기본설계서(온라인)』 <별첨3> 참조 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : 한국은행 송신, O : 참가기관 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (한국은행 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 한국은행) + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + + //전문 전송일시 YYYYMMDDHHMMSS 기관에서 수신 시간 이후에 미수신자료를 수신코자 할 때는 전송일자와 상수(YYYYMMDD999999)를 SET한다. + // 파일의 기준일자가 당일인지 체크한다. + String baseDate = batchDoc.getBatchMsg().getHeader().getBaseDate(); + + if ( !baseDate.equals(TelegramKeys.getYYYYMMDD())) { + compileField(8, baseDate + "9999999", this.al_FieldProps[8]); + } else { + compileField(8, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[8]); + } + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //Block-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[10]); + + //Sequence-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[11]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(12, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[12]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(13, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[13]); + + //송신 집계 내역 + if ( OpCode_unit_end.equals(getFldOpCode())) { + compileField(14, batchDoc.getBatchMsg().getBody().getSendSummary(), this.al_FieldProps[14]); + }else if ( OpCode_all_end.equals(getFldOpCode())){ + compileField(14, calculateSendSum(), this.al_FieldProps[14]); + }else{ + compileField(14, "", this.al_FieldProps[14]); + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + private String calculateSendSum(){ + String sendSum = ""; + try { +// String prevSum = batchDoc.getEAIBatchMessage().getBody().getSendSummary(); + // 0701 0006180 03 0000002 02 0000001 04 0000001 06 0000001 05 000002 00 70000001 + // 4 13 22 31 40 49 56 +// int fileNum = Integer.parseInt( prevSum.substring(0,2)); +// long sendCnt = 0; +// for ( int inx=0; inx 참조 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : 한국은행 송신, O : 참가기관 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (한국은행 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 한국은행) + compileField(7, recvTelegramBody.substring(0,1), this.al_FieldProps[7]); + + + //전문 전송일시 YYYYMMDDHHMMSS 기관에서 수신 시간 이후에 미수신자료를 수신코자 할 때는 전송일자와 상수(YYYYMMDD999999)를 SET한다. + compileField(8, recvTelegramBody.substring(1,15), this.al_FieldProps[8]); + + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, recvTelegramBody.substring(15,18), this.al_FieldProps[9]); + + //Block-NO + compileField(10, recvTelegramBody.substring(18,22), this.al_FieldProps[10]); + + //Sequence-NO + compileField(11, recvTelegramBody.substring(22,25), this.al_FieldProps[11]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(12, recvTelegramBody.substring(25,41), this.al_FieldProps[12]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(13, recvTelegramBody.substring(41,57), this.al_FieldProps[13]); + + //송신 집계 내역 + compileField(14, recvTelegramBody.substring(57,57+128), this.al_FieldProps[13]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0620.java b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0620.java new file mode 100644 index 0000000..308b0a6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokjj/SEND_BOKJJ_0620.java @@ -0,0 +1,186 @@ +package com.eactive.eai.batch.job.jobItem.bokjj; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKJJ_0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKJJ_0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : 공통부 중 1 ~ 6번 길이(21)와 개별부 길이의 합 (전체 전문 길이 ? 5 ) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 - 『기본설계서(온라인)』 <별첨3> 참조 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : 한국은행 송신, O : 참가기관 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (한국은행 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 한국은행) + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { //신한은망 전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG.java new file mode 100644 index 0000000..55c6815 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG.java @@ -0,0 +1,104 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKNG extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 한국은행 국고망 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_BOKNG() { + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + try { + logger.info("{} >>>>> 응답코드 Checking......", logHeader); + int currFiledIndex = 6; + String currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.BOKGG_RES_CODE_SUCESS)) { + String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getBokGGRetDescription(currFieldValue); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); // + super.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + }catch (Exception e){ + logger.error( e.getMessage(), e); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString()); + super.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(3).equalsIgnoreCase("0600") ||super.getFieldValueString(3).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(9); + } + else { + return super.getOpCode(); + } + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i> 업무관리정보 + private final String TrCodeHandShake1 = "0001"; //세션키 교환 요구 (전문번호 : X0001) + private final String TrCodeHandShake2 = "0002"; //세션키 교환 통보 (전문번호 : X0002) + private final String TrCodeHandShake3 = "0003"; //세션키 교환 통보 응답 (전문번호 : X0003) + private final String TrCodeHandShake4 = "0004"; //세션키 교환 확인 통보 (전문번호 : X0004) + private final String TrCodeHandShake5 = "0005"; //세션키 교환 확인 통보 응답 (전문번호 : X0005) + private final int INFORMALFIELD_INDEX = 8; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_BOKNG_0001() { + // + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //받은 h/s 데이터 처리 + byte[] handShakeData = new byte[bout.toByteArray().length]; + System.arraycopy(bout.toByteArray(), 0, handShakeData, 0, handShakeData.length); + batchDoc.getBatchMsg().getBody().setSendBuffer(handShakeData); + + + //업무관리정보 유효성 확인 + if (this.getTelegramType().equalsIgnoreCase(this.TrCodeHandShake1)) { + } + else if(this.getTelegramType().equalsIgnoreCase(this.TrCodeHandShake2)) { + } + else if(this.getTelegramType().equalsIgnoreCase(this.TrCodeHandShake3)) { + } + else if(this.getTelegramType().equalsIgnoreCase(this.TrCodeHandShake4)) { + } + else if(this.getTelegramType().equalsIgnoreCase(this.TrCodeHandShake5)) { + + int result = IniSafeManager.getInstance().finalHandShake(batchDoc, handShakeData); + if ( result != 1 ){ + logger.info("{} 3WAY HandShake Failed >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } + else { + logger.info("{} 0000 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(idx-1)); + // 길이부(4) 제거 + return Integer.parseInt(byte_size) - 4; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0300.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0300.java new file mode 100644 index 0000000..d3e4840 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0300.java @@ -0,0 +1,197 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKNG_0300 extends DefaultTelegram implements TelegramService { + + private int INFORMALFIELD_INDEX = 11; + + /** + * 생성자 + */ + public RECV_BOKNG_0300() { + //결번확인통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _missing_count = new String ((byte[]) al_Field.get(10)); + String missing_field = new String ((byte[]) al_Field.get(11)); + + int recv_migging_count = Integer.parseInt(_missing_count); + + if (recv_migging_count == 0 ) { +// checkFileEOF(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of recv data length [" + byte_size + "]", logHeader); + int tot_byte_size = Integer.parseInt(byte_size); + + int read_byte_size = 0; + + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + logger.info("{} he sum of definite field length [" + (tot_byte_size- read_byte_size) + "]", logHeader); + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0310.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0310.java new file mode 100644 index 0000000..affec4d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0310.java @@ -0,0 +1,248 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +public class RECV_BOKNG_0310 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + + public RECV_BOKNG_0310() { + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (((recv_block_no - block_no) > 1 ) || ((recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; + missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + return false; + + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + byte[] dec = new byte[bout.toByteArray().length]; + byte[] enc = new byte[bout.toByteArray().length-3]; + System.arraycopy(bout.toByteArray(), 0, dec, 0, 3); + System.arraycopy(bout.toByteArray(), 3, enc, 0, enc.length); + System.arraycopy(IniSafeManager.getInstance().dec(batchDoc,enc), 0, dec, 3, enc.length); + + block_data.put( new Integer(recv_seq_no-1) , dec); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0320.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0320.java new file mode 100644 index 0000000..86dc861 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0320.java @@ -0,0 +1,393 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +public class RECV_BOKNG_0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; +// private boolean isFirstFlag = true; + + /** + * 생성자 + */ + public RECV_BOKNG_0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + String fName = new String ((byte[]) al_Field.get(4)); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (( recv_block_no != 9999 ) && ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + byte[] dec = new byte[bout.toByteArray().length]; + byte[] enc = new byte[bout.toByteArray().length]; + if ( recv_block_no > 0 && recv_block_no < 9999 ){ + System.arraycopy(bout.toByteArray(), 0, enc, 0, enc.length); + System.arraycopy(IniSafeManager.getInstance().dec(batchDoc,enc), 0, dec, 0, enc.length); + } + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + try { + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode); + batchDoc.getBatchMsg().getHeader().setRecLen((int)info.getFileRecSize()); + } catch (Exception e) { // 에러가 나도 아무것도 안함 + // do nothing + } + + long totRecCnt = 0; + try { + totRecCnt = Integer.parseInt(batchDoc.getBatchMsg().getFileHeader().substring(19, 26)); + } catch (Exception e) { + // do nothing + } + + batchDoc.getBatchMsg().getHeader().setFileSize ( (totRecCnt + 2 ) * batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().getHeader().setTotRecCnt( totRecCnt + 2 ); + + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , dec); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.KFB_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0330.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0330.java new file mode 100644 index 0000000..f7a73f2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0330.java @@ -0,0 +1,142 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.LogUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKNG_0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKNG_0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(8).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + + } else if (super.getFieldValueString(8).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0600.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0600.java new file mode 100644 index 0000000..60c9424 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0600.java @@ -0,0 +1,184 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +public class RECV_BOKNG_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_BOKNG_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + byte[] byteUser = al_Field.get(10); + byte[] bytePass = al_Field.get(11); + byte[] enc = new byte[byteUser.length + bytePass.length]; + System.arraycopy(byteUser, 0, enc, 0, byteUser.length); + System.arraycopy(bytePass, 0, enc, byteUser.length, bytePass.length); + byte[] dec = IniSafeManager.getInstance().dec(batchDoc,enc); + byte[] decUser = new byte[byteUser.length]; + byte[] decPass = new byte[bytePass.length]; + System.arraycopy(dec, 0, decUser, 0, byteUser.length); + System.arraycopy(dec, byteUser.length, decPass, 0, bytePass.length); + batchDoc.getBatchMsg().getHeader().setRecvUserID(new String(decUser)); + batchDoc.getBatchMsg().getHeader().setRecvUserPassword(new String(decPass)); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(4)); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0610.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0610.java new file mode 100644 index 0000000..79d607d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0610.java @@ -0,0 +1,164 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKNG_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_BOKNG_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKJJ_RET_CODE_TEL_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0620.java b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0620.java new file mode 100644 index 0000000..055d390 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/RECV_BOKNG_0620.java @@ -0,0 +1,126 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_BOKNG_0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_BOKNG_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(9)); // 0 base 인덱스 + + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ +/* public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } +*/ + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0001.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0001.java new file mode 100644 index 0000000..edd4dd9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0001.java @@ -0,0 +1,298 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +public class SEND_BOKNG_0001 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private byte[] MSG = null; + + private final String TrCodeHandShake1 = "0001"; //세션키 교환 요구 (전문번호 : X0001) + private final String TrCodeHandShake2 = "0002"; //세션키 교환 통보 (전문번호 : X0002) + private final String TrCodeHandShake3 = "0003"; //세션키 교환 통보 응답 (전문번호 : X0003) + private final String TrCodeHandShake4 = "0004"; //세션키 교환 확인 통보 (전문번호 : X0004) + private final String TrCodeHandShake5 = "0005"; //세션키 교환 확인 통보 응답 (전문번호 : X0005) + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKNG_0001() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = prepareByteMsg(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //전문 발생 (송신) 주체, 참가기관 발생: 'B', 한국은행 발생: 'C' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //전문처리결과, 정상: '000', 오류: 'A. 응답코드' 참조 + compileField(6, TelegramKeys.BOKGG_RES_CODE_SUCESS, this.al_FieldProps[6]); + // 여기 까지 공통부 + + //개별부의 전체길이 + // 개별데이터부 + 4 + compileField(7, Integer.toString(MSG.length + 4) , this.al_FieldProps[7]); + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return MSG.length; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + System.arraycopy( MSG, 0, data, 0, MSG.length); + + this.al_Field.set( idx, MSG); + + return MSG.length; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + private boolean prepareByteMsg(){ + logger.debug("this.getFldTelegramType()-->" + this.getFldTelegramType()); + if ( this.getFldTelegramType().equals(TrCodeHandShake1)){ + MSG = IniSafeManager.getInstance().initHandShakeClient(this.batchDoc); + }else if ( this.getFldTelegramType().equals(TrCodeHandShake2)){ + MSG = IniSafeManager.getInstance().initHandShake(this.batchDoc); + }else if ( this.getFldTelegramType().equals(TrCodeHandShake3)){ + MSG = IniSafeManager.getInstance().updateHandShakeClient(this.batchDoc); + }else if ( this.getFldTelegramType().equals(TrCodeHandShake4)){ + MSG = IniSafeManager.getInstance().updateHandShake(this.batchDoc); + }else if ( this.getFldTelegramType().equals(TrCodeHandShake5)){ + MSG = IniSafeManager.getInstance().finalHandShakeClient(this.batchDoc); + } + + logger.debug("MSG-->" + CommonLib.getDumpMessage(MSG)); + if ( MSG == null ) + return false; + + return true; + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size() - 1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += this.getCalculatedLength(this.al_Field.size() - 1); + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0300.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0300.java new file mode 100644 index 0000000..a3bb529 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0300.java @@ -0,0 +1,393 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKNG_0300 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_BOKNG_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //전문 발생 (송신) 주체, 참가기관 발생: 'B', 한국은행 발생: 'C' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //전문처리결과, 정상: '000', 오류: 'A. 응답코드' 참조 + compileField(6, TelegramKeys.BOKGG_RES_CODE_SUCESS, this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, "" + batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, "" + this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[9]); + + //결번갯수 + compileField(10, "" + MISSING_COUNT, this.al_FieldProps[10]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return MISSING_FIELD.length(); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0310.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0310.java new file mode 100644 index 0000000..2e082be --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0310.java @@ -0,0 +1,344 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +public class SEND_BOKNG_0310 extends DefaultTelegram implements TelegramService { + +// private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BOKNG_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //전문 발생 (송신) 주체, 참가기관 발생: 'B', 한국은행 발생: 'C' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //전문처리결과, 정상: '000', 오류: 'A. 응답코드' 참조 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+SEQUENCE_NO , this.al_FieldProps[9]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + byte[] encData = IniSafeManager.getInstance().enc(batchDoc,fileData); + ByteArrayInputStream bin = new ByteArrayInputStream(encData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + +// int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + +// this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug( logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0320.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0320.java new file mode 100644 index 0000000..6a8344d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0320.java @@ -0,0 +1,488 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; +import java.io.File; + + +public class SEND_BOKNG_0320 extends DefaultTelegram implements TelegramService { + + private FileInputStream fin; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int REC_CNT; + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_BOKNG_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num == 0 || block_num == 9999) { + recCnt = 1; + } + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + if ( block_num > 0 && block_num < 9999) { + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num > 0 && block_num < 9999) { + byte[] encData = IniSafeManager.getInstance().enc(batchDoc,fileData); + logger.debug("encData-->" + CommonLib.getDumpMessage(encData)); + ByteArrayInputStream bin = new ByteArrayInputStream(encData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + }else{ + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + } + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (fin != null ) { + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + boolean result = false; + + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + //20240612 + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + result = true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + } + + return result; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + + private boolean createFile () + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int BLOCK_NO = 0; + int SEQUENCE_NO = 0; + int sequence_size = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + + this.setConditionTxt(""); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[34]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + fileData = new byte[26]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + BLOCK_NO = block_no+1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( sequence_size / recLen ); + // 남은 바이트 수 + + long totalDataLen = batchDoc.getBatchMsg().getHeader().getRecLen() * (batchDoc.getBatchMsg().getHeader().getTotRecCnt() - 2); + long remainSize = totalDataLen - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / recLen; + + if ( seqCnt < remainCnt){ + REAL_BYTE = seqCnt * recLen; + }else{ + REAL_BYTE = (int)(remainCnt) * recLen; + } + int readCnt = REAL_BYTE / recLen; + if ( remainCnt - readCnt < 1 ) { + this.setConditionTxt(TelegramKeys.EOF); + } + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + REAL_BYTE = fileData.length; + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + logger.debug("i-->(" + i + "),SEND_LENGTH-->" + SEND_LENGTH); + + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + logger.debug("SEND_LENGTH-->(" + SEND_LENGTH + "),REAL_SEND_LENGTH-->" + REAL_SEND_LENGTH); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0330.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0330.java new file mode 100644 index 0000000..01625d0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0330.java @@ -0,0 +1,314 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKNG_0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private String recvTelegramBody; + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKNG_0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + recvTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + String recvBlock = recvTelegramBody.substring(1,5); + if ( recvBlock.equals("0000") ){ + REAL_BYTE = batchDoc.getBatchMsg().getFileHeader().getBytes().length; + }else{ + REAL_BYTE = batchDoc.getBatchMsg().getFileTrailer().getBytes().length; + } + + boolean result = calculateSendLength(); + if (!result) return false; + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //전문 발생 (송신) 주체, 참가기관 발생: 'B', 한국은행 발생: 'C' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //전문처리결과, 정상: '000', 오류: 'A. 응답코드' 참조 + compileField(6, TelegramKeys.BOKNG_RET_CODE_000, this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, recvTelegramBody.substring(1,5), this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, recvTelegramBody.substring(5,8), this.al_FieldProps[9]); + + //Record 수 + compileField(10, recvTelegramBody.substring(8,11), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(8)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ batchDoc.getBatchMsg().getHeader().getRecLen(); + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + } else if ( recv_block_no == 9999 ) { + LogUtil.setLogFileEnd(batchDoc); + } + + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + String recvBlock = recvTelegramBody.substring(1,5); + if ( recvBlock.equals("0000") ){ + System.arraycopy(batchDoc.getBatchMsg().getFileHeader().getBytes(), 0, data, 0, REAL_BYTE ); + }else{ + System.arraycopy(batchDoc.getBatchMsg().getFileTrailer().getBytes(), 0, data, 0, REAL_BYTE ); + } + +// // 수신한 은행코드와 송신하는 은행코드가 다름 +// System.arraycopy( telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(), 0, data, 15, 3); + + logger.warn("SEND_BOKGG_0330:DATA-->[" + new String(data) + "]" ); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0600.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0600.java new file mode 100644 index 0000000..07dd59e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0600.java @@ -0,0 +1,360 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerDAO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class SEND_BOKNG_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + //private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //개별업무 종료 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKNG_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + if ( OpCode_start.equals(getFldOpCode()) ) { + if (!setIdPass()) return false; + } + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //전문처리결과, 정상: '000', 오류: 'A. 응답코드' 참조 + compileField(6, TelegramKeys.BOKGG_RES_CODE_SUCESS, this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- 한국은행 기준 파일 수신시 ‘R’, 송신시 ‘S’ + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //전문 전송일시 ‘YYYYMMDDHHMMSS’ + compileField(8, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[8]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + String plane = batchDoc.getBatchMsg().getHeader().getUserID() + batchDoc.getBatchMsg().getHeader().getUserPassword(); + logger.debug("plane-->[" + plane + "](" + plane.getBytes().length + ")") ; + byte[] enc = IniSafeManager.getInstance().enc(batchDoc, plane.getBytes()); + logger.debug("enc-->(" + enc.length + ")" + CommonLib.getDumpMessage(enc)) ; + byte[] byteID = new byte[20]; + byte[] bytePass = new byte[16]; + System.arraycopy(enc, 0, byteID, 0, 20); + System.arraycopy(enc, 20, bytePass, 0, 16); + + //송신자명 송신기관 사용자ID - 상기 전문상 암호화 대상은 「송신자ID」, 「송신자PWD」 임 + al_Field.set(10, byteID); + + //송신자 암호 송신기관 Password - 상기 전문상 암호화 대상은 「송신자ID」, 「송신자PWD」 임 + al_Field.set(11, bytePass); + + byte[] test = new byte[36]; + System.arraycopy(byteID, 0, test, 0, 20); + System.arraycopy(bytePass, 0, test, 20, 16); + logger.debug("[TEST_ENC]-->(" + test.length + ")" + CommonLib.getDumpMessage(test)) ; + byte[] test2 = IniSafeManager.getInstance().dec(batchDoc, test); + logger.debug("[TEST_DEC]-->(" + test2.length + ")" + CommonLib.getDumpMessage(test2)) ; + logger.debug("[TEST_STR1]-->" + new String (test2) ) ; + logger.debug("[TEST_STR2]-->" + new String (test2) + "<--") ; + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + else return 8; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < 8) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + + String summary = "01" + batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( summary.getBytes(), 0, data, 0, 8); + return 8; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } +// SEND_LENGTH += this.getCalculatedLength(this.al_Field.size() - 1); + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean setIdPass(){ + try { + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String instiCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + String userID = hdrInfo.substring(38,58); + String passWord = hdrInfo.substring(58,74); + batchDoc.getBatchMsg().getHeader().setUserID(userID); + batchDoc.getBatchMsg().getHeader().setUserPassword(passWord); + try { + OutsideManager.getInstance().updateOsdIdPassword(procCode, instiCode, userID, passWord); + + // 대외기관정보도 업데이트 한다. + FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class); + BatchTargetVO vo = dao.getBatchTargetVO(procCode, instiCode); + + FlowControllerManager.getInstance().getTargets().put(procCode + instiCode, vo); + } catch (Exception e) { + logger.warn("ID와 비밀번호 수정 실패"); + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0610.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0610.java new file mode 100644 index 0000000..01c4da6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0610.java @@ -0,0 +1,325 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.doc.Header; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class SEND_BOKNG_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private final String OpCode_all_end = "004"; //개별업무 종료 + +// private String recvTelegramBody; + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_BOKNG_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //전문 발생 (송신) 주체, 참가기관 발생: 'B', 한국은행 발생: 'C' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //전문처리결과, 정상: '000', 오류: 'A. 응답코드' 참조 + compileField(6, TelegramKeys.BOKGG_RES_CODE_SUCESS, this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //전문 전송일시 YYYYMMDDHHMMSS 기관에서 수신 시간 이후에 미수신자료를 수신코자 할 때는 전송일자와 상수(YYYYMMDD999999)를 SET한다. + compileField(8, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[8]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + // InboundServer 생성 후에 변경된 사용자 ID, 암호를 가져온다. + Header header = batchDoc.getBatchMsg().getHeader(); + String processCode = header.getProcessCode(); + String organCode = header.getInstitutionCode(); + BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(processCode, organCode); + + String userID = btVO.getDemadnTargets()[0].getSocketID(); + String password = btVO.getDemadnTargets()[0].getSocketPwd(); + + //뒤에 스페이스가 있는 경우 모두 짤리므로 다시 붙여서 20 자리를 만든다. + String appendUserID = userID + " "; + batchDoc.getBatchMsg().getHeader().setUserID(appendUserID.substring(0, 20)); + + //뒤에 스페이스가 있는 경우 모두 짤리므로 다시 붙여서 16 자리를 만든다. + String appendPassword = password + " "; + batchDoc.getBatchMsg().getHeader().setUserPassword(appendPassword.substring(0, 16)); + + String plane = batchDoc.getBatchMsg().getHeader().getUserID() + batchDoc.getBatchMsg().getHeader().getUserPassword(); + logger.debug("0610 plane-->[" + plane + "](" + plane.getBytes().length + ")") ; + byte[] enc = IniSafeManager.getInstance().enc(batchDoc, plane.getBytes()); + logger.debug("enc-->[" + new String(enc) + "](" + enc.length + ")") ; + byte[] byteID = new byte[20]; + byte[] bytePass = new byte[16]; + System.arraycopy(enc, 0, byteID, 0, 20); + System.arraycopy(enc, 20, bytePass, 0, 16); + + //송신자명 송신기관 사용자ID - 상기 전문상 암호화 대상은 「송신자ID」, 「송신자PWD」 임 + al_Field.set(10, byteID); + + //송신자 암호 송신기관 Password - 상기 전문상 암호화 대상은 「송신자ID」, 「송신자PWD」 임 + al_Field.set(11, bytePass); + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + else return 8; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < 8) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + + String summary = "01" + batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( summary.getBytes(), 0, data, 0, 8); + return 8; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } +// SEND_LENGTH += this.getCalculatedLength(this.al_Field.size() - 1); + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0620.java b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0620.java new file mode 100644 index 0000000..7f8b82a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/bokng/SEND_BOKNG_0620.java @@ -0,0 +1,200 @@ +package com.eactive.eai.batch.job.jobItem.bokng; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_BOKNG_0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_BOKNG_0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //필수 (전문전체길이 - 길이부길이) + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - BOK + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //국고망: 'BOK', 한은망: 'FTP'참가기관 코드 + //- 국고망 : 현행 기관코드(외부기관 지로코드)를 맨 앞에서 + //3자리 기재 (마지막자리는 공백) + //- 한은망 : 현행 기관코드(한국은행 부여 기관코드)를 기재 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문 목록 상의 전문종별 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 (File Name) + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문발생 주체, 항시 ‘B' + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드.- BOK 중심 수신 구분, 항시 ‘S' + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF.java new file mode 100644 index 0000000..f608d6c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF.java @@ -0,0 +1,101 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +public class RECV_CCRSF extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 신용회복위원회 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_CCRSF() { + } + + public boolean doValidation() + { + if (!super.doValidation()) return false; + + try { + logger.info("{} >>>>> 응답코드 Checking......", logHeader); + int currFiledIndex = 7; + String currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.CCRSF_RES_CODE_SUCESS)) { + String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getCCRSFRetDescription(currFieldValue); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); // + super.setResolveResponseCode("950"); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + }catch (Exception e){ + logger.error( e.getMessage(), e); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString()); + super.setResolveResponseCode("990"); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(4).equalsIgnoreCase("0600") ||super.getFieldValueString(4).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(9); + } + else { + return super.getOpCode(); + } + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of recv data length [" + byte_size + "]", logHeader); + int tot_byte_size = Integer.parseInt(byte_size); + + int read_byte_size = 0; + + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + logger.info("{} he sum of definite field length [" + (tot_byte_size- read_byte_size) + "]", logHeader); + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0310.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0310.java new file mode 100644 index 0000000..a190748 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0310.java @@ -0,0 +1,241 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CCRSF_0310 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + public RECV_CCRSF_0310() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + // 받은 블록 번호가 현재 처리 하는 블럭 보다 작으면 스킵 + if ( recv_block_no < block_no ){ + return true; + } + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (((recv_block_no - block_no) > 1 ) || ((recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + return false; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0320.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0320.java new file mode 100644 index 0000000..fce63ad --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0320.java @@ -0,0 +1,387 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CCRSF_0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; + + /** + * 생성자 + */ + public RECV_CCRSF_0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + String fName = new String ((byte[]) al_Field.get(5)); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + // 받은 블록 번호가 현재 처리 하는 블럭 보다 작으면 스킵 + if ( recv_block_no > 0 && recv_block_no < block_no ){ + return true; + } +// //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error +// if (( recv_block_no != 9999 ) && ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 )) { +// logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); +// this.setConditionTxt(TelegramKeys.ERROR); +// +// String[] msgArgs = new String[3]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = _block_no; +// msgArgs[2] = ""+block_no; +// String errCode = "BECEAIFJI024"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// +// return false; +// +// } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + try { + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode); + batchDoc.getBatchMsg().getHeader().setRecLen((int)info.getFileRecSize()); + } catch (Exception e) { // 에러가 나도 아무것도 안함 + // do nothing + } + + long totRecCnt = 0; + try { + totRecCnt = Integer.parseInt(batchDoc.getBatchMsg().getFileHeader().substring(23, 30)); + } catch (Exception e) { + // do nothing + } + + batchDoc.getBatchMsg().getHeader().setFileSize ( (totRecCnt + 2 ) * batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().getHeader().setTotRecCnt( totRecCnt + 2 ); + + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ + // 강제 결번 세팅 +// } else if ((recv_block_no > 0) && ( recv_seq_no%30 != 5 ) ){ + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + if ( init ){ + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + } + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.KFB_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0330.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0330.java new file mode 100644 index 0000000..696e74c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0330.java @@ -0,0 +1,144 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class RECV_CCRSF_0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_CCRSF_0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size() -1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(9).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + + } else if (super.getFieldValueString(9).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0600.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0600.java new file mode 100644 index 0000000..6b9bfa9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0600.java @@ -0,0 +1,170 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CCRSF_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_CCRSF_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(5)); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0610.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0610.java new file mode 100644 index 0000000..51b7508 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0610.java @@ -0,0 +1,161 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CCRSF_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_CCRSF_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKJJ_RET_CODE_TEL_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0620.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0620.java new file mode 100644 index 0000000..f63f2d6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/RECV_CCRSF_0620.java @@ -0,0 +1,115 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CCRSF_0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_CCRSF_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(9)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(10)); // 0 base 인덱스 + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0300.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0300.java new file mode 100644 index 0000000..4c7b38e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0300.java @@ -0,0 +1,396 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CCRSF_0300 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_CCRSF_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //(송신길이)는 TCP/IP 프로토콜에서만 사용 자기 자신 포함 안함 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션 코드 : 회원가기관의 주전산기(또는 중계기)를 위한 트랜잭션 구분자로 “CREDITFTP”를 사용한다. + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //시스템 명칭 : 일괄전송 업무를 타 업무와 구분하기 위하여 사용하는 부호로 “FTP”를 사용한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //회원기관코드 : 전문을 생성하여 발신하는 기관을 나타내기 위한 부호로 회원기관별로 유일하게 부여한다.(5.2 참조). + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문코드 : 전문을 구별하기 위하여 사용하는 기호로 전문 생성기관, 이용목적 등을 포함하고 있다(3.3 참조). + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //업무구분코드 : 전문에 포함된 파일의 용도나 속성을 나타내기 위한 기호로 ‘표준보고서 양식’의 별칭을 사용한다(6.1~6.4 참조). + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문 생성기관 : 전문을 작성한 기관을 나타내는 기호로 신용회복위원회가 생성한 경우 “C”를, 회원기관이 생성한 전문에는 “B”를 사용한다. + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 : 전문의 처리결과를 나타내는 부호로 다음과 같이 설정한다. + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + // 여기부터는 개별부 + + //송수신구분 : 적용업무를 구분하기 위한 기호 + //“S”: 파일송신(신용회복위원회가 회원기관에 파일을 전송)의 경우 + //“R”: 파일수신(회원기관이 신용회복위원회에 파일을 전송) + compileField(8, getFldTrClass() , this.al_FieldProps[8]); + + //Block-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + + //Sequence-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[10]); + + //결번갯수 + compileField(11, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size() - 1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return MISSING_FIELD.length(); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0310.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0310.java new file mode 100644 index 0000000..5675d6e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0310.java @@ -0,0 +1,335 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CCRSF_0310 extends DefaultTelegram implements TelegramService { + + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_CCRSF_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //(송신길이)는 TCP/IP 프로토콜에서만 사용 자기 자신 포함 안함 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션 코드 : 회원가기관의 주전산기(또는 중계기)를 위한 트랜잭션 구분자로 “CREDITFTP”를 사용한다. + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //시스템 명칭 : 일괄전송 업무를 타 업무와 구분하기 위하여 사용하는 부호로 “FTP”를 사용한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //회원기관코드 : 전문을 생성하여 발신하는 기관을 나타내기 위한 부호로 회원기관별로 유일하게 부여한다.(5.2 참조). + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문코드 : 전문을 구별하기 위하여 사용하는 기호로 전문 생성기관, 이용목적 등을 포함하고 있다(3.3 참조). + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //업무구분코드 : 전문에 포함된 파일의 용도나 속성을 나타내기 위한 기호로 ‘표준보고서 양식’의 별칭을 사용한다(6.1~6.4 참조). + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문 생성기관 : 전문을 작성한 기관을 나타내는 기호로 신용회복위원회가 생성한 경우 “C”를, 회원기관이 생성한 전문에는 “B”를 사용한다. + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 : 전문의 처리결과를 나타내는 부호로 다음과 같이 설정한다. + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + // 여기부터는 개별부 + + //송수신구분 : 적용업무를 구분하기 위한 기호 + //“S”: 파일송신(신용회복위원회가 회원기관에 파일을 전송)의 경우 + //“R”: 파일수신(회원기관이 신용회복위원회에 파일을 전송) + compileField(8, getFldTrClass() , this.al_FieldProps[8]); + + //Block-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[9]); + + //Sequence-NO + compileField(10, ""+SEQUENCE_NO , this.al_FieldProps[10]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(11, "" + recCnt, this.al_FieldProps[11]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0320.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0320.java new file mode 100644 index 0000000..5b1c70a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0320.java @@ -0,0 +1,464 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_CCRSF_0320 extends DefaultTelegram implements TelegramService { + + private FileInputStream fin; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_CCRSF_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //(송신길이)는 TCP/IP 프로토콜에서만 사용 자기 자신 포함 안함 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션 코드 : 회원가기관의 주전산기(또는 중계기)를 위한 트랜잭션 구분자로 “CREDITFTP”를 사용한다. + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //시스템 명칭 : 일괄전송 업무를 타 업무와 구분하기 위하여 사용하는 부호로 “FTP”를 사용한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //회원기관코드 : 전문을 생성하여 발신하는 기관을 나타내기 위한 부호로 회원기관별로 유일하게 부여한다.(5.2 참조). + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문코드 : 전문을 구별하기 위하여 사용하는 기호로 전문 생성기관, 이용목적 등을 포함하고 있다(3.3 참조). + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //업무구분코드 : 전문에 포함된 파일의 용도나 속성을 나타내기 위한 기호로 ‘표준보고서 양식’의 별칭을 사용한다(6.1~6.4 참조). + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문 생성기관 : 전문을 작성한 기관을 나타내는 기호로 신용회복위원회가 생성한 경우 “C”를, 회원기관이 생성한 전문에는 “B”를 사용한다. + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 : 전문의 처리결과를 나타내는 부호로 다음과 같이 설정한다. + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + // 여기부터는 개별부 + + //송수신구분 : 적용업무를 구분하기 위한 기호 + //“S”: 파일송신(신용회복위원회가 회원기관에 파일을 전송)의 경우 + //“R”: 파일수신(회원기관이 신용회복위원회에 파일을 전송) + compileField(8, getFldTrClass() , this.al_FieldProps[8]); + + //Block-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[9]); + + //Sequence-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[10]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num == 0 || block_num == 9999) { + recCnt = 1; + }else{ + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + compileField(11, "" + recCnt, this.al_FieldProps[11]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num == 0 || block_num == 9999) { + lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + batchDoc.getBatchMsg().getHeader().getRecLen(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (fin != null ) { + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean createFile () + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int BLOCK_NO = 0; + int SEQUENCE_NO = 0; + int sequence_size = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + + this.setConditionTxt(""); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[96]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + fileData = new byte[60]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + BLOCK_NO = block_no+1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( sequence_size / recLen ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / recLen; + + if ( seqCnt < remainCnt - 1){ + REAL_BYTE = seqCnt * recLen; + }else{ + REAL_BYTE = (int)(remainCnt - 1) * recLen; + } + int readCnt = REAL_BYTE / recLen; + if ( remainCnt - readCnt <= 1 ) { + this.setConditionTxt(TelegramKeys.EOF); + } + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + REAL_BYTE = fileData.length; + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0330.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0330.java new file mode 100644 index 0000000..af0d34a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0330.java @@ -0,0 +1,307 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CCRSF_0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CCRSF_0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + recvTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + + REAL_BYTE = recvTelegramBody.length() - 11; + + boolean result = calculateSendLength(); + if (!result) return false; + + //(송신길이)는 TCP/IP 프로토콜에서만 사용 자기 자신 포함 안함 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션 코드 : 회원가기관의 주전산기(또는 중계기)를 위한 트랜잭션 구분자로 “CREDITFTP”를 사용한다. + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //시스템 명칭 : 일괄전송 업무를 타 업무와 구분하기 위하여 사용하는 부호로 “FTP”를 사용한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //회원기관코드 : 전문을 생성하여 발신하는 기관을 나타내기 위한 부호로 회원기관별로 유일하게 부여한다.(5.2 참조). + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문코드 : 전문을 구별하기 위하여 사용하는 기호로 전문 생성기관, 이용목적 등을 포함하고 있다(3.3 참조). + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //업무구분코드 : 전문에 포함된 파일의 용도나 속성을 나타내기 위한 기호로 ‘표준보고서 양식’의 별칭을 사용한다(6.1~6.4 참조). + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문 생성기관 : 전문을 작성한 기관을 나타내는 기호로 신용회복위원회가 생성한 경우 “C”를, 회원기관이 생성한 전문에는 “B”를 사용한다. + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 : 전문의 처리결과를 나타내는 부호로 다음과 같이 설정한다. + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + // 여기부터는 개별부 + + //송수신구분 : 적용업무를 구분하기 위한 기호 + //“S”: 파일송신(신용회복위원회가 회원기관에 파일을 전송)의 경우 + //“R”: 파일수신(회원기관이 신용회복위원회에 파일을 전송) + compileField(8, getFldTrClass() , this.al_FieldProps[8]); + + //Block-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[9]); + + //Sequence-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[10]); + + //Record 수 --받은 내용을 그대로 돌려 보내기 + compileField(11, recvTelegramBody.substring(8,11), this.al_FieldProps[11]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ batchDoc.getBatchMsg().getHeader().getRecLen(); + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + } else if ( recv_block_no == 9999 ) { + LogUtil.setLogFileEnd(batchDoc); + int fileCnt = 0; + try { + fileCnt = Integer.parseInt(batchDoc.getBatchMsg().getBody().getSendSummary()); + } catch (Exception e) { + } + batchDoc.getBatchMsg().getBody().setSendSummary("" + ++fileCnt); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + System.arraycopy(recvTelegramBody.getBytes(), 11, data, 0, REAL_BYTE ); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0600.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0600.java new file mode 100644 index 0000000..b4d1178 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0600.java @@ -0,0 +1,299 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CCRSF_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + //private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //개별업무 종료 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CCRSF_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //(송신길이)는 TCP/IP 프로토콜에서만 사용 자기 자신 포함 안함 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션 코드 : 회원가기관의 주전산기(또는 중계기)를 위한 트랜잭션 구분자로 “CREDITFTP”를 사용한다. + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //시스템 명칭 : 일괄전송 업무를 타 업무와 구분하기 위하여 사용하는 부호로 “FTP”를 사용한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //회원기관코드 : 전문을 생성하여 발신하는 기관을 나타내기 위한 부호로 회원기관별로 유일하게 부여한다.(5.2 참조). + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문코드 : 전문을 구별하기 위하여 사용하는 기호로 전문 생성기관, 이용목적 등을 포함하고 있다(3.3 참조). + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //업무구분코드 : 전문에 포함된 파일의 용도나 속성을 나타내기 위한 기호로 ‘표준보고서 양식’의 별칭을 사용한다(6.1~6.4 참조). + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문 생성기관 : 전문을 작성한 기관을 나타내는 기호로 신용회복위원회가 생성한 경우 “C”를, 회원기관이 생성한 전문에는 “B”를 사용한다. + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 : 전문의 처리결과를 나타내는 부호로 다음과 같이 설정한다. + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + // 여기부터는 개별부 + + //송수신구분 : 적용업무를 구분하기 위한 기호 + //“S”: 파일송신(신용회복위원회가 회원기관에 파일을 전송)의 경우 + //“R”: 파일수신(회원기관이 신용회복위원회에 파일을 전송) + compileField(8, getFldTrClass() , this.al_FieldProps[8]); + + //관리정보 : 전문의 기능을 나타내는 부호로 + // 개별업무를 시작하는 경우 “001”, + // 개별업무를 종료하는 경우 “003”, + // 일괄전송 모든 업무를 종료하고자 하는 경우 “004”, + // 파일 재전송을 요구하는 경우 “006”을 사용한다. + // ※ 현재 일괄전송 시스템에서 운영하고 있는 개별업무는 회원기관업무시스템 관련업무(업무구분코드가 “FTP”) 밖에 없으며 향후 개별업무가 확장성을 고려함 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //최종 블록번호 : 지금까지 수신한 최종 블록번호를 나타내며 처음부터 받고자 하는 경우 “0000”을 사용한다. + compileField(10, "", this.al_FieldProps[10]); + + //최종 시퀀스번호 : 해당 블록 내에서의 최종 시퀀스번호를 사용한다. + compileField(11, "", this.al_FieldProps[11]); + + //전송 일시 : 전문을 생성한 기관(신용회복위원회 또는 회원기관)에서 전문을 전송하는 일자와 시각(YYYYMMDDHhMmSs)을 기입한다. + //단, 회원기관이 자료 수신 시간대 이후에 미수신 자료를 신용회복위원회로부터 받고자 하는 경우에는 일자에 정상적인 전송일자(YYYYMMDD)를 기입하고 시각은 “999999”(HhMmSs)를 기입한다. + compileField(12, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[12]); + + //송신집계 : 개별업무 종료 및 전 업무 종료 시에만 사용하는 항목으로 송신한 파일의 수를 나타내며 기타의 경우는 “0000”을 사용한다. + if ( this.getFldOpCode().equalsIgnoreCase(OpCode_start) ) + compileField(13, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[13]); + else + compileField(13, "1" ,this.al_FieldProps[13]); + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < 8) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + String summary = "01" + batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( summary.getBytes(), 0, data, 0, 8); + return 8; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + else return 8; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0610.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0610.java new file mode 100644 index 0000000..9a11ab3 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0610.java @@ -0,0 +1,306 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CCRSF_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + private final String OpCode_all_end = "004"; //개별업무 종료 + + /** + * 생성자 + */ + public SEND_CCRSF_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //(송신길이)는 TCP/IP 프로토콜에서만 사용 자기 자신 포함 안함 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션 코드 : 회원가기관의 주전산기(또는 중계기)를 위한 트랜잭션 구분자로 “CREDITFTP”를 사용한다. + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //시스템 명칭 : 일괄전송 업무를 타 업무와 구분하기 위하여 사용하는 부호로 “FTP”를 사용한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //회원기관코드 : 전문을 생성하여 발신하는 기관을 나타내기 위한 부호로 회원기관별로 유일하게 부여한다.(5.2 참조). + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문코드 : 전문을 구별하기 위하여 사용하는 기호로 전문 생성기관, 이용목적 등을 포함하고 있다(3.3 참조). + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //업무구분코드 : 전문에 포함된 파일의 용도나 속성을 나타내기 위한 기호로 ‘표준보고서 양식’의 별칭을 사용한다(6.1~6.4 참조). + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문 생성기관 : 전문을 작성한 기관을 나타내는 기호로 신용회복위원회가 생성한 경우 “C”를, 회원기관이 생성한 전문에는 “B”를 사용한다. + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 : 전문의 처리결과를 나타내는 부호로 다음과 같이 설정한다. + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + // 여기부터는 개별부 + + //송수신구분 : 적용업무를 구분하기 위한 기호 + //“S”: 파일송신(신용회복위원회가 회원기관에 파일을 전송)의 경우 + //“R”: 파일수신(회원기관이 신용회복위원회에 파일을 전송) + compileField(8, getFldTrClass() , this.al_FieldProps[8]); + + //관리정보 : 전문의 기능을 나타내는 부호로 + // 개별업무를 시작하는 경우 “001”, + // 개별업무를 종료하는 경우 “003”, + // 일괄전송 모든 업무를 종료하고자 하는 경우 “004”, + // 파일 재전송을 요구하는 경우 “006”을 사용한다. + // ※ 현재 일괄전송 시스템에서 운영하고 있는 개별업무는 회원기관업무시스템 관련업무(업무구분코드가 “FTP”) 밖에 없으며 향후 개별업무가 확장성을 고려함 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //최종 블록번호 : 지금까지 수신한 최종 블록번호를 나타내며 처음부터 받고자 하는 경우 “0000”을 사용한다. + compileField(10, "", this.al_FieldProps[10]); + + //최종 시퀀스번호 : 해당 블록 내에서의 최종 시퀀스번호를 사용한다. + compileField(11, "", this.al_FieldProps[11]); + + //전송 일시 : 전문을 생성한 기관(신용회복위원회 또는 회원기관)에서 전문을 전송하는 일자와 시각(YYYYMMDDHhMmSs)을 기입한다. + //단, 회원기관이 자료 수신 시간대 이후에 미수신 자료를 신용회복위원회로부터 받고자 하는 경우에는 일자에 정상적인 전송일자(YYYYMMDD)를 기입하고 시각은 “999999”(HhMmSs)를 기입한다. + compileField(12, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[12]); + + //송신집계 : 개별업무 종료 및 전 업무 종료 시에만 사용하는 항목으로 송신한 파일의 수를 나타내며 기타의 경우는 “0000”을 사용한다. + int fileCnt = 0; + try { + fileCnt = Integer.parseInt(batchDoc.getBatchMsg().getBody().getSendSummary()); + } catch (Exception e) {} + compileField(13, "" + fileCnt, this.al_FieldProps[13]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + +// /** +// * return value : 0 no left data to be sent +// * -1 error +// * >0 data copied to the data field +// * +// * 비정형 필드인 결번확인의 데이터를 얻어낸다. +// * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. +// */ +// public int getInformalFieldSendData(int idx, byte[] data) { +// try { +// if (idx >= this.getFieldCount() ) { +// logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI011"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if (data.length < 8) { +// logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI014"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if ( !OpCode_all_end.equals(getFldOpCode()) ) { +// return 0; +// } +// +// String summary = "01" + batchDoc.getBatchMsg().getHeader().getBizCode(); +// System.arraycopy( summary.getBytes(), 0, data, 0, 8); +// return 8; +// } catch (Exception ex) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI006"; +// String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( ex.getMessage(), ex); +// return -1; +// } +// } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( !OpCode_all_end.equals(getFldOpCode()) ) { + return 0; + } + else return 8; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0620.java b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0620.java new file mode 100644 index 0000000..6a85973 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ccrs/SEND_CCRSF_0620.java @@ -0,0 +1,195 @@ +package com.eactive.eai.batch.job.jobItem.ccrs; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CCRSF_0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CCRSF_0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //(송신길이)는 TCP/IP 프로토콜에서만 사용 자기 자신 포함 안함 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션 코드 : 회원가기관의 주전산기(또는 중계기)를 위한 트랜잭션 구분자로 “CREDITFTP”를 사용한다. + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //시스템 명칭 : 일괄전송 업무를 타 업무와 구분하기 위하여 사용하는 부호로 “FTP”를 사용한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //회원기관코드 : 전문을 생성하여 발신하는 기관을 나타내기 위한 부호로 회원기관별로 유일하게 부여한다.(5.2 참조). + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문코드 : 전문을 구별하기 위하여 사용하는 기호로 전문 생성기관, 이용목적 등을 포함하고 있다(3.3 참조). + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //업무구분코드 : 전문에 포함된 파일의 용도나 속성을 나타내기 위한 기호로 ‘표준보고서 양식’의 별칭을 사용한다(6.1~6.4 참조). + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문 생성기관 : 전문을 작성한 기관을 나타내는 기호로 신용회복위원회가 생성한 경우 “C”를, 회원기관이 생성한 전문에는 “B”를 사용한다. + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 : 전문의 처리결과를 나타내는 부호로 다음과 같이 설정한다. + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + // 여기부터는 개별부 + + //송수신구분 : 적용업무를 구분하기 위한 기호 + //“S”: 파일송신(신용회복위원회가 회원기관에 파일을 전송)의 경우 + //“R”: 파일수신(회원기관이 신용회복위원회에 파일을 전송) + compileField(8, getFldTrClass() , this.al_FieldProps[8]); + + //Block-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[9]); + + //Sequence-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[10]); + + //예비 필드 + compileField(11, "", this.al_FieldProps[11]); + + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT.java b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT.java new file mode 100644 index 0000000..4eb8925 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT.java @@ -0,0 +1,72 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.lang.String; + +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_CFABT extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : 여신금융협회 전문 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_CFABT() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int recCnt = Integer.parseInt( super.getFieldValueString(3) ); + String bizCode = super.getFieldValueString(0).substring(3); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + int recLen = (int)jvo.getFileRecSize(); + return (recCnt * recLen ); + + } catch (Exception ex) { + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return -1; + } + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0200.java b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0200.java new file mode 100644 index 0000000..63c9e41 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0200.java @@ -0,0 +1,346 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CFABT_0200 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 14; + private ByteArrayOutputStream bout; + private FileOutputStream fout; + /** + * 생성자 + */ + public RECV_CFABT_0200() { + //DATA전문 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + String fName = new String((byte[])this.al_Field.get(4)).trim(); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + long recLen = 0; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, true); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + batchDoc.getBatchMsg().getHeader().setRecLen((int)recLen); + + return true; + + + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 +// batchDoc.getBatchMsg().setTelegramBody(new String((byte[])this.al_Field.get(14))); + batchDoc.getBatchMsg().setTelegramBody(""); + batchDoc.getBatchMsg().getBody().setRecvFld01(new String((byte[])this.al_Field.get(1))); + batchDoc.getBatchMsg().getBody().setRecvFld04(new String((byte[])this.al_Field.get(4))); + batchDoc.getBatchMsg().getBody().setRecvFld07(new String((byte[])this.al_Field.get(7))); + batchDoc.getBatchMsg().getBody().setRecvFld08(new String((byte[])this.al_Field.get(8))); + batchDoc.getBatchMsg().getBody().setRecvFld09(new String((byte[])this.al_Field.get(9))); + + return writeToFile(); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch (Exception ex) { + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return -1; + } + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean writeToFile(){ + if ( !createFile () ) + return false; + boolean isHeader = false; + boolean isTrailer = false; + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + try { + String strRecvLen = getJobInfo().getProperty(TelegramKeys.RECV_REC_LEN); + recLen = Integer.parseInt(strRecvLen); + } catch (Exception e) {} + + byte[]layout = new byte[recLen]; + try { + int recCnt = Integer.parseInt( super.getFieldValueString(9) ); + for (int jnx = 0; jnx < recCnt; jnx++) { + System.arraycopy( bout.toByteArray(), jnx*layout.length, layout,0,layout.length); + fout.write(layout); + fout.write( '\n' ); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+recLen; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + batchDoc.getBatchMsg().getHeader().setFileSize(lnCurSize); + byte[] hdata = new byte[2]; + if ( layout.length > 2 ){ + System.arraycopy(layout, 0, hdata, 0, 2); + if ( "HD".equals(new String(hdata))){ + isHeader = true; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(0); + } + if ( "TD".equals(new String(hdata))){ + isTrailer = true; + } + } + } + int curCnt = (int)batchDoc.getBatchMsg().getHeader().getTotRecCnt(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(curCnt + recCnt); + } catch (Exception e) { + logger.error( e.getMessage(), e); + return false; + }finally{ + try { + fout.close(); + } catch (Exception e2) { + logger.error( e2.getMessage(), e2); + } + } + + try { + if ( isHeader ){ + batchDoc.getBatchMsg().setFileHeader(new String(layout)); + LogUtil.setLogFileStart(batchDoc); + } + if ( isTrailer ){ + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + batchDoc.getBatchMsg().setFileTrailer(new String(layout)); + + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + File file = new File(strFullPath); + File rcvArchFile = new File( StringUtil.realToArchDir(strFullPath) ); + File rcvRootFile = new File( StringUtil.realToRootDir(strFullPath) ); + + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + this.setResolveResponseCode("40"); + } + //수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(업무 서버에 자동 송신하도록 수신 File Event 발생)", logHeader); + if (!rcvRootFile.createNewFile()) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + this.setResolveResponseCode("40"); + } + LogUtil.setLogFileEnd(batchDoc); + } + } catch (Exception e) { + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + private boolean createFile () { + try { + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + fileName; + File file = new File(strFullPath); + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() > 0 ){ + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + }else{ + fout = new FileOutputStream(file, false); + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0210.java b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0210.java new file mode 100644 index 0000000..61f5b36 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0210.java @@ -0,0 +1,243 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CFABT_0210 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_CFABT_0210() { + //DATA응답 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + +// try { +// +//// String str_seq = new String ((byte[]) al_Field.get(8)); +//// +//// int recv_seq = Integer.parseInt(str_seq); +//// +//// this.batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq); +//// if ( this.getOpCode().equals("999")){ +//// this.setConditionTxt("NOFILE"); +//// } +// } catch ( Exception e) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI001"; +// String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( e.getMessage(), e); +// return false; +// } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return 0; + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return false; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + long totalFileSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + long curFileSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + if ( curFileSize >= totalFileSize){ + this.setConditionTxt(TelegramKeys.EOF); +// LogUtil.setLogFileEnd(batchDoc); + //요구송신 파일 END DB로그 +// try { +//// LogUtil.setLogFileEnd(batchDoc); +//// if ( checkMoreFileInDir()){ +//// this.setConditionTxt(""); +//// } else { +//// this.setConditionTxt(TelegramKeys.EOF); +//// } +// +// } catch (Exception ex) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI021"; +// String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return false; +// } + } + + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + +// private boolean checkMoreFileInDir(){ +// +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// try{ +// +// //거래구분 코드 설정 +// int bizCodeStartIndex = 0; +// int bizCodeEndIndex = 0; +// ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); +// for (int i=0; organList!=null && i 0) { +// for (int inx=0; inx= fileName.length()) bizCodeStartIndex = 0; +// if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); +// String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); +// BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); +// if ( bjvo != null ) { +// if (bjvo.getPriority() < msgPriority ){ +// msgPriority = bjvo.getPriority(); +// sndRealFile = fileList[inx]; +// batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); +// batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); +// } +// } +// } +// if ( sndRealFile == null ) { +// return false; +// } +// String strFileName = sndRealFile.getName(); +// String renamedFileName = strFileName + "_" + CalendarUtil.getCurrentTimeNoDash(); +// File sndArchFile = new File( batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + renamedFileName ); +// logger.info("{} >>>>> 송신 대기 파일을 송신 Real 디렉토리 -> 송신 Arch 디렉토리로 이동.....", logHeader); +// boolean isSuccessMoveFile = sndRealFile.renameTo(sndArchFile); +// if (!isSuccessMoveFile) { +// String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI044", new String[] {sndRealFile.getAbsolutePath(), sndArchFile.getAbsolutePath()}); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //송신 대기중인 파일을 송신 Real 디렉토리 -> 송신 Arch 디렉토리로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] +// return false; +// } +// +// batchDoc.getBatchMsg().getHeader().setFileName(strFileName); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(renamedFileName); +// +// } else { +// return false; +// } +// +// } catch ( Exception e){ +// return false; +// } +// return true; +// } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0800.java b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0800.java new file mode 100644 index 0000000..40424d1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0800.java @@ -0,0 +1,124 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CFABT_0800 extends DefaultTelegram implements TelegramService +{ +// //>> 업무관리정보 +// private final String OpCode_start = "001"; //업무개시 +// private final String OpCode_restart = "002"; //업무재개시 +// private final String OpCode_end = "040"; //업무종료 +// private final String OpCode_teset = "301"; //회선시험 + + + /** + * 생성자 + */ + public RECV_CFABT_0800() { + //여신금융협회 개시/종료/통신망 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + +// //업무관리정보 유효성 확인 +// if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_restart)) { +// String bizCode = super.getFieldValueString(0).substring(3); +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); +// if ( jvo != null ){ +// batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); +// batchDoc.getBatchMsg().getHeader().setJobCode(jvo.getMsgDstCode()); +// } +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_teset)) { +// } +// else { +// logger.info("{} 0800 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); +// this.setResolveResponseCode("94"); +// +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = this.getOpCode(); +// String errCode = "BECEAIFJI008"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// +// } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + batchDoc.getBatchMsg().getBody().setRecvFld01(new String((byte[])this.al_Field.get(1))); + batchDoc.getBatchMsg().getBody().setRecvFld04(new String((byte[])this.al_Field.get(4))); + batchDoc.getBatchMsg().getBody().setRecvFld07(new String((byte[])this.al_Field.get(7))); + batchDoc.getBatchMsg().getBody().setRecvFld08(new String((byte[])this.al_Field.get(8))); + batchDoc.getBatchMsg().getBody().setRecvFld09(new String((byte[])this.al_Field.get(9))); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0810.java b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0810.java new file mode 100644 index 0000000..5928b19 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/RECV_CFABT_0810.java @@ -0,0 +1,115 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_CFABT_0810 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_CFABT_0810() { + //여신금융협회 개시/종료/통신망 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + +// //업무관리정보 유효성 확인 +// if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_restart)) { +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_teset)) { +// } +// else { +// logger.info("{} 0800 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); +// this.setResolveResponseCode("94"); +// +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = this.getOpCode(); +// String errCode = "BECEAIFJI008"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// +// } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + if ( getOpCode().equals("004")){ + try { + int sleepTime = Integer.parseInt(getTelegramInfo().getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0200.java b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0200.java new file mode 100644 index 0000000..868a4ec --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0200.java @@ -0,0 +1,507 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CFABT_0200 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private File file; + private int SEQUENCE_NO; + private int REC_CNT; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private Properties jobInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_CFABT_0200() { + //DATA전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = makeSendData(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TR - CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //TEXT 개시문자 + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //업무구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //전문개시일시 + compileField(5, TelegramKeys.getYYYYMMddHHmmss().substring(2), this.al_FieldProps[5]); + + //전문추적번호 + compileField(6, makeZero("", ((byte[]) this.al_Field.get(6)).length), this.al_FieldProps[6]); + + //거래구분코드 - 전문발생기관에서 전문을 구분하기 위하여 부여되는 코드로 한 거래가 끝날때까지 코드가 바뀌지 않고 SET 되어져야 한다. + // - 수신기관 CODE(2) : 수신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신기관 CODE(2) : 발신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신 단말 번호(8) + // - 블록 건수 (6) + String txnGbnCd = "00" + telegramInfo.getProperty(TelegramKeys.BANK_CODE) + + makeZero("", ((byte[]) this.al_Field.get(7)).length - 4 ) ; + compileField(7, txnGbnCd, this.al_FieldProps[7]); + + //BLOCK 건수 - 데이터 전문 전송 횟수를 set함. + compileField(8, makeZero("" + SEQUENCE_NO, ((byte[]) this.al_Field.get(8)).length), this.al_FieldProps[8]); + + //자료건수 - 한 전문내에 SET할 수 있는 해당 업무별 RECORD의 갯수이며 전문 송신시 실 RECORD의 수를 SET함. + compileField(9, makeZero( ""+ REC_CNT, ((byte[]) this.al_Field.get(9)).length), this.al_FieldProps[9]); + + //자료계속 여부 - 향후 사용 + compileField(10, makeZero("", ((byte[]) this.al_Field.get(10)).length), this.al_FieldProps[10]); + + //망 관리정보 - 협회와 신용카드업자간의 시스템 상태에 대한 정보코드로 아래 값 중 하나를 SET 한다 + // 001 - 개시 + // 002 - 재개시 + // 003 - 종료예고 + // 004 - 종료 + // 005 - SYSTEM BUSY + // 006 - SYSTEM BUSY 회복 + // 007 - SYSTEM 장애 + // 008 - SYSTEM 장애 회복 + // 301 - 상태확인 처리 + compileField(11, this.getFldOpCode(), this.al_FieldProps[11]); + + //응답코드 - 전문의 처리결과를 정의해주는 코드로 다음의 응답코드를 기록한다. + compileField(12, makeZero("", ((byte[]) this.al_Field.get(12)).length), this.al_FieldProps[12]); + + // FILLER + compileField(13, "", this.al_FieldProps[13]); + //<< 전문 완성 + + +// //전문일련번호 - 전송 Data중 최초 Data 순서번호 또는 재개시, 거부응답의 경우에는 정상처리의 최종 Data번호 +// compileField(7, "" + SEQUENCE_NO, this.al_FieldProps[7]); +// +// //DATA건수 - 데이터블록내의 전송 Data 건수 +// compileField(8, "" + REC_CNT, this.al_FieldProps[8]); +// //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + (REC_CNT*batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + // 로깅을 위해 +// byte[] fieldData = new byte[fldLen]; +// System.arraycopy(data, 0, fieldData, 0, fldLen); +// this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if ( file != null ){ // 처음 전송이면 + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(file); + //요구송신 파일 Start DB로그 +// batchDoc.getBatchMsg().getHeader().setFileSize(file.length()); + LogUtil.setLogFileStart(batchDoc); + } +// if ( this.getOpCode().equals("000") ){ // DATA전송인 경우 +// this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO + REC_CNT - 1); +// } +// logger.debug("[파일사이즈]->" + batchDoc.getBatchMsg().getHeader().getFileSize() + ", 현재 크기-->" + batchDoc.getBatchMsg().getBody().getCurFileSize()); + long totalFileSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + long curFileSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + if ( curFileSize >= totalFileSize){ + LogUtil.setLogFileEnd(batchDoc); + } + batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 +// batchDoc.getBatchMsg().setTelegramBody(new String((byte[])this.al_Field.get(14))); + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + jobInfo = getJobInfo(); + SEQUENCE_NO = batchDoc.getBatchMsg().getBody().getSeqNum() + 1; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + + } + + private boolean createFile () + { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null ){ + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + } + return !( fin == null); + } + + private boolean makeSendData() + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + +// byte[] fileLine = null; +// +// if ( retryCnt > 0 ){ // 타임오버 이후의 재 전송인 경우, 이전에 DATA가 있었던 경우에만 +// +// if ( batchDoc.getBatchMsg().getTelegramBody() != null && !batchDoc.getBatchMsg().getTelegramBody().equals("") ){ +// logger.debug("batchDoc.getEAIBatchMessage().getTelegramBody()-->[" + batchDoc.getBatchMsg().getTelegramBody() + "]"); +// byte[] prevData = batchDoc.getBatchMsg().getTelegramBody().getBytes(); +// fileLine = new byte[prevData.length + 2]; +// System.arraycopy( batchDoc.getBatchMsg().getTelegramHeader().getBytes(), 47, fileLine, 0, 2); +// System.arraycopy(prevData, 0, fileLine, 2, prevData.length); +// } +// }else{ +// if ( isReSend ){ // 중단된 이후 재 송신인 경우 +// fileLine = skipLine(); +// }else{ +// fileLine = FileUtil.readLine(fin); +// } +// } + + // 한번에 블러킹 할 건수 + int seqCnt = 1; + int padLen = 0; + try { + seqCnt = Integer.parseInt(jobInfo.getProperty(TelegramKeys.BLOCKING_COUNT)); + padLen = Integer.parseInt(jobInfo.getProperty(TelegramKeys.PADDING_LEN)); + } catch (Exception e) {} + + + logger.debug("[SEND_CFABT_0200]SEQUENCE_NO-->" + SEQUENCE_NO + ",seqCnt-->" + seqCnt); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + logger.debug("[SEND_CFABT_0200]batchDoc.getBatchMsg().getHeader().getFileSize()-->" + batchDoc.getBatchMsg().getHeader().getFileSize()); + logger.debug("[SEND_CFABT_0200]batchDoc.getBatchMsg().getBody().getCurFileSize()-->" + batchDoc.getBatchMsg().getBody().getCurFileSize()); + logger.debug("[SEND_CFABT_0200]remainSize-->" + remainSize); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + logger.debug("[SEND_CFABT_0200]remainCnt-->" + remainCnt); + + boolean isLastSeq = false; + REC_CNT = seqCnt; + if ( remainCnt < seqCnt ){ + REC_CNT = (int)remainCnt; + isLastSeq = true; + } + logger.debug("[SEND_CFABT_0200]readCnt-->" + REC_CNT); + + REAL_BYTE = batchDoc.getBatchMsg().getHeader().getRecLen() * seqCnt + padLen; + + logger.debug("[SEND_CFABT_0200]REAL_BYTE-->" + REAL_BYTE); + + fileData = new byte[REAL_BYTE]; + for (int inx = 0; inx < fileData.length; inx++) { + fileData[inx] = ' '; + } + for ( int inx = 0 ; inx < REC_CNT ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + if ( isLastSeq ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + +// +// fileLine = FileUtil.readLine(fin); +// +// if ( fileLine != null ){ +// byte[] byte_cnt = new byte[2]; +// byte[] byte_first_seq = new byte[8]; +// //logger.debug( "makeSendData:fileLine-->" + new String(fileLine )); +// System.arraycopy( fileLine, 0, byte_cnt, 0, 2); +// System.arraycopy( fileLine, 2, byte_first_seq, 0, 8); +// REC_CNT = Integer.parseInt( new String(byte_cnt)); +// SEQUENCE_NO = Integer.parseInt( new String(byte_first_seq)); +// REAL_BYTE = REC_CNT * batchDoc.getBatchMsg().getHeader().getRecLen(); +// fileData = new byte[REAL_BYTE]; +// System.arraycopy( fileLine, 2, fileData, 0, REAL_BYTE); +// +// }else{ +// REAL_BYTE = 0; +// this.setFldOpCode("999"); +// SEQUENCE_NO = batchDoc.getBatchMsg().getBody().getSeqNum(); +// fin.close(); +// BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); +// +// } + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + +// private byte[] skipLine() throws Exception{ +// byte[] fileLine = null; +// byte[] byte_count = new byte[2]; +// byte[] byte_sequence = new byte[8]; +// int iCount = 0; +// int iSequence = 0; +// int skipCnt = 0; // 읽은 라인에서 스킵할 건수 +// while ( ( fileLine = FileUtil.readLine(fin) ) != null ){ +// System.arraycopy( fileLine, 0, byte_count, 0, 2); +// System.arraycopy(fileLine, 2, byte_sequence, 0, 8); +// iCount = Integer.parseInt( new String(byte_count)); +// iSequence = Integer.parseInt( new String(byte_sequence)); +// if ( LAST_SEQ + 1 <= iSequence+iCount -1 ){ +// //logger.debug("skipLine:LAST_SEQ->" + LAST_SEQ); +// +// skipCnt = LAST_SEQ + 1 - iSequence; +// int skipByte = skipCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); +// byte []newFileLine = new byte[fileLine.length - skipByte]; +// if ( iCount - skipCnt < 10 ){ +// newFileLine[0] = '0'; +// newFileLine[1] = (""+(iCount - skipCnt)).getBytes()[0]; +// }else{ +// System.arraycopy((""+(iCount - skipCnt)).getBytes(), 0, newFileLine, 0, 2); +// } +// System.arraycopy(fileLine, 2 + skipByte, newFileLine, 2, newFileLine.length -2); +// return newFileLine; +// } +// } +// throw new Exception("재전송 시작할 위치를 찾지 못하였습니다."); +// } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0210.java b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0210.java new file mode 100644 index 0000000..176a1d8 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0210.java @@ -0,0 +1,272 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CFABT_0210 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CFABT_0210() { + //DATA응답 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TR - CODE + compileField(1, batchDoc.getBatchMsg().getBody().getRecvFld01(), this.al_FieldProps[1]); + + //TEXT 개시문자 + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //업무구분코드 + compileField(4, batchDoc.getBatchMsg().getBody().getRecvFld04(), this.al_FieldProps[4]); + + //전문개시일시 + compileField(5, TelegramKeys.getYYYYMMddHHmmss().substring(2), this.al_FieldProps[5]); + + //전문추적번호 + compileField(6, makeZero("", ((byte[]) this.al_Field.get(6)).length), this.al_FieldProps[6]); + + //거래구분코드 - 전문발생기관에서 전문을 구분하기 위하여 부여되는 코드로 한 거래가 끝날때까지 코드가 바뀌지 않고 SET 되어져야 한다. + // - 수신기관 CODE(2) : 수신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신기관 CODE(2) : 발신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신 단말 번호(8) + // - 블록 건수 (6) + compileField(7, batchDoc.getBatchMsg().getBody().getRecvFld07(), this.al_FieldProps[7]); + + //BLOCK 건수 - 데이터 전문 전송 횟수를 set함. + compileField(8, batchDoc.getBatchMsg().getBody().getRecvFld08(), this.al_FieldProps[8]); + + //자료건수 - 한 전문내에 SET할 수 있는 해당 업무별 RECORD의 갯수이며 전문 송신시 실 RECORD의 수를 SET함. + compileField(9, batchDoc.getBatchMsg().getBody().getRecvFld09(), this.al_FieldProps[9]); + + //자료계속 여부 - 향후 사용 + compileField(10, makeZero("", ((byte[]) this.al_Field.get(10)).length), this.al_FieldProps[10]); + + //망 관리정보 - 협회와 신용카드업자간의 시스템 상태에 대한 정보코드로 아래 값 중 하나를 SET 한다 + // 001 - 개시 + // 002 - 재개시 + // 003 - 종료예고 + // 004 - 종료 + // 005 - SYSTEM BUSY + // 006 - SYSTEM BUSY 회복 + // 007 - SYSTEM 장애 + // 008 - SYSTEM 장애 회복 + // 301 - 상태확인 처리 + compileField(11, this.getFldOpCode(), this.al_FieldProps[11]); + + //응답코드 - 전문의 처리결과를 정의해주는 코드로 다음의 응답코드를 기록한다. + compileField(12, makeZero("", ((byte[]) this.al_Field.get(12)).length), this.al_FieldProps[12]); + + // FILLER + compileField(13, "", this.al_FieldProps[13]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0800.java b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0800.java new file mode 100644 index 0000000..aa16c74 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0800.java @@ -0,0 +1,271 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CFABT_0800 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CFABT_0800() { + //여신금융협회 개시/종료/통신망 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TR - CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //TEXT 개시문자 + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //업무구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //전문개시일시 + compileField(5, TelegramKeys.getYYYYMMddHHmmss().substring(2), this.al_FieldProps[5]); + + //전문추적번호 + compileField(6, makeZero("", ((byte[]) this.al_Field.get(6)).length), this.al_FieldProps[6]); + + //거래구분코드 - 전문발생기관에서 전문을 구분하기 위하여 부여되는 코드로 한 거래가 끝날때까지 코드가 바뀌지 않고 SET 되어져야 한다. + // - 수신기관 CODE(2) : 수신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신기관 CODE(2) : 발신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신 단말 번호(8) + // - 블록 건수 (6) + String txnGbnCd = "00" + telegramInfo.getProperty(TelegramKeys.BANK_CODE) + + makeZero("", ((byte[]) this.al_Field.get(7)).length - 4 ) ; + compileField(7, txnGbnCd, this.al_FieldProps[7]); + + //BLOCK 건수 - 데이터 전문 전송 횟수를 set함. + compileField(8, makeZero("", ((byte[]) this.al_Field.get(8)).length), this.al_FieldProps[8]); + + //자료건수 - 한 전문내에 SET할 수 있는 해당 업무별 RECORD의 갯수이며 전문 송신시 실 RECORD의 수를 SET함. + compileField(9, makeZero("", ((byte[]) this.al_Field.get(9)).length), this.al_FieldProps[9]); + + //자료계속 여부 - 향후 사용 + compileField(10, makeZero("", ((byte[]) this.al_Field.get(10)).length), this.al_FieldProps[10]); + + //망 관리정보 - 협회와 신용카드업자간의 시스템 상태에 대한 정보코드로 아래 값 중 하나를 SET 한다 + // 001 - 개시 + // 002 - 재개시 + // 003 - 종료예고 + // 004 - 종료 + // 005 - SYSTEM BUSY + // 006 - SYSTEM BUSY 회복 + // 007 - SYSTEM 장애 + // 008 - SYSTEM 장애 회복 + // 301 - 상태확인 처리 + compileField(11, this.getFldOpCode(), this.al_FieldProps[11]); + + //응답코드 - 전문의 처리결과를 정의해주는 코드로 다음의 응답코드를 기록한다. + compileField(12, makeZero("", ((byte[]) this.al_Field.get(12)).length), this.al_FieldProps[12]); + + // FILLER + compileField(13, "", this.al_FieldProps[13]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0810.java b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0810.java new file mode 100644 index 0000000..887e272 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cfa/SEND_CFABT_0810.java @@ -0,0 +1,270 @@ +package com.eactive.eai.batch.job.jobItem.cfa; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CFABT_0810 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CFABT_0810() { + //여신금융협회 개시/종료/통신망 응답 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TR - CODE + compileField(1, batchDoc.getBatchMsg().getBody().getRecvFld01(), this.al_FieldProps[1]); + + //TEXT 개시문자 + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //업무구분코드 + compileField(4, batchDoc.getBatchMsg().getBody().getRecvFld04(), this.al_FieldProps[4]); + + //전문개시일시 + compileField(5, TelegramKeys.getYYYYMMddHHmmss().substring(2), this.al_FieldProps[5]); + + //전문추적번호 + compileField(6, makeZero("", ((byte[]) this.al_Field.get(6)).length), this.al_FieldProps[6]); + + //거래구분코드 - 전문발생기관에서 전문을 구분하기 위하여 부여되는 코드로 한 거래가 끝날때까지 코드가 바뀌지 않고 SET 되어져야 한다. + // - 수신기관 CODE(2) : 수신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신기관 CODE(2) : 발신기관에 해당하는 CODE를 기록한다. (기관 CODE CHECK) + // - 발신 단말 번호(8) + // - 블록 건수 (6) + compileField(7, batchDoc.getBatchMsg().getBody().getRecvFld07(), this.al_FieldProps[7]); + + //BLOCK 건수 - 데이터 전문 전송 횟수를 set함. + compileField(8, batchDoc.getBatchMsg().getBody().getRecvFld08(), this.al_FieldProps[8]); + + //자료건수 - 한 전문내에 SET할 수 있는 해당 업무별 RECORD의 갯수이며 전문 송신시 실 RECORD의 수를 SET함. + compileField(9, batchDoc.getBatchMsg().getBody().getRecvFld09(), this.al_FieldProps[9]); + + //자료계속 여부 - 향후 사용 + compileField(10, makeZero("", ((byte[]) this.al_Field.get(10)).length), this.al_FieldProps[10]); + + //망 관리정보 - 협회와 신용카드업자간의 시스템 상태에 대한 정보코드로 아래 값 중 하나를 SET 한다 + // 001 - 개시 + // 002 - 재개시 + // 003 - 종료예고 + // 004 - 종료 + // 005 - SYSTEM BUSY + // 006 - SYSTEM BUSY 회복 + // 007 - SYSTEM 장애 + // 008 - SYSTEM 장애 회복 + // 301 - 상태확인 처리 + compileField(11, this.getFldOpCode(), this.al_FieldProps[11]); + + //응답코드 - 전문의 처리결과를 정의해주는 코드로 다음의 응답코드를 기록한다. + compileField(12, makeZero("", ((byte[]) this.al_Field.get(12)).length), this.al_FieldProps[12]); + + // FILLER + compileField(13, "", this.al_FieldProps[13]); + //<< 전문 완성 + + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<14; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return 0; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25.java new file mode 100644 index 0000000..3a1f030 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25.java @@ -0,0 +1,172 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_CMS25 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 : CMS쪽 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_CMS25() { + } + + public boolean doValidation() + { + if (!super.doValidation()) return false; + + try { + logger.info("{} >>>>> 응답코드 Checking......", logHeader); + int currFiledIndex = 8; + String currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if ((!currFieldValue.equals(TelegramKeys.RES_CODE_SUCESS) && !currFieldValue.trim().equals(""))) { + String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getCmsRetDescription(currFieldValue); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); // + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + }catch (Exception e){ + logger.error( e.getMessage(), e); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString()); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + return Integer.parseInt( getTelegramInfo().getProperty(propKey) ); + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + idx = vo.getLengthField(); + if (idx == 0) return -1; + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + try { + if ( Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ) == 0 ) + read_byte_size -= 1; + }catch(Exception e1) {} + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + return; + } + LogUtil.setLogFileEnd(batchDoc); + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){} + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0310.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0310.java new file mode 100644 index 0000000..dbf8852 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0310.java @@ -0,0 +1,260 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CMS25_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_CMS25_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + +// //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error +// if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ +// this.setConditionTxt(TelegramKeys.ERROR); +// String[] msgArgs = new String[3]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = _block_no; +// msgArgs[2] = ""+block_no; +// String errCode = "BECEAIFJI024"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return false; +// } + + if ( recv_block_no == block_no ){ + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if ( recv_block_no == block_no ){ + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + } + + + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + try { + if ( Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ) == 0 ) + read_byte_size -= 1; + }catch(Exception e1) {} + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0320.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0320.java new file mode 100644 index 0000000..cc89618 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0320.java @@ -0,0 +1,250 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CMS25_0320 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_CMS25_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); +// +// //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error +// if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ +// Logging(DEBUG, " doExecute >> recived block_no is bigger than current block_no" ); +// this.setConditionTxt(TelegramKeys.ERROR); +// +// String[] msgArgs = new String[3]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = _block_no; +// msgArgs[2] = ""+block_no; +// String errCode = "BECEAIFJI024"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return false; +// } + if ( block_no == 0 && recv_block_no == 1) + batchDoc.getBatchMsg().getBody().setBlockNum(1); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( recv_block_no == block_no ){ + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + try { + if ( Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ) == 0 ) + read_byte_size -= 1; + }catch(Exception e1) {} + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + try{ + if ( getTelegramInfo().getProperty(TelegramKeys.DEBUG).equals("Y") ){ + int blockNum = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seqNum = batchDoc.getBatchMsg().getBody().getSeqNum(); + logger.info( "DATA FIELD DATA(" + blockNum + ")(" +seqNum+ ")" + CommonLib.getDumpMessage(data) ); + } + }catch ( Exception e){} + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0600.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0600.java new file mode 100644 index 0000000..2360e65 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0600.java @@ -0,0 +1,119 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CMS25_0600 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_CMS25_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + batchDoc.getBatchMsg().getBody().setRecvFld09(new String((byte[])this.al_Field.get(9))); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0610.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0610.java new file mode 100644 index 0000000..b628d7d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0610.java @@ -0,0 +1,151 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CMS25_0610 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_CMS25_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + // File Open LOG + File ff = new File(fileName); + + //응답송신이 아니고 0610/0004를 수신하면 (응답송신의 경우 recv0300일경우에 파일을 이동시키므로 이단계에서는 파일이 존재하지 않음 + if (!CommonKeys.PROCESS_RESPONSE_SEND.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + if (ff.exists() && OpCode_noexsist.equals(this.getOpCode())) { + logger.info("{} FILE SIZE ("+ ff.length() + "]", logHeader); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(ff); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + if (OpCode_noexsist.equals(this.getOpCode()) && fileNm != null && !fileNm.trim().equals("")) { + //응답수신 파일 Start DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + if ( OpCode_noexsist.equals(this.getOpCode()) ){ + try { + int sleepTime = Integer.parseInt(getTelegramInfo().getProperty(TelegramKeys.SLEEP_TIME_POST)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + } + + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0620.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0620.java new file mode 100644 index 0000000..52ad423 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0620.java @@ -0,0 +1,140 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CMS25_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_CMS25_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + //int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + + if (recv_block_no > block_no ){ + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); //데이터 기록후 Vector 초기화 + } + if ( recv_block_no < block_no ){ + this.setConditionTxt(TelegramKeys.IGNORE); + }else{ + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + } + + +// if (recv_block_no > block_no || recv_seq_no < seq_no){ +// // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 +// // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. +// this.setConditionTxt(TelegramKeys.ERROR); +// Logging(DEBUG, " received block_no is bigger than current block_no"); +// String[] msgArgs = new String[3]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = _block_no; +// msgArgs[2] = ""+block_no; +// String errCode = "BECEAIFJI024"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return false; +// } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0630.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0630.java new file mode 100644 index 0000000..0bc270e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0630.java @@ -0,0 +1,224 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CMS25_0630 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_CMS25_0630() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + + int file_len = 8; + try{ + file_len = Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.FILE_NAME_LEN) ); + }catch(Exception e){} + + String fileInfo = new String ((byte[]) al_Field.get(9)); + String fName = fileInfo.substring(0, file_len).trim(); + long fSize = Long.parseLong(fileInfo.substring(file_len, file_len + 12)); //화일 size + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_CDCMS_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + } + + String pattern = null; + long recLen = 0; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getHeader().setFileSize(fSize); + long recCnt = 0; + if ( recLen > 0 ){ + recCnt = fSize / recLen; + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + String propKey = TelegramKeys.FILE_NAME_LEN; + try { + int fieldLen = Integer.parseInt( getTelegramInfo().getProperty(propKey) ); + return fieldLen + 16; + } catch (Exception e) {} + return 8 + 16; + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0640.java b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0640.java new file mode 100644 index 0000000..23a1845 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/RECV_CMS25_0640.java @@ -0,0 +1,367 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_CMS25_0640 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_CMS25_0640() { + //화일정보수신통보 + } + + BufferedInputStream bis; + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String fileInfo = new String ((byte[]) al_Field.get(9)); // 화일정보내역 + int file_len = 8; + try { + file_len = Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.FILE_NAME_LEN) ); + }catch ( Exception e){} + + long fSize = Long.parseLong(fileInfo.substring(file_len, file_len + 12)); //화일 size + if (getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_ALREADY_RECEIVED) + ||getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_NOT_REGISTERED)) { //기송신 파일이면 + checkMoreFileinDB(); + } else { + + if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면 + // 레코드 크기 150 + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + // 한번에 블러킹 할 건수 26 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recLen ); + + // 1887600 % ( 150 * 26 ) + if ( fSize % ( recLen * seqCnt ) != 0 ){ + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } + if ( !createFile() ){ + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } + + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + + // 1887600/150= 12584 + int blockSize = batchDoc.getBatchMsg().getHeader().getBlockSize(); + long skipBlockCnt = fSize / ( blockSize * seqCnt * recLen); + + if ( skipBlockCnt > 0 ){ + long iLoopCnt = skipBlockCnt * blockSize * seqCnt; + for( int inx = 0; inx < iLoopCnt; inx++){ + FileUtil.readLine(bis); + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen); + } + batchDoc.getBatchMsg().getBody().setBlockNum((int)skipBlockCnt+1); //기 송신된 블럭 다음부터 송신 + }else{ + batchDoc.getBatchMsg().getBody().setBlockNum(1); + } + + // + int seqSize = recLen * seqCnt; // 3900 + int blockDataSize = blockSize * seqSize; // 390000 + int seqNo = (int)( fSize % blockDataSize ) / seqSize; + + int appendLen = 0; + try { + appendLen = Integer.parseInt(getJobInfo().getProperty(TelegramKeys.APPEND_LL_LEN)); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + for (int inx = 0; inx < seqNo; inx++) { + byte[] fileData = new byte[seqSize]; + for (int jnx = 0; jnx < seqCnt; jnx++) { + byte[] fileLine = FileUtil.readLine(bis); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, jnx * recLen, Math.min(recLen, fileLine.length)); + if ( appendLen > 0 ){ + fileData[((jnx+1) * recLen)-1] = '\n'; + } + if ( appendLen > 1 ){ + fileData[((jnx+1) * recLen)-2] = '\r'; + } + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen); + + } + + block_data.put( new Integer(inx), fileData); + } + batchDoc.getBatchMsg().getBody().setSeqNum(seqNo); + + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + String propKey = TelegramKeys.FILE_NAME_LEN; + try { + int fieldLen = Integer.parseInt( getTelegramInfo().getProperty(propKey) ); + return fieldLen + 16; + } catch (Exception e) { + return 8 + 16; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID(); + String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath()); + batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName()); + batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getEAIBatchMessage().getHeader().setFileSize(0); + batchDoc.getEAIBatchMessage().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + + } + */ + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0300.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0300.java new file mode 100644 index 0000000..4551b34 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0300.java @@ -0,0 +1,512 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_CMS25_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + //compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //결번갯수 + compileField(11, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + batchDoc.getBatchMsg().getBody().setBlockNum(block_no + 1); + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + String jobCode = this.batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + + case 12: + return MISSING_FIELD.length(); + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + src = batchDoc.getBatchMsg().getHeader().getFileName().getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=1,3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + try{ + String skip = telegramInfo.getProperty(TelegramKeys.SKIP_SUMMARY); + if ( skip.equals("Y")){ + block_size = seq_no; + } + }catch ( Exception e){} + + byte[] _missingNm = new byte[block_size]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + String writeNoLf = ""; + try { + writeNoLf = getJobInfo().getProperty(TelegramKeys.SKIP_LF); + } catch (Exception e) {} + + + for (int i = 0; i"+ data.length ); + logger.info( "[SEND_CMS25]:dataCnt -->"+ dataCnt ); + logger.info( "[SEND_CMS25]:recLen -->"+ recLen ); + } + }catch ( Exception e){} + + for (int jnx = 0; jnx < dataCnt; jnx++) { + System.arraycopy( data,jnx*layout.length,layout,0,layout.length); + // 수신한 DATA에서 각 RECORD 마지막에 개행문자가 포함된 경우 SPACE로 변경 + // 2013.04.16 이해승 차장님 Confirm + if ( layout[recLen-2] == '\r' || layout[recLen-2] == '\n' ){ + layout[recLen-2] = ' '; + } + if ( layout[recLen-1] == '\r' || layout[recLen-1] == '\n' ){ + layout[recLen-1] = ' '; + } + fout.write(layout); + fout.write( '\n' ); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+recLen; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + } + } + } + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); //데이터 기록후 Vector 초기화 + } + + this.MISSING_FIELD = new String (_missingNm); + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(MISSING_COUNT); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(MISSING_FIELD); + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI027"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean createFile () { + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0310.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0310.java new file mode 100644 index 0000000..d90ecfa --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0310.java @@ -0,0 +1,411 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_CMS25_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + //compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + src = batchDoc.getBatchMsg().getHeader().getFileName().getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0320.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0320.java new file mode 100644 index 0000000..79031c3 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0320.java @@ -0,0 +1,530 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0320 extends DefaultTelegram implements TelegramService +{ + + private BufferedInputStream bis; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_CMS25_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + //compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + src = batchDoc.getBatchMsg().getHeader().getFileName().getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + int appendLen = 0; + try { + appendLen = Integer.parseInt(getJobInfo().getProperty(TelegramKeys.APPEND_LL_LEN)); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(bis); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), + Math.min(batchDoc.getBatchMsg().getHeader().getRecLen(), fileLine.length)); + if ( appendLen > 0 ){ + fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-1] = '\n'; + } + if ( appendLen > 1 ){ + fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-2] = '\r'; + } + } + + if ( isLastSeq ){ + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0600.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0600.java new file mode 100644 index 0000000..9f06aa5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0600.java @@ -0,0 +1,378 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_CMS25_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + +// //화일명 +// if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ +// compileField(7, "", this.al_FieldProps[7]); +// } else { +// compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); +// } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + String orgCd = telegramInfo.getProperty(TelegramKeys.BANK_CODE); + String orgCd2 = orgCd.substring(1); + if ( orgCd.length() == 8 ) + orgCd2 = orgCd.substring(0,1)+orgCd.substring(7,8); + String passwd = EncryptManager.getInstance().getEncrypt(batchDoc.getBatchMsg().getHeader().getUserID(), + (batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6), + //telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1), + orgCd2, + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(12, passwd, this.al_FieldProps[12]); + }else if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("KCB") ) { + String passwd = EncryptManager.getInstance().getEncryptForKCB( batchDoc.getBatchMsg().getHeader().getUserID(), + batchDoc.getBatchMsg().getHeader().getUserPassword(), + "A000", + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(12, passwd, this.al_FieldProps[12]); + }else{ + compileField(12, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[12]); + } + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + if ( "001|004".indexOf(this.getFldOpCode()) < 0 ){ + src = batchDoc.getBatchMsg().getHeader().getFileName().getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + } + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0610.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0610.java new file mode 100644 index 0000000..d0a54b8 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0610.java @@ -0,0 +1,410 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_CMS25_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + logger.info("{} Process Type : ["+this.batchDoc.getBatchMsg().getHeader().getProcessType()+"]", logHeader); + logger.info("{} FldOpCode : ["+this.getFldOpCode()+"]", logHeader); + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + +// //화일명 +// if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ +// compileField(7, "", this.al_FieldProps[7]); +// } else { +// compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); +// } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + //compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + compileField(9, batchDoc.getBatchMsg().getBody().getRecvFld09(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(12, "", this.al_FieldProps[12]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (this.getFldOpCode().equals("001")) return true; + + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + if ( "001|004".indexOf(this.getFldOpCode()) < 0 ){ + src = batchDoc.getBatchMsg().getHeader().getFileName().getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + } + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0620.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0620.java new file mode 100644 index 0000000..1f8a2a2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0620.java @@ -0,0 +1,337 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CMS25_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } +// //화일명 +// compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + try { + sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME_0620)); + } catch (Exception e) {} + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + src = batchDoc.getBatchMsg().getHeader().getFileName().getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0630.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0630.java new file mode 100644 index 0000000..51f0134 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0630.java @@ -0,0 +1,378 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0630 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_CMS25_0630() { + //화일정보수신요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + int seqSize = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ) * batchDoc.getBatchMsg().getHeader().getRecLen(); + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(fileName, getCalculatedLength(7))); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12)); + // 0630 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + fileInfo.append(makeZero(""+(SEND_LENGTH + seqSize - 13 - (getCalculatedLength(7) - 8)), 4)); + + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + SEND_LENGTH += ( getCalculatedLength(9) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + + case 9: + propKey = TelegramKeys.FILE_NAME_LEN; + fieldLen = 8; + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + } catch (Exception e) {} + return fieldLen + 16; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + src = fileName.getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 9: + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + int seqSize = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ) * batchDoc.getBatchMsg().getHeader().getRecLen(); + + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(fileName, getCalculatedLength(7))); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12)); + // 0630 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + fileInfo.append(makeZero(""+(SEND_LENGTH + seqSize - 13), 4)); + System.arraycopy(fileInfo.toString().getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0640.java b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0640.java new file mode 100644 index 0000000..c70c879 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/cms25/SEND_CMS25_0640.java @@ -0,0 +1,409 @@ +package com.eactive.eai.batch.job.jobItem.cms25; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_CMS25_0640 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_CMS25_0640() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(batchDoc.getBatchMsg().getHeader().getFileName(), getCalculatedLength(7))); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getBody().getCurFileSize(),12)); + fileInfo.append(makeZero(""+calculateTelegramSize(), 4)); + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + //해당 거래구분에 대한 Job_Code 값 설정 + //거래구분코드 조회 BizCode 조회 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + if (info != null) { + batchDoc.getBatchMsg().getHeader().setJobCode(info.getMsgDstCode());; + } else { + logger.debug("{} " + batchDoc.getBatchMsg().getHeader().getUUID()+ "'s Job Code is null", logHeader); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + batchDoc.getBatchMsg().getHeader().setJobCode((processCode+"00000")); //dummy code + // TEST 용 return false; + } + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(1) - 1 ); + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += ( getCalculatedLength(7) - 1 ); + SEND_LENGTH += ( getCalculatedLength(9) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 7: + propKey = TelegramKeys.FILE_NAME_LEN; + break; + + case 9: + propKey = TelegramKeys.FILE_NAME_LEN; + fieldLen = 8; + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + } catch (Exception e) {} + return fieldLen + 16; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + if ( propKey.equals(TelegramKeys.FILE_NAME_LEN)) return 8; + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + for ( int inx = 0; inx < fldLen; inx++ ){ + data[inx] = (byte)0x20; + } + + byte[] src = null; + switch (idx) { + + case 1: + // TR 코드 + src = telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 3: + // 기관코드 + src = telegramInfo.getProperty(TelegramKeys.BANK_CODE).getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 7: + // 파일명 + src = batchDoc.getBatchMsg().getHeader().getFileName().getBytes(); + System.arraycopy(src, 0, data, 0, Math.min(src.length, fldLen) ); + break; + + case 9: + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(batchDoc.getBatchMsg().getHeader().getFileName(), getCalculatedLength(7))); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getBody().getCurFileSize(),12)); + fileInfo.append(makeZero(""+calculateTelegramSize(), 4)); + System.arraycopy(fileInfo.toString().getBytes(), 0, data, 0, fldLen ); + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private int calculateTelegramSize(){ + int recSize = 200; + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo != null && bJobInfo.getFileRecSize() > 0 ){ + recSize = (int)Math.min(bJobInfo.getFileRecSize(), 4000); + } + + // 0630/0640 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630/0640 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + return (batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize) * recSize + SEND_LENGTH - 13 - (getCalculatedLength(7) - 8); + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25.java new file mode 100644 index 0000000..fd05370 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25.java @@ -0,0 +1,29 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25 extends DefaultTelegram implements TelegramService +{ + + public RECV_DAC25() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_030.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_030.java new file mode 100644 index 0000000..df9e27d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_030.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25_030 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_030() { + //LOGIN 응답 + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_070.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_070.java new file mode 100644 index 0000000..35f415f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_070.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25_070 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_070() { + //LOGIN 응답 + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_100.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_100.java new file mode 100644 index 0000000..3e2b42b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_100.java @@ -0,0 +1,137 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.lang.String; +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; + +public class RECV_DAC25_100 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_100() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + String fileName = new String ((byte[]) al_Field.get(6)).substring(0, 5); + String fromId = new String ((byte[]) al_Field.get(8)).trim(); + if ( !fromId.equals("") ){ + fileName = fileName + "_" + fromId; + } + String endGb = new String ((byte[]) al_Field.get(12)); + String bizCode = fileName.substring(0,5); + long fileSize = Long.parseLong(new String ((byte[]) al_Field.get(7))); //화일 size + batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + if ( endGb.equalsIgnoreCase(TelegramKeys.MAGICLINK_END)) { + this.setConditionTxt(TelegramKeys.NOFILE); + } + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + + try { + int recSize = (int)bJobInfo.getFileRecSize(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(fileSize/recSize); + } catch (Exception e) { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + } + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fileName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(new String ((byte[]) al_Field.get(6))); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separator; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + File file = new File(strFullPathName); + if ( file.exists() ){ + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + LogUtil.setLogFileStart(batchDoc); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_110.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_110.java new file mode 100644 index 0000000..66f652b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_110.java @@ -0,0 +1,80 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25_110 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_110() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_120.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_120.java new file mode 100644 index 0000000..c9aee65 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_120.java @@ -0,0 +1,203 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_DAC25_120 extends DefaultTelegram implements TelegramService +{ + private String strFullPathName = ""; + private FileOutputStream fout = null; + + private File rcvRealFile = null; + private File rcvArchFile = null; + private File rcvErrorFile = null; + + public RECV_DAC25_120() { // 다른 전문과 달리 전문 번호가 없어 편의상 120번을 부여함 + } + + public boolean doPreExecute() + { + if (!super.doPreExecute()) return false; + //1. 수신파일 저장 경로 설정 + //저장 디렉토리는 Inbound Server 에서 설정됨 (응답수신 Real 또는 응답송신 Real) + strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separator; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + logger.info("{} 응답수신 파일 저장 경로 : [" + this.strFullPathName + "]", logHeader); + rcvRealFile = new File( this.strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPathName) ); + rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPathName) ); + + //2. 응답수신 파일 생성 + logger.info("{} >>>>> 응답수신 파일 생성...... ("+ this.strFullPathName +")", logHeader); + try { +// boolean append = true; +// if ( batchDoc.getBatchMsg().getBody().getCurFileSize() < 1){ +// append = false; +// } + fout = new FileOutputStream(rcvRealFile, true); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI041", new String[] {rcvRealFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 해당 경로에 생성시 오류가 발생하였습니다. [Path : {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + try { + return Integer.parseInt(new String ((byte[]) al_Field.get(0))); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + //파일 끝에 append + fout.write(data, 0, length); + + //읽어 들인 파일 사이즈 저장 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch (Exception ex) { + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.error("{} ★★★★★ 수신 파일 데이터 WRITE 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //1. 수신 파일 Close =========================================================== + if (fout != null) fout.close(); + + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() < batchDoc.getBatchMsg().getHeader().getFileSize() ){ + return true; + } + + setConditionTxt(TelegramKeys.EOF); + //2. 수신 파일 End DB로그 ====================================================== + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //사이즈 비교 + long recvSize = rcvRealFile.length(); + if ( recvSize != batchDoc.getBatchMsg().getHeader().getFileSize() ){ + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SEND_BYTE_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute]recvSize-->" + recvSize ); + logger.debug(this.getClass().getName() + "[doPostExecute]batchDoc.getBatchMsg().getHeader().getFileSize()-->" + batchDoc.getBatchMsg().getHeader().getFileSize() ); + return false; + } + super.setFileHeaderAndTrailer(rcvRealFile); + } + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) ) { + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + logger.debug(this.getClass().getName() + "[doPostExecute]super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](1)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPathName) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](2)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_130.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_130.java new file mode 100644 index 0000000..58bc294 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_DAC25_130.java @@ -0,0 +1,142 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_DAC25_130 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_DAC25_130() { + //수신확인 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + + String procYn = new String ((byte[]) al_Field.get(8)); // 처리여부 + + if (getResCode().equalsIgnoreCase(TelegramKeys.MAGIC_RES_CODE_SUCESS) + && procYn.equalsIgnoreCase("Y")) { + LogUtil.setLogFileEnd(batchDoc); + checkMoreFileinDB(); + }else{ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[1]; + msgArgs[0] = getResCode(); + String errCode = "BECEAIFRS021"; //'기타오류'(응답코드:{1}) 응답전문이 수신되었습니다. + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setLogFileEnd(batchDoc); + } + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// SchedulerMessageVO info; +// try{ +// info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); +// if ( info == null ) { +// return; +// } +// String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); +// String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); +// +// //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 +// SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); +// +// //BatchMsgDoc 값 설정 +// batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); +// batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); +// batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); +// batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); +// batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); +// batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); +// BatchJobInfoVO bjInfo = DirInfoManager.getInstance().getFileInfo(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setRecLen((int)bjInfo.getFileRecSize()); +// batchDoc.getBatchMsg().getHeader().setFileSize(0); +// batchDoc.getBatchMsg().getBody().setCurFileSize(0); +// this.setConditionTxt(""); +// +// } catch ( Exception e){ +// +// } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_ML12X.java b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_ML12X.java new file mode 100644 index 0000000..280088c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/RECV_ML12X.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_ML12X extends DefaultTelegram implements TelegramService +{ + + public RECV_ML12X() { + } + + public boolean doExecute() { + + return true; + } + /** + * RULE의 TelegramType만 가지고, 다음 텔레그램의 ID를 결정한다. + */ + public String getRealRecvTelegram() { + + PhaseInfoVO info = (PhaseInfoVO) this.al_NextStage.get(0); + if ( info == null ) return ""; + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (info.getPhaseSeq() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(info.getTelegramID()); //Stage Logging 용 + return info.getTelegramID(); + } + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_003.java b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_003.java new file mode 100644 index 0000000..423cb48 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_003.java @@ -0,0 +1,191 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_003 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_DAC25_003() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //TR CODE + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType().substring(0,3), this.al_FieldProps[2]); + + //응답코드 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //업무필드 + compileField(4, "", this.al_FieldProps[4]); + + //예비 + compileField(5, "", this.al_FieldProps[5]); + + //송신자 ID + compileField(6, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[6]); + + //송신자 암호 + compileField(7, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[7]); + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + //Job Type + compileField(8, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[8]); + //File Name + compileField(9, "", this.al_FieldProps[9]); + //Flag + compileField(10, "", this.al_FieldProps[10]); + //시작시간 + compileField(11, "", this.al_FieldProps[11]); + //끝시간 + compileField(12, "", this.al_FieldProps[12]); + }else{ + //Job Type + compileField(8, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[8]); + //File Name + compileField(9, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[9]); + //Flag + compileField(10, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[10]); + //시작시간 + compileField(11, "200000000000", this.al_FieldProps[11]); + //끝시간 + compileField(12, TelegramKeys.getYYYYMMDD() + "2400", this.al_FieldProps[12]); + } + + //Password 변경 여부 + compileField(13, "", this.al_FieldProps[13]); + + //New Password + compileField(14, "", this.al_FieldProps[14]); + + //Comm Size + compileField(15, "" +batchDoc.getBatchMsg().getHeader().getPacketSize(), this.al_FieldProps[15]); + + //FILLER + compileField(16, "", this.al_FieldProps[16]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + batchDoc.getBatchMsg().getBody().setErrorMsg(""); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_007.java b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_007.java new file mode 100644 index 0000000..30df00f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_007.java @@ -0,0 +1,181 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_007 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_DAC25_007() { + //LOGOUT 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //TR CODE + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType().substring(0,3), this.al_FieldProps[2]); + + //응답코드 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //업무필드 + compileField(4, "", this.al_FieldProps[4]); + + //예비 + compileField(5, "", this.al_FieldProps[5]); + + //송신자 ID + compileField(6, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[6]); + + //송신자 암호 + compileField(7, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[7]); + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + //Job Type + compileField(8, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[8]); + //File Name + compileField(9, "", this.al_FieldProps[9]); + //Flag + compileField(10, "", this.al_FieldProps[10]); + //시작시간 + compileField(11, "", this.al_FieldProps[11]); + //끝시간 + compileField(12, "", this.al_FieldProps[12]); + }else{ + //Job Type + compileField(8, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[8]); + //File Name + compileField(9, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[9]); + //Flag + compileField(10, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[10]); + //시작시간 + compileField(11, "", this.al_FieldProps[11]); + //끝시간 + compileField(12, "", this.al_FieldProps[12]); + } + + //FILLER + compileField(13, "", this.al_FieldProps[13]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_100.java b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_100.java new file mode 100644 index 0000000..9aee22f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_100.java @@ -0,0 +1,230 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_100 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + private File file; + + /** + * 생성자 + */ + public SEND_DAC25_100() { + //송신 파일 통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + + //길이 필드 + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //TR CODE + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType().substring(0,3), this.al_FieldProps[2]); + + //응답코드 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //업무필드 + compileField(4, "", this.al_FieldProps[4]); + + //예비 + compileField(5, "", this.al_FieldProps[5]); + + //FILE NAME + compileField(6, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[6]); + + //FILE SIZE + compileField(7, ""+calculateFileSize(), this.al_FieldProps[7]); + + //송신자 ID + compileField(8, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[8]); + + //수신자 ID + compileField(9, hdrInfo.substring(48, 58), this.al_FieldProps[9]); + + //FILLER 1 + compileField(10, "", this.al_FieldProps[10]); + + //FILLER 2 + compileField(11, "", this.al_FieldProps[11]); + + //마지막 여부 - 체크 안함 + compileField(12, TelegramKeys.MAGICLINK_END, this.al_FieldProps[12]); + + //전송종류 + compileField(13, TelegramKeys.MAGICLINK_NEW, this.al_FieldProps[13]); + + //FILLER 3 + compileField(14, "", this.al_FieldProps[14]); + + //FILLER 4 + compileField(15, "", this.al_FieldProps[15]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private long calculateFileSize () { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + + long sendFileSize = file.length() + TelegramKeys.MLINK_HEADER_LEN; + this.batchDoc.getBatchMsg().getHeader().setFileSize(sendFileSize); + return sendFileSize; + + } catch (Exception e) { + return 0; + } + } + + /* + private boolean checkMoreFile(){ + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info != null ) { + return true; + } + } catch ( Exception e){ + return false; + } + return false; + } + */ + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_110.java b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_110.java new file mode 100644 index 0000000..db6e459 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_110.java @@ -0,0 +1,176 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_110 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + /** + * 생성자 + */ + public SEND_DAC25_110() { + //송신 파일 통보응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + if ( !calculateSendLength() ) return false; + + //길이 필드 + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //TR CODE + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType().substring(0,3), this.al_FieldProps[2]); + + //응답코드 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //업무필드 + compileField(4, "", this.al_FieldProps[4]); + + //예비 + compileField(5, "", this.al_FieldProps[5]); + + //FILE NAME + compileField(6, batchDoc.getBatchMsg().getHeader().getRenamedFileName(), this.al_FieldProps[6]); + + //FILE SIZE + compileField(7, "" + 0, this.al_FieldProps[7]); + + //송신자 ID + compileField(8, recvTelegramBody.substring(30,50), this.al_FieldProps[8]); + + //수신자 ID + compileField(9, recvTelegramBody.substring(50,70), this.al_FieldProps[9]); + + //FILLER 1 + compileField(10, "", this.al_FieldProps[10]); + + //FILLER 2 + compileField(11, "", this.al_FieldProps[11]); + + //마지막 여부 + compileField(12, recvTelegramBody.substring(81,84), this.al_FieldProps[12]); + + //전송종류 + compileField(13, recvTelegramBody.substring(84,87), this.al_FieldProps[13]); + + //FILLER 3 + compileField(14, "", this.al_FieldProps[14]); + + //FILLER 4 + compileField(15, makeZero(""+batchDoc.getBatchMsg().getHeader().getPacketSize(),4), this.al_FieldProps[15]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_120.java b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_120.java new file mode 100644 index 0000000..47ae6db --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_120.java @@ -0,0 +1,385 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_120 extends DefaultTelegram implements TelegramService +{ +// private Properties jobInfo; + private int REAL_BYTE; // 실 data byte수 + private String filename; + private File file; + private FileInputStream fin ; + private byte[] fileHeader; + private byte[] fileData; + + public SEND_DAC25_120() { // 다른 전문과 달리 전문 번호가 없어 편의상 120번을 부여함 + } + + public boolean doExecute() { + try { + if (!setBlockAndSeqNO()) return false; + //길이 필드 + compileField(0, "" + REAL_BYTE, this.al_FieldProps[0]); + + //<< 전문 완성 + + return true; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPreExecute() { + if (!super.doPreExecute()) return false; + return true; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_BYTE + 4; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + /** + * 여기서는 파일을 닫는다. + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + batchDoc.getBatchMsg().setTelegramHeader(new String((byte[])this.al_Field.get(0))); + batchDoc.getBatchMsg().setTelegramBody(new String(fileData)); + + if ( getConditionTxt().equals(TelegramKeys.EOF)){ + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(file); + + if ( fin != null ) { + fin.close(); + fin = null; + } + logger.info("{} doPostExecute called : file close", logHeader); + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + long totSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + if ( curSize != totSize ){ + logger.debug("[SEND_DAC25_120:doPostExecute]-->" + curSize + "/" + totSize ); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean setBlockAndSeqNO (){ + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + REAL_BYTE = 0; // data 버퍼에 현재까지 채워진 공간 + int bufferSize = batchDoc.getBatchMsg().getHeader().getPacketSize(); // data 버퍼의 크기 + fileData = new byte[bufferSize]; + // // 각 레코드의 크기 +// int newLineByteLen = 1; +// try { +// Properties jobInfo = getJobInfo(); +// newLineByteLen = Integer.parseInt(jobInfo.getProperty(TelegramKeys.MLINK_NEWLINE_LEN)); +// String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); +// if ( hdrInfo.substring(65, 67).equals("LL")){ +// newLineByteLen = Integer.parseInt(hdrInfo.substring(67, 68)); +// } +// } catch (Exception e) {} +// int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); +// byte[] recBuffer = new byte[recSize]; +// for (int inx = 0; inx < recBuffer.length; inx++) { +// recBuffer[inx] = ' '; +// } +// logger.debug("[SEND_DAC25_120]newLineByteLen-->" + newLineByteLen ); +// logger.debug("[SEND_DAC25_120]recSize-->" + recSize ); +// logger.debug("[SEND_DAC25_120]recBuffer.length-->" + recBuffer.length ); +// String fileLine = null; + + if (fileHeader != null ){ + int headerLen = fileHeader.length; + System.arraycopy( fileHeader, 0, fileData, 0, headerLen); + REAL_BYTE = headerLen; + + REAL_BYTE += fin.read(fileData, headerLen, fileData.length - headerLen ); +// file +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= REAL_BYTE; + batchDoc.getBatchMsg().setFileHeader(new String(fileHeader)); + fileHeader = null; +// isFirstRec = true; + }else{ + REAL_BYTE = fin.read(fileData); + +// byte[] sendSum = batchDoc.getBatchMsg().getBody().getSendBuffer(); +// if ( sendSum != null ){ +// System.arraycopy( sendSum, 0, fileData, 0, sendSum.length); +// REAL_BYTE = sendSum.length; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= REAL_BYTE; +// batchDoc.getBatchMsg().getBody().setSendBuffer(null); +// } + } +// while ( bufferSize > 0 ){ +// // 일단 한건 읽어 봅시다. +// fileLine = fbr.readLine(); +// if ( fileLine == null ){ // 읽은게 없으면 빠져 나가고 +// fbr.close(); // 다 읽었으면 포인터를 닫고 +// fbr = null; +// setConditionTxt(TelegramKeys.EOF); +// break; +// } +// +// System.arraycopy( fileLine.getBytes(), 0, recBuffer, 0, Math.min(recSize,fileLine.getBytes().length )); +// switch (newLineByteLen) { +// case 1: +// recBuffer[recSize-1] = '\n'; +// break; +// case 2: +// recBuffer[recSize-2] = '\r'; +// recBuffer[recSize-1] = '\n'; +// break; +// default: +// break; +// } +// +// if ( isFirstRec ){ +// String fileHeader = batchDoc.getBatchMsg().getFileHeader() + new String( recBuffer ); +// batchDoc.getBatchMsg().setFileHeader(fileHeader); +// isFirstRec = false; +// } +// // 한레코드 복사 +// +// if ( bufferSize >= recSize ){ // 남음 버퍼 크기가 레코드 한건 보다 크다면 +// System.arraycopy( recBuffer, 0, fileData, fileData.length - bufferSize, recSize); +// REAL_BYTE += recSize; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= recSize; +// } else { +// System.arraycopy( recBuffer, 0, fileData, fileData.length - bufferSize, bufferSize); +// REAL_BYTE += bufferSize; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// byte[] recBit = new byte[recSize-bufferSize]; +// System.arraycopy( recBuffer, bufferSize, recBit, 0, recSize-bufferSize ); +// batchDoc.getBatchMsg().getBody().setSendBuffer(recBit); +// bufferSize = 0; +// } +// } + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + if ( lnCurSize >= batchDoc.getBatchMsg().getHeader().getFileSize()){ + setConditionTxt(TelegramKeys.EOF); + batchDoc.getBatchMsg().setFileTrailer(new String(fileData)); + } + + return true; + + } catch (Exception ex) { + logger.error("{} ★★★★★ 송신 파일 데이터 READ 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + private boolean createFile() + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fin != null ) return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + int headerLen = TelegramKeys.MLINK_HEADER_LEN; + fileHeader = new byte[headerLen]; + for (int inx = 0; inx < headerLen - 2; inx++) { + fileHeader[inx] = ' '; + } + + // 헤더 구분 : <> + System.arraycopy( "<>".getBytes(), 0, fileHeader, 0, 10); + + // 업무 구분 : 1 + System.arraycopy( "1".getBytes(), 0, fileHeader, 10, 1); + + // 자료 형태 : 텍스트 파일(N), BINARY 파일(B), 압축데이타(C) + // # 자료형태 알수 없음 따라서 항상 N 으로 표시 + System.arraycopy( "N".getBytes(), 0, fileHeader, 11, 1); + + // 파일 크기 : BODY부분의 크기 + String strFileSize = makeZero( "" + ( batchDoc.getBatchMsg().getHeader().getFileSize() - TelegramKeys.MLINK_HEADER_LEN ), 10); + System.arraycopy( strFileSize.getBytes(), 0, fileHeader, 12, 10); + + // 압축후 파일크기 : 압축후의 BODY부분의 크기 + System.arraycopy( strFileSize.getBytes(), 0, fileHeader, 22, 10); + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + // 송신자 ID : 송신자의 ID + System.arraycopy( hdrInfo.getBytes(), 38, fileHeader, 32, 10); + + // 업체 구분: 송신자의 업체구분 코드 + // 정보 구분: BODY의 정보구분 코드 (문서명) + String infoGb = batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( infoGb.getBytes(), 0, fileHeader, 42, 5); + + // 예비 1 바이트 + //String reserve = " "; + //System.arraycopy( reserve.getBytes(), 0, fileHeader, 47, 1); + + // 수신자수 : BODY부분을 수신할 ec-Bank HiVAN ID의 수 + System.arraycopy( "001".getBytes(), 0, fileHeader, 48, 3); + + // 수신자 ID : + System.arraycopy( hdrInfo.getBytes(), 48, fileHeader, 51, 10); + // 레코드 구분자 : CR, LF + fileHeader[headerLen-2] = '\r'; + fileHeader[headerLen-1] = '\n'; + + //요구송신 파일 Start DB로그 + try { + LogUtil.setLogFileStart(batchDoc); + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + this.filename = fileDir+ File.separator + fileNm; + this.file = new File(this.filename); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File does not exist!!! ["+this.filename+"]", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID(),filename, fin ); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI021"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_130.java b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_130.java new file mode 100644 index 0000000..c21294c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dac25/SEND_DAC25_130.java @@ -0,0 +1,165 @@ +package com.eactive.eai.batch.job.jobItem.dac25; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class SEND_DAC25_130 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_DAC25_130() { + //수신확인 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + if ( !calculateSendLength() ) return false; + + //길이 필드 + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //TR CODE + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType().substring(0,3), this.al_FieldProps[2]); + + //응답코드 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //업무필드 + compileField(4, "", this.al_FieldProps[4]); + + //예비 + compileField(5, "", this.al_FieldProps[5]); + + //FILE NAME + compileField(6, batchDoc.getBatchMsg().getHeader().getRenamedFileName(), this.al_FieldProps[6]); + + //FILE SIZE + compileField(7, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[7]); + + //처리여부 + if ( this.getResolveResponseCode().equals(TelegramKeys.MAGIC_RES_CODE_SUCESS)) { + compileField(8, "Y", this.al_FieldProps[8]); + } else { + compileField(8, "N", this.al_FieldProps[8]); + } + + //FILLER + compileField(9, "", this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25.java new file mode 100644 index 0000000..515a833 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25.java @@ -0,0 +1,29 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25 extends DefaultTelegram implements TelegramService +{ + + public RECV_DAC25() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_030.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_030.java new file mode 100644 index 0000000..4b19a87 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_030.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25_030 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_030() { + //LOGIN 응답 + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_070.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_070.java new file mode 100644 index 0000000..031766c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_070.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25_070 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_070() { + //LOGIN 응답 + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_100.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_100.java new file mode 100644 index 0000000..8cbb7e5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_100.java @@ -0,0 +1,137 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.lang.String; +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; + +public class RECV_DAC25_100 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_100() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + String fileName = new String ((byte[]) al_Field.get(5)).substring(0, 5); + String fromId = new String ((byte[]) al_Field.get(7)).trim(); + if ( !fromId.equals("") ){ + fileName = fileName + "_" + fromId; + } + String endGb = new String ((byte[]) al_Field.get(11)); + String bizCode = fileName.substring(0,5); + long fileSize = Long.parseLong(new String ((byte[]) al_Field.get(6))); //화일 size + batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + if ( endGb.equalsIgnoreCase(TelegramKeys.MAGICLINK_END)) { + this.setConditionTxt(TelegramKeys.NOFILE); + } + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + + try { + int recSize = (int)bJobInfo.getFileRecSize(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(fileSize/recSize); + } catch (Exception e) { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + } + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fileName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(new String ((byte[]) al_Field.get(5))); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separator; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + File file = new File(strFullPathName); + if ( file.exists() ){ + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + LogUtil.setLogFileStart(batchDoc); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_110.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_110.java new file mode 100644 index 0000000..d6cceb4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_110.java @@ -0,0 +1,80 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DAC25_110 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_DAC25_110() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_120.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_120.java new file mode 100644 index 0000000..fa795dd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_120.java @@ -0,0 +1,204 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_DAC25_120 extends DefaultTelegram implements TelegramService +{ + private String strFullPathName = ""; + private FileOutputStream fout = null; + + private File rcvRealFile = null; + private File rcvArchFile = null; + private File rcvErrorFile = null; + + public RECV_DAC25_120() { // 다른 전문과 달리 전문 번호가 없어 편의상 120번을 부여함 + } + + public boolean doPreExecute() + { + if (!super.doPreExecute()) return false; + //1. 수신파일 저장 경로 설정 + //저장 디렉토리는 Inbound Server 에서 설정됨 (응답수신 Real 또는 응답송신 Real) + strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separator; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + logger.info("{} 응답수신 파일 저장 경로 : [" + this.strFullPathName + "]", logHeader); + rcvRealFile = new File( this.strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPathName) ); + rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPathName) ); + + //2. 응답수신 파일 생성 + logger.info("{} >>>>> 응답수신 파일 생성...... ("+ this.strFullPathName +")", logHeader); + try { +// boolean append = true; +// if ( batchDoc.getBatchMsg().getBody().getCurFileSize() < 1){ +// append = false; +// } + fout = new FileOutputStream(rcvRealFile, true); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI041", new String[] {rcvRealFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 해당 경로에 생성시 오류가 발생하였습니다. [Path : {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + try { + return Integer.parseInt(new String ((byte[]) al_Field.get(0))); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + //파일 끝에 append + fout.write(data, 0, length); + + //읽어 들인 파일 사이즈 저장 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch (Exception ex) { + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.error("{} ★★★★★ 수신 파일 데이터 WRITE 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //1. 수신 파일 Close =========================================================== + if (fout != null) fout.close(); + + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() < batchDoc.getBatchMsg().getHeader().getFileSize() ){ + return true; + } + + setConditionTxt(TelegramKeys.EOF); + //2. 수신 파일 End DB로그 ====================================================== + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //사이즈 비교 + long recvSize = rcvRealFile.length(); + if ( recvSize != batchDoc.getBatchMsg().getHeader().getFileSize() ){ + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SEND_BYTE_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute]recvSize-->" + recvSize ); + logger.debug(this.getClass().getName() + "[doPostExecute]batchDoc.getBatchMsg().getHeader().getFileSize()-->" + batchDoc.getBatchMsg().getHeader().getFileSize() ); + return false; + } + super.setFileHeaderAndTrailer(rcvRealFile); + } + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) ) { + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + logger.debug(this.getClass().getName() + "[doPostExecute]super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](1)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPathName) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](2)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_130.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_130.java new file mode 100644 index 0000000..18cb461 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_DAC25_130.java @@ -0,0 +1,142 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_DAC25_130 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_DAC25_130() { + //수신확인 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + + String procYn = new String ((byte[]) al_Field.get(7)); // 처리여부 + + if (getResCode().equalsIgnoreCase(TelegramKeys.MAGIC_RES_CODE_SUCESS) + && procYn.equalsIgnoreCase("Y")) { + LogUtil.setLogFileEnd(batchDoc); + checkMoreFileinDB(); + }else{ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[1]; + msgArgs[0] = getResCode(); + String errCode = "BECEAIFRS021"; //'기타오류'(응답코드:{1}) 응답전문이 수신되었습니다. + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setLogFileEnd(batchDoc); + } + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// SchedulerMessageVO info; +// try{ +// info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); +// if ( info == null ) { +// return; +// } +// String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); +// String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); +// +// //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 +// SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); +// +// //BatchMsgDoc 값 설정 +// batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); +// batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); +// batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); +// batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); +// batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); +// batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); +// BatchJobInfoVO bjInfo = DirInfoManager.getInstance().getFileInfo(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setRecLen((int)bjInfo.getFileRecSize()); +// batchDoc.getBatchMsg().getHeader().setFileSize(0); +// batchDoc.getBatchMsg().getBody().setCurFileSize(0); +// this.setConditionTxt(""); +// +// } catch ( Exception e){ +// +// } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_ML12X.java b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_ML12X.java new file mode 100644 index 0000000..5d9ef71 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/RECV_ML12X.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_ML12X extends DefaultTelegram implements TelegramService +{ + + public RECV_ML12X() { + } + + public boolean doExecute() { + + return true; + } + /** + * RULE의 TelegramType만 가지고, 다음 텔레그램의 ID를 결정한다. + */ + public String getRealRecvTelegram() { + + PhaseInfoVO info = (PhaseInfoVO) this.al_NextStage.get(0); + if ( info == null ) return ""; + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (info.getPhaseSeq() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(info.getTelegramID()); //Stage Logging 용 + return info.getTelegramID(); + } + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_003.java b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_003.java new file mode 100644 index 0000000..47230b5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_003.java @@ -0,0 +1,190 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_003 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_DAC25_003() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[6]); + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + }else{ + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[7]); + //File Name +// compileField(8, jobInfo.getProperty(TelegramKeys.MLINK_FILENAME), this.al_FieldProps[8]); + compileField(8, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[8]); + //Flag + compileField(9, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[9]); + //시작시간 + compileField(10, "200000000000", this.al_FieldProps[10]); + //끝시간 + compileField(11, TelegramKeys.getYYYYMMDD() + "2400", this.al_FieldProps[11]); + } + + //Password 변경 여부 + compileField(12, "", this.al_FieldProps[12]); + + //New Password + compileField(13, "", this.al_FieldProps[13]); + + //Comm Size + compileField(14, "" +batchDoc.getBatchMsg().getHeader().getPacketSize(), this.al_FieldProps[14]); + + //FILLER + compileField(15, "", this.al_FieldProps[15]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + batchDoc.getBatchMsg().getBody().setErrorMsg(""); +// jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_007.java b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_007.java new file mode 100644 index 0000000..94a0d99 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_007.java @@ -0,0 +1,181 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_007 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; +// private Properties jobInfo; + + /** + * 생성자 + */ + public SEND_DAC25_007() { + //LOGOUT 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[6]); + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + }else{ + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[7]); + //File Name +// compileField(8, jobInfo.getProperty(TelegramKeys.MLINK_FILENAME), this.al_FieldProps[8]); + compileField(8, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[8]); + //Flag + compileField(9, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + } + + //FILLER + compileField(12, "", this.al_FieldProps[12]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; +// jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_100.java b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_100.java new file mode 100644 index 0000000..10616c2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_100.java @@ -0,0 +1,240 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_100 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + private File file; +// private Properties + /** + * 생성자 + */ + public SEND_DAC25_100() { + //송신 파일 통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); +// try { +// if ( hdrInfo.substring(58, 61).equals("LEN")){ +// int newLen = Integer.parseInt(hdrInfo.substring(61, 65)); +// batchDoc.getBatchMsg().getHeader().setRecLen(newLen); +// } +// } catch (Exception e) {} + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, ""+calculateFileSize(), this.al_FieldProps[6]); + + //송신자 ID + compileField(7, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[7]); + + //수신자 ID + compileField(8, hdrInfo.substring(48, 58), this.al_FieldProps[8]); + + //FILLER 1 + compileField(9, "", this.al_FieldProps[9]); + + //FILLER 2 + compileField(10, "", this.al_FieldProps[10]); + + //마지막 여부 - 체크 안함 + compileField(11, TelegramKeys.MAGICLINK_END, this.al_FieldProps[10]); + + /* + * + if (checkMoreFile()){ + compileField(11, TelegramKeys.MAGICLINK_NEXT, this.al_FieldProps[10]); + }else{ + } + */ + + //전송종류 + compileField(12, TelegramKeys.MAGICLINK_NEW, this.al_FieldProps[12]); + + //FILLER 3 + compileField(13, "", this.al_FieldProps[13]); + + //FILLER 4 + compileField(14, "", this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private long calculateFileSize () { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + + long sendFileSize = file.length() + TelegramKeys.MLINK_HEADER_LEN; + this.batchDoc.getBatchMsg().getHeader().setFileSize(sendFileSize); + return sendFileSize; + + } catch (Exception e) { + return 0; + } + } + + /* + private boolean checkMoreFile(){ + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info != null ) { + return true; + } + } catch ( Exception e){ + return false; + } + return false; + } + */ + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_110.java b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_110.java new file mode 100644 index 0000000..7a19823 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_110.java @@ -0,0 +1,174 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_110 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + /** + * 생성자 + */ + public SEND_DAC25_110() { + //송신 파일 통보응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getRenamedFileName(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, "" + 0, this.al_FieldProps[6]); + + //송신자 ID + compileField(7, recvTelegramBody.substring(30,50), this.al_FieldProps[7]); + + //수신자 ID + compileField(8, recvTelegramBody.substring(50,70), this.al_FieldProps[8]); + + //FILLER 1 + compileField(9, "", this.al_FieldProps[9]); + + //FILLER 2 + compileField(10, "", this.al_FieldProps[10]); + + //마지막 여부 + compileField(11, recvTelegramBody.substring(81,84), this.al_FieldProps[10]); + + //전송종류 + compileField(12, recvTelegramBody.substring(84,87), this.al_FieldProps[12]); + + //FILLER 3 + compileField(13, "", this.al_FieldProps[13]); + + //FILLER 4 + compileField(14, makeZero(""+batchDoc.getBatchMsg().getHeader().getPacketSize(),4), this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_120.java b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_120.java new file mode 100644 index 0000000..bffef99 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_120.java @@ -0,0 +1,386 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DAC25_120 extends DefaultTelegram implements TelegramService +{ +// private Properties jobInfo; + private int REAL_BYTE; // 실 data byte수 + private String filename; + private File file; + private FileInputStream fin ; + private byte[] fileHeader; + private byte[] fileData; + + public SEND_DAC25_120() { // 다른 전문과 달리 전문 번호가 없어 편의상 120번을 부여함 + } + + public boolean doExecute() { + try { + if (!setBlockAndSeqNO()) return false; + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, "" + REAL_BYTE, this.al_FieldProps[0]); + + //<< 전문 완성 + + return true; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPreExecute() { + if (!super.doPreExecute()) return false; + return true; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_BYTE + 4; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + /** + * 여기서는 파일을 닫는다. + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + batchDoc.getBatchMsg().setTelegramHeader(new String((byte[])this.al_Field.get(0))); + batchDoc.getBatchMsg().setTelegramBody(new String(fileData)); + + if ( getConditionTxt().equals(TelegramKeys.EOF)){ + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(file); + + if ( fin != null ) { + fin.close(); + fin = null; + } + logger.info("{} doPostExecute called : file close", logHeader); + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + long totSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + if ( curSize != totSize ){ + logger.debug("[SEND_DAC25_120:doPostExecute]-->" + curSize + "/" + totSize ); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean setBlockAndSeqNO (){ + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } +// boolean isFirstRec = false; + + REAL_BYTE = 0; // data 버퍼에 현재까지 채워진 공간 + int bufferSize = batchDoc.getBatchMsg().getHeader().getPacketSize(); // data 버퍼의 크기 + fileData = new byte[bufferSize]; + // // 각 레코드의 크기 +// int newLineByteLen = 1; +// try { +// Properties jobInfo = getJobInfo(); +// newLineByteLen = Integer.parseInt(jobInfo.getProperty(TelegramKeys.MLINK_NEWLINE_LEN)); +// String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); +// if ( hdrInfo.substring(65, 67).equals("LL")){ +// newLineByteLen = Integer.parseInt(hdrInfo.substring(67, 68)); +// } +// } catch (Exception e) {} +// int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); +// byte[] recBuffer = new byte[recSize]; +// for (int inx = 0; inx < recBuffer.length; inx++) { +// recBuffer[inx] = ' '; +// } +// logger.debug("[SEND_DAC25_120]newLineByteLen-->" + newLineByteLen ); +// logger.debug("[SEND_DAC25_120]recSize-->" + recSize ); +// logger.debug("[SEND_DAC25_120]recBuffer.length-->" + recBuffer.length ); +// String fileLine = null; + + if (fileHeader != null ){ + int headerLen = fileHeader.length; + System.arraycopy( fileHeader, 0, fileData, 0, headerLen); + REAL_BYTE = headerLen; + + REAL_BYTE += fin.read(fileData, headerLen, fileData.length - headerLen ); +// file +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= REAL_BYTE; + batchDoc.getBatchMsg().setFileHeader(new String(fileHeader)); + fileHeader = null; +// isFirstRec = true; + }else{ + REAL_BYTE = fin.read(fileData); + +// byte[] sendSum = batchDoc.getBatchMsg().getBody().getSendBuffer(); +// if ( sendSum != null ){ +// System.arraycopy( sendSum, 0, fileData, 0, sendSum.length); +// REAL_BYTE = sendSum.length; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= REAL_BYTE; +// batchDoc.getBatchMsg().getBody().setSendBuffer(null); +// } + } +// while ( bufferSize > 0 ){ +// // 일단 한건 읽어 봅시다. +// fileLine = fbr.readLine(); +// if ( fileLine == null ){ // 읽은게 없으면 빠져 나가고 +// fbr.close(); // 다 읽었으면 포인터를 닫고 +// fbr = null; +// setConditionTxt(TelegramKeys.EOF); +// break; +// } +// +// System.arraycopy( fileLine.getBytes(), 0, recBuffer, 0, Math.min(recSize,fileLine.getBytes().length )); +// switch (newLineByteLen) { +// case 1: +// recBuffer[recSize-1] = '\n'; +// break; +// case 2: +// recBuffer[recSize-2] = '\r'; +// recBuffer[recSize-1] = '\n'; +// break; +// default: +// break; +// } +// +// if ( isFirstRec ){ +// String fileHeader = batchDoc.getBatchMsg().getFileHeader() + new String( recBuffer ); +// batchDoc.getBatchMsg().setFileHeader(fileHeader); +// isFirstRec = false; +// } +// // 한레코드 복사 +// +// if ( bufferSize >= recSize ){ // 남음 버퍼 크기가 레코드 한건 보다 크다면 +// System.arraycopy( recBuffer, 0, fileData, fileData.length - bufferSize, recSize); +// REAL_BYTE += recSize; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= recSize; +// } else { +// System.arraycopy( recBuffer, 0, fileData, fileData.length - bufferSize, bufferSize); +// REAL_BYTE += bufferSize; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// byte[] recBit = new byte[recSize-bufferSize]; +// System.arraycopy( recBuffer, bufferSize, recBit, 0, recSize-bufferSize ); +// batchDoc.getBatchMsg().getBody().setSendBuffer(recBit); +// bufferSize = 0; +// } +// } + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + if ( lnCurSize >= batchDoc.getBatchMsg().getHeader().getFileSize()){ + setConditionTxt(TelegramKeys.EOF); + batchDoc.getBatchMsg().setFileTrailer(new String(fileData)); + } + + return true; + + } catch (Exception ex) { + logger.error("{} ★★★★★ 송신 파일 데이터 READ 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + private boolean createFile() + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fin != null ) return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + int headerLen = TelegramKeys.MLINK_HEADER_LEN; + fileHeader = new byte[headerLen]; + for (int inx = 0; inx < headerLen - 2; inx++) { + fileHeader[inx] = ' '; + } + + // 헤더 구분 : <> + System.arraycopy( "<>".getBytes(), 0, fileHeader, 0, 10); + + // 업무 구분 : 1 + System.arraycopy( "1".getBytes(), 0, fileHeader, 10, 1); + + // 자료 형태 : 텍스트 파일(N), BINARY 파일(B), 압축데이타(C) + // # 자료형태 알수 없음 따라서 항상 N 으로 표시 + System.arraycopy( "N".getBytes(), 0, fileHeader, 11, 1); + + // 파일 크기 : BODY부분의 크기 + String strFileSize = makeZero( "" + ( batchDoc.getBatchMsg().getHeader().getFileSize() - TelegramKeys.MLINK_HEADER_LEN ), 10); + System.arraycopy( strFileSize.getBytes(), 0, fileHeader, 12, 10); + + // 압축후 파일크기 : 압축후의 BODY부분의 크기 + System.arraycopy( strFileSize.getBytes(), 0, fileHeader, 22, 10); + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + // 송신자 ID : 송신자의 ID + System.arraycopy( hdrInfo.getBytes(), 38, fileHeader, 32, 10); + + // 업체 구분: 송신자의 업체구분 코드 + // 정보 구분: BODY의 정보구분 코드 (문서명) + String infoGb = batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( infoGb.getBytes(), 0, fileHeader, 42, 5); + + // 예비 1 바이트 + //String reserve = " "; + //System.arraycopy( reserve.getBytes(), 0, fileHeader, 47, 1); + + // 수신자수 : BODY부분을 수신할 ec-Bank HiVAN ID의 수 + System.arraycopy( "001".getBytes(), 0, fileHeader, 48, 3); + + // 수신자 ID : + System.arraycopy( hdrInfo.getBytes(), 48, fileHeader, 51, 10); + // 레코드 구분자 : CR, LF + fileHeader[headerLen-2] = '\r'; + fileHeader[headerLen-1] = '\n'; + + //요구송신 파일 Start DB로그 + try { + LogUtil.setLogFileStart(batchDoc); + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + this.filename = fileDir+ File.separator + fileNm; + this.file = new File(this.filename); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File does not exist!!! ["+this.filename+"]", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID(),filename, fin ); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI021"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_130.java b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_130.java new file mode 100644 index 0000000..3b31088 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/dacom/SEND_DAC25_130.java @@ -0,0 +1,163 @@ +package com.eactive.eai.batch.job.jobItem.dacom; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class SEND_DAC25_130 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_DAC25_130() { + //수신확인 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getRenamedFileName(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[6]); + + //처리여부 + if ( this.getResolveResponseCode().equals(TelegramKeys.MAGIC_RES_CODE_SUCESS)) { + compileField(7, "Y", this.al_FieldProps[7]); + } else { + compileField(7, "N", this.al_FieldProps[7]); + } + + //FILLER + compileField(8, "", this.al_FieldProps[8]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT.java b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT.java new file mode 100644 index 0000000..451eec3 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT.java @@ -0,0 +1,75 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DEBIT extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 직불카드망 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_DEBIT() { + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(3).equalsIgnoreCase("0600") ||super.getFieldValueString(3).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(9); + } + else { + return super.getOpCode(); + } + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of recv data length [" + byte_size + "]", logHeader); + int tot_byte_size = Integer.parseInt(byte_size); + + int read_byte_size = 0; + + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + logger.info("{} he sum of definite field length [" + (tot_byte_size- read_byte_size) + "]", logHeader); + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0310.java b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0310.java new file mode 100644 index 0000000..c1f153d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0310.java @@ -0,0 +1,242 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_DEBIT_0310 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_DEBIT_0310() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (((recv_block_no - block_no) > 1 ) || ((recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + return false; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0320.java b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0320.java new file mode 100644 index 0000000..21ea515 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0320.java @@ -0,0 +1,394 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_DEBIT_0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; + + /** + * 생성자 + */ + public RECV_DEBIT_0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + String fName = new String ((byte[]) al_Field.get(4)); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bJobInfo.getFileRecSize()); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (( recv_block_no != 9999 ) && ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if (recLen < 10 ){ + recLen = bout.toByteArray().length; + } + byte[] recvData = new byte[recLen]; + for (int inx = 0; inx < recvData.length; inx++) { + recvData[inx] = ' '; + } + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + System.arraycopy(bout.toByteArray(), 0, recvData, 0, Math.min(recLen, bout.toByteArray().length)); + fout.write( recvData ); + fout.write(newLine); + fout.close(); +// logger.debug("VAN TEST HEADER\n" + CommonLib.getDumpMessage(bout.toByteArray())); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + try { + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode); + batchDoc.getBatchMsg().getHeader().setRecLen((int)info.getFileRecSize()); + } catch (Exception e) { // 에러가 나도 아무것도 안함 + // do nothing + } + +// batchDoc.getBatchMsg().getHeader().setFileSize( Integer.parseInt(new String(bout.toByteArray()).substring(23,30)) * batchDoc.getBatchMsg().getHeader().getRecLen()); +// int recCnt = (int)batchDoc.getBatchMsg().getHeader().getFileSize()/batchDoc.getBatchMsg().getHeader().getRecLen(); +// batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + System.arraycopy(bout.toByteArray(), 0, recvData, 0, Math.min(recLen, bout.toByteArray().length)); + fout.write( recvData ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); +// logger.debug("VAN TEST TRAILER\n" + CommonLib.getDumpMessage(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ + // 강제 결번 세팅 +// } else if ((recv_block_no > 0) && ( recv_seq_no%30 != 5 ) ){ + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.KFB_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0330.java b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0330.java new file mode 100644 index 0000000..1577921 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0330.java @@ -0,0 +1,144 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class RECV_DEBIT_0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_DEBIT_0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(8).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + + } else if (super.getFieldValueString(8).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0600.java b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0600.java new file mode 100644 index 0000000..ee7bd76 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0600.java @@ -0,0 +1,175 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_DEBIT_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_DEBIT_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKJJ_RET_CODE_TEL_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(4)); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0610.java b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0610.java new file mode 100644 index 0000000..894f452 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0610.java @@ -0,0 +1,167 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DEBIT_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_DEBIT_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_all_end)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKJJ_RET_CODE_TEL_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0620.java b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0620.java new file mode 100644 index 0000000..4ca8654 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/RECV_DEBIT_0620.java @@ -0,0 +1,174 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_DEBIT_0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_DEBIT_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(8)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(9)); // 0 base 인덱스 + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + if ( block_no > 1 && block_no > recv_block_no ){ + this.setConditionTxt("IGNORE"); + }else{ + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + } + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0300.java b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0300.java new file mode 100644 index 0000000..5521515 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0300.java @@ -0,0 +1,403 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DEBIT_0300 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_DEBIT_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : EAI에서 정의 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //은행코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : VAN사 송신, B : 은행 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 0 과 VAN구분 코 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, "" + batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, "" + this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[9]); + + //결번갯수 + compileField(10, "" + MISSING_COUNT, this.al_FieldProps[10]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (MISSING_COUNT==0) { + fout.close(); + //블럭 번호를 증가 + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum() + 1; + batchDoc.getBatchMsg().getBody().setBlockNum(block_no); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return MISSING_FIELD.length(); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[block_size]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0310.java b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0310.java new file mode 100644 index 0000000..ab4bce4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0310.java @@ -0,0 +1,333 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DEBIT_0310 extends DefaultTelegram implements TelegramService { + + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_DEBIT_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : EAI에서 정의 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //은행코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : VAN사 송신, B : 은행 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 0 과 VAN구분 코 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+SEQUENCE_NO , this.al_FieldProps[9]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0320.java b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0320.java new file mode 100644 index 0000000..d427e71 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0320.java @@ -0,0 +1,472 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_DEBIT_0320 extends DefaultTelegram implements TelegramService { + + private FileInputStream fin; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_DEBIT_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : EAI에서 정의 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //은행코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : VAN사 송신, B : 은행 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 0 과 VAN구분 코 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(10, "" + recCnt, this.al_FieldProps[10]); + + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num > 0 && block_num < 9999) { + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (fin != null ) { + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean createFile () + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int BLOCK_NO = 0; + int SEQUENCE_NO = 0; + int sequence_size = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + + this.setConditionTxt(""); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[recLen]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + fileData = new byte[recLen]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + + // 전송내역 추가 + String sendSum = batchDoc.getBatchMsg().getBody().getSendSummary(); + if (sendSum == null ){ + sendSum = "01" + + batchDoc.getBatchMsg().getHeader().getBizCode().substring(4,6) + + makeZero( "" + ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() - 2), 7 ) ; + } else { + int sendedFileCnt = Integer.parseInt(sendSum.substring(0,2)); + sendSum = makeZero( "" + ( sendedFileCnt + 1), 2 ) + + sendSum.substring(2, 2 + 9*sendedFileCnt) + + batchDoc.getBatchMsg().getHeader().getBizCode().substring(4,6) + + makeZero( "" + ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() - 2), 7 ) ; + } + batchDoc.getBatchMsg().getBody().setSendSummary(sendSum); + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + BLOCK_NO = block_no+1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + BLOCK_NO = block_no; + SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( sequence_size / recLen ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / recLen; + + if ( seqCnt < remainCnt - 1){ + REAL_BYTE = seqCnt * recLen; + }else{ + REAL_BYTE = (int)(remainCnt - 1) * recLen; + } + int readCnt = REAL_BYTE / recLen; + if ( remainCnt - readCnt <= 1 ) { + this.setConditionTxt(TelegramKeys.EOF); + } + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + REAL_BYTE = fileData.length; + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0330.java b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0330.java new file mode 100644 index 0000000..44029bb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0330.java @@ -0,0 +1,299 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DEBIT_0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_DEBIT_0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + recvTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + + REAL_BYTE = recvTelegramBody.getBytes().length - 11; + + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : EAI에서 정의 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //은행코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : VAN사 송신, B : 은행 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 0 과 VAN구분 코 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + //“S”: 파일 송신업무 관련 전문 (VAN → KB) + //“R”: 파일 수신업무 관련 전문 (KB → VAN) + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, recvTelegramBody.substring(1,5), this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, recvTelegramBody.substring(5,8), this.al_FieldProps[9]); + + //Record 수 + compileField(10, recvTelegramBody.substring(8,11), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(8)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + batchDoc.getBatchMsg().getHeader().setFileSize( lnCurSize ); + int recCnt = (int)batchDoc.getBatchMsg().getHeader().getFileSize()/batchDoc.getBatchMsg().getHeader().getRecLen(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + } else if ( recv_block_no == 9999 ) { + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + System.arraycopy(recvTelegramBody.getBytes(), 11, data, 0, REAL_BYTE ); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0600.java b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0600.java new file mode 100644 index 0000000..386fea6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0600.java @@ -0,0 +1,295 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DEBIT_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + //private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_all_end = "004"; //개별업무 종료 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_DEBIT_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : EAI에서 정의 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //은행코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + String bizGubunCode = null; + if ( this.getFldOpCode().equals(OpCode_start)){ + bizGubunCode = batchDoc.getBatchMsg().getHeader().getBizCode().subSequence(0,4) + "00"; + }else{ + bizGubunCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + } + compileField(4, bizGubunCode, this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : VAN사 송신, B : 은행 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 0 과 VAN구분 코 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + + //전문 전송일시 MMDDHHMMSS 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(10, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[10]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(11, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[11]); + + //송신 집계 내역 + boolean skip_sum = false; + try { + if ( telegramInfo.getProperty(TelegramKeys.SKIP_SUMMARY).indexOf("Y") > -1 ){ + skip_sum = true; + } + } catch (Exception e) {} + + if ( skip_sum ){ + compileField(12, makeZero("", this.al_Field.get(12).length), this.al_FieldProps[12]); + }else{ + if ( OpCode_unit_end.equals(getFldOpCode())) { + compileField(12, batchDoc.getBatchMsg().getBody().getSendSummary(), this.al_FieldProps[12]); + }else if ( OpCode_all_end.equals(getFldOpCode())){ + logger.debug("[SEND_DEBIT_0600]batchDoc.getBatchMsg().getHeader().getBizCode()-->" + batchDoc.getBatchMsg().getHeader().getBizCode()); + logger.debug("[SEND_DEBIT_0600]batchDoc.getBatchMsg().getBody().getSendSummary()-->" + batchDoc.getBatchMsg().getBody().getSendSummary()); + compileField(12, "01" + batchDoc.getBatchMsg().getHeader().getBizCode().substring(0, 2)+ "00" + batchDoc.getBatchMsg().getBody().getSendSummary().substring(0,2), this.al_FieldProps[12]); + }else{ + compileField(12, "", this.al_FieldProps[12]); + } + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // 맨 마지막 XX 필드는 수신 버퍼 처리용이므로 보내는 경우에는 계산하지 않음 2009.09.10 dhjeong + for (int i=1; i< this.al_Field.size() - 1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size() - 1); + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int dLen = getCalculatedLength(idx); + if (dLen > 0) { + for (int inx = 0; inx < data.length; inx++) { + data[inx] = ' '; + } + return dLen; + }else{ + return 0; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + return Integer.parseInt(getTelegramInfo().getProperty(TelegramKeys.FILLER_LEN_0600)); + } catch (Exception e) { + return 0; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0610.java b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0610.java new file mode 100644 index 0000000..f1aa820 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0610.java @@ -0,0 +1,247 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DEBIT_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_DEBIT_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + + //전문송신 Byte 수 : EAI에서 정의 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //은행코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : VAN사 송신, B : 은행 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 0 과 VAN구분 코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + compileField(7, recvTelegramBody.substring(0,1), this.al_FieldProps[7]); + + //전문 전송일시 MMDDHHMMSS 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(8, recvTelegramBody.substring(1,11), this.al_FieldProps[8]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “004”: 전업무종료 요구/요구응답 + compileField(9, recvTelegramBody.substring(11,14), this.al_FieldProps[9]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(10, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[10]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(11, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[11]); + + //송신 집계 내역 +// compileField(12, recvTelegramBody.substring(42), this.al_FieldProps[12]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return 0; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0620.java b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0620.java new file mode 100644 index 0000000..847a1f5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/debit/SEND_DEBIT_0620.java @@ -0,0 +1,235 @@ +package com.eactive.eai.batch.job.jobItem.debit; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_DEBIT_0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_DEBIT_0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전문송신 Byte 수 : EAI에서 정의 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - FTP + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //은행코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 + compileField(4, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[4]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + // C : VAN사 송신, B : 은행 송신 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]); + + //응답코드 0 과 VAN구분 코 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + // 여기 까지 공통부 + + //송수신 업무 구분코드. + compileField(7, getFldTrClass() , this.al_FieldProps[7]); + + //Block-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[8]); + + //Sequence-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[9]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<7; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=7; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // 맨 마지막 XX 필드는 수신 버퍼 처리용이므로 보내는 경우에는 계산하지 않음 2009.09.10 dhjeong + for (int i=1; i< this.al_Field.size() -1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 1 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + return 0; + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return 0; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(7); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC.java new file mode 100644 index 0000000..a51b231 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC.java @@ -0,0 +1,70 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FIUSC extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 금융정보분석원 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_FIUSC() { + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(6); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + int llLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + llLength = ((byte[])this.al_Field.get(idx-1)).length; + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i = 0; organList != null && i < organList.size(); i++) { + OutsideVO organInfo = organList.get(i); + if (institutionCode.equals(organInfo.getOsdCode())) { + bizCodeStartIndex = organInfo.getBizCdStartIdx(); + bizCodeEndIndex = organInfo.getBizCdEndIdx(); + break; + } + } + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + batchDoc.getBatchMsg().getHeader().setFileName(fileName); + batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + this.getSeparator(); + } + String fileFullName = fileDir + fileName; + File file = new File(fileFullName); + if (file.exists()) file.delete(); + + // 초기화 + batchDoc.getBatchMsg().getBody().setCurFileSize(0L); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + String hashLength = new String ((byte[]) al_Field.get(19)); // 레코드길이(4) 기본값 "0001" + + // Byte거래 이므로 레코드길이(4) 기본값이 "0001"인데, 송신 테스트를 위해 전자서명 데이터 byte 길이 입력 + String byte_size = hashLength.equals("0001") ? "0" : hashLength; //전자서명 PEM DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + + try { + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + // 전자서명 비정형데이터 수신확인 + logger.debug("{} doInformalField >> received e-Sign Hash Data : "+new String(bout.toByteArray()), logHeader); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size()-1; i++) { // 전자서명 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0303.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0303.java new file mode 100644 index 0000000..ab0c7da --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0303.java @@ -0,0 +1,215 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +public class RECV_FIUSC_0303 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 13; + + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_FIUSC_0303() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + // RTN_CD 비정상 거래에 대한 결번테스트 시 사용되는 거래번호 Counting +// batchDoc.getBatchMsg().getHeader().setRecLen(batchDoc.getBatchMsg().getHeader().getRecLen()+1); + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no.trim()); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no.trim()); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + String byte_size = new String ((byte[]) al_Field.get(12)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + + try { + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0304.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0304.java new file mode 100644 index 0000000..4153bbc --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0304.java @@ -0,0 +1,84 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class RECV_FIUSC_0304 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_FIUSC_0304() { + //파일 확인 요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0305.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0305.java new file mode 100644 index 0000000..284cdbf --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0305.java @@ -0,0 +1,83 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class RECV_FIUSC_0305 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_FIUSC_0305() { + //파일 확인 요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0312.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0312.java new file mode 100644 index 0000000..0aab82d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0312.java @@ -0,0 +1,83 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FIUSC_0312 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_FIUSC_0312() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + //응답수신 파일 Start DB로그 + LogUtil.setLogFileStart(batchDoc); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0314.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0314.java new file mode 100644 index 0000000..0c303f1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0314.java @@ -0,0 +1,115 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FIUSC_0314 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_FIUSC_0314() { + //파일 확인 응답 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + String rtn_cd = new String ((byte[]) al_Field.get(10)); + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + if (rtn_cd.equals("00")) { + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() <= batchDoc.getBatchMsg().getBody().getCurFileSize()){ + this.setConditionTxt(TelegramKeys.EOF); + } + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + + } else { + // 이전에 송신한 최초 시퀀스 찾아 내어 시퀀스 번호 다시 세팅 + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + for ( int inx=0; inx < seq_no; inx++){ + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + byte[] data = block_data.get(inx); + if ( data != null ){ + batchDoc.getBatchMsg().getBody().setSeqNum(inx); + batchDoc.getBatchMsg().getBody().setCurFileSize(inx*batchDoc.getBatchMsg().getHeader().getSequenceSize()); + break; + } + } + } + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0315.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0315.java new file mode 100644 index 0000000..b7a54a0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0315.java @@ -0,0 +1,154 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FIUSC_0315 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_FIUSC_0315() { + //파일 종료 응답 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + // 수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + // 다음 파일거래를 위해 배치메시지 초기화 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0L); + + // 작업대기 큐에 다음 거래파일이 없으면 업무종료 + if ( checkMoreFile() ) { + this.setConditionTxt(""); + } else { + this.setConditionTxt(TelegramKeys.NOFILE); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + private boolean checkMoreFile(){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return false; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + // info에는 userId에 대한 정보가 없다. 기존의 값을 그래도 사용한다. +// batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + + // 다음 파일의 체크 파일 가져오기 + if ( info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) || + info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND ) ){ + String hdrInfoName = info.getHdrInfoName(); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt()); + } + } catch ( Exception e){ + return false; + + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0610.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0610.java new file mode 100644 index 0000000..772a662 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0610.java @@ -0,0 +1,73 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FIUSC_0610 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_FIUSC_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0640.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0640.java new file mode 100644 index 0000000..cc31774 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/RECV_FIUSC_0640.java @@ -0,0 +1,84 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FIUSC_0640 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_FIUSC_0640() { + //업무종료요구 및 응답(0600/0040, 0610/0040) + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + + // 20250827 org 파일을 삭제한다. + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + File filePath = new File(fileDir); + for (File listFile : filePath.listFiles()) { + if (listFile.getName().endsWith(".org")) listFile.delete(); + } + logger.debug("RECV_FIUSC_0640 .org File Delete"); + + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0302.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0302.java new file mode 100644 index 0000000..c21f4cf --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0302.java @@ -0,0 +1,506 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0302 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + private int HASH_LENGTH; //전자서명 HASH data byte수 + private String HASH_LENGTH_INFO; //전자서명 HASH data byte수 (4byte String) + + private Properties telegramInfo; + + private String fileHeaderInfo; //송신파일 헤더정보(106byte) + private byte[] fileTrailerInfo; //송신파일 암호화데이터 전자서명정보(100byte~가변) + + /** + * 생성자 + */ + public SEND_FIUSC_0302() { + //파일 시작 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + //Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + //기관코드(6) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID(20) + byte[] userId = new byte[20]; + Arrays.fill(userId, (byte)' '); + + // checked file에서 가져온 사용자 ID + String checkedFileUserId = fileHeaderInfo.substring(SEND_FIUSC_HEAD.USER_ID.getStrPos(),SEND_FIUSC_HEAD.USER_ID.getEndPos()); + System.arraycopy(checkedFileUserId.getBytes(), 0, userId, 0, Math.min(checkedFileUserId.getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드 + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //문서종류코드(6) + compileField(++i, fileHeaderInfo.substring(SEND_FIUSC_HEAD.DOC_CODE.getStrPos(),SEND_FIUSC_HEAD.DOC_CODE.getEndPos()), this.al_FieldProps[i]); + + //보고메시지유형코드(2) + compileField(++i, fileHeaderInfo.substring(SEND_FIUSC_HEAD.MSG_GBN_CD.getStrPos(),SEND_FIUSC_HEAD.MSG_GBN_CD.getEndPos()), this.al_FieldProps[i]); + + //문서번호(17) + compileField(++i, fileHeaderInfo.substring(SEND_FIUSC_HEAD.DOC_NO.getStrPos(),SEND_FIUSC_HEAD.DOC_NO.getEndPos()), this.al_FieldProps[i]); + + //보고일자(8) + compileField(++i, fileHeaderInfo.substring(SEND_FIUSC_HEAD.DOC_DATETIME.getStrPos(),SEND_FIUSC_HEAD.DOC_DATETIME.getEndPos()), this.al_FieldProps[i]); + + //종전문서번호(17) + compileField(++i, fileHeaderInfo.substring(SEND_FIUSC_HEAD.PRE_DOC_NO.getStrPos(),SEND_FIUSC_HEAD.PRE_DOC_NO.getEndPos()), this.al_FieldProps[i]); + + //보고파일명(40) + compileField(++i, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[i]); + + //거래순번(15) + compileField(++i, fileHeaderInfo.substring(SEND_FIUSC_HEAD.TGRA_SEQ.getStrPos(),SEND_FIUSC_HEAD.TGRA_SEQ.getEndPos()), this.al_FieldProps[i]); + + //기본보고문서번호(17) + compileField(++i, fileHeaderInfo.substring(SEND_FIUSC_HEAD.DEF_DOC_NO.getStrPos(),SEND_FIUSC_HEAD.DEF_DOC_NO.getEndPos()), this.al_FieldProps[i]); + + //중계기관코드(6) + compileField(++i, telegramInfo.getProperty(TelegramKeys.FIUSC_EAI_CD), this.al_FieldProps[i]); + + //레코드 길이(4) + if (telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE).startsWith("D")) { + compileField(++i, "0001", this.al_FieldProps[i]); + } else { + compileField(++i, HASH_LENGTH_INFO, this.al_FieldProps[i]); // Local 테스트용 (응답수신에서 전자서명(가변) 길이값으로 사용됨 + } + + //압축사용여부(1) + String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String compGb = "0"; + if ( ( renamedFileName.indexOf(".ZIP_") > -1 ) || ( renamedFileName.indexOf(".zip_")) > -1 ){ + compGb = "2"; + } + if ( renamedFileName.indexOf(".Z_") > -1 ){ + compGb = "1"; + } + compileField(++i, compGb, this.al_FieldProps[i]); + + //파일 전체 크기(10) + compileField(++i, ""+ calculateFileSize(), this.al_FieldProps[i]); + + //전자서명데이터(가변) +// compileField(++i, fileTrailerInfo, this.al_FieldProps[i]); // 가변데이터는 공통(SEND1)에서 별도처리 + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + private long calculateFileSize () { + + long length = 0L; + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + this.getSeparator(); + } + + String fileName = fileDir + fileNm; + try { + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + length = file.length(); + + //EMS 송수신파일관리 헤더 및 트레일러 크기만큼 송신파일에서 파싱하여 설정 +// super.setFileHeaderAndTrailer(file); + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + } + if (length < 0) { + return 0; + } + this.batchDoc.getBatchMsg().getHeader().setFileSize(length); + return length; + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return HASH_LENGTH; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < HASH_LENGTH) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + //data = fileData; + ByteArrayInputStream bin = new ByteArrayInputStream(fileTrailerInfo); + bin.read(data, 0, HASH_LENGTH); + + return HASH_LENGTH; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + //송신파일 0~100byte 파싱하여 document FileHeader에 설정 + //송신파일 100byte~전자서명Hash 길이 파싱하여 document FileTailer에 설정 + if (this.batchDoc.getBatchMsg().getHeader().getRuleCode().equals("FIU01")) { + HashMap fileInfoMap = getFileInfo(); + fileHeaderInfo = fileInfoMap.get("fileHeaderInfo").toString(); //송신파일 헤더정보(100byte) + fileTrailerInfo = (byte[])fileInfoMap.get("fileTrailerInfo"); //송신파일 암호화데이터 전자서명정보(100byte~가변) + HASH_LENGTH_INFO = fileHeaderInfo.substring(SEND_FIUSC_HEAD.HASH_SIZE.getStrPos(),SEND_FIUSC_HEAD.HASH_SIZE.getEndPos()); + HASH_LENGTH = Integer.valueOf(HASH_LENGTH_INFO); + + this.batchDoc.getBatchMsg().setFileHeader(fileHeaderInfo); + this.batchDoc.getBatchMsg().setFileTrailer(new String(fileTrailerInfo)); + } + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + private boolean calculateSendLength() { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += HASH_LENGTH; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + private HashMap getFileInfo() { + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + this.getSeparator(); + } + + HashMap fileInfo = new HashMap(); + + String fileName = fileDir + fileNm; + String orgFileName = fileName + ".org"; + + try { + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + + //InputStream ios = null;// 20250910 npe + InputStream ioss = null; + FileOutputStream fos = null; + + File orgFile = new File(orgFileName); // 20250825 // 원본 파일 + try { + // 전송파일에서 .chk 파일에서 헤더정보 추출 + String headerInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + headerInfo = headerInfo.substring(38); + fileInfo.put("fileHeaderInfo", headerInfo); + + // 재전송을 위해 원본파일(전송정보(100byte)길이 + 전자서명길이(가변) + 데이터(가변)) Copy + byte[] copyBuffer = new byte[1024]; + ioss = new FileInputStream(file); + + //File orgFile = new File(orgFileName);// 20250825 + + if (!orgFile.exists()) {// 20250825 ogr 파일이 있으면 새로 만들지 않는다 - 재전송을 위해 + fos = new FileOutputStream(orgFile); + + int copyLength; + while ((copyLength = ioss.read(copyBuffer)) > 0) { + fos.write(copyBuffer, 0, copyLength); + } + } + } finally { + try { + //if (ios != null) ios.close(); + if (ioss != null) ioss.close(); + if (fos != null) fos.close(); + } catch (IOException ioe) { + logger.debug(ioe.getMessage(),ioe); + } + } + + //암호화데이터 전자서명 Hash값 길이(4byte) + String fileHeaderInfo = fileInfo.get("fileHeaderInfo").toString(); + int encHashLength = Integer.valueOf(fileHeaderInfo.substring(SEND_FIUSC_HEAD.HASH_SIZE.getStrPos(),SEND_FIUSC_HEAD.HASH_SIZE.getEndPos())); + + File sourceFile = orgFile.exists() ? orgFile : file; // 읽기용 // 20250825 + File targetFile = new File(fileName); // 20250825 + + RandomAccessFile randomFile = null; + try { + //randomFile = new RandomAccessFile(fileName,"r"); + randomFile = new RandomAccessFile(sourceFile,"r");// 20250825 - 재전송을 위해 원본파일로 생성한다. + + // 전송파일에서 암호화데이터 전자서명 Hash값을 헤더정보의 길이값만큼 파싱하여 전자서명정보 추출 + byte[] hashBytes = new byte[encHashLength]; + randomFile.readFully(hashBytes); + + fileInfo.put("fileTrailerInfo", hashBytes); + + // 전자서명길이(가변) byte 제외하고 데이터만 전송파일에 다시 저장 + randomFile.seek(encHashLength); + byte[] dataBytes = new byte[(int)randomFile.length()-(encHashLength)]; + randomFile.readFully(dataBytes); + + //fos = new FileOutputStream(file); + fos = new FileOutputStream(targetFile);// 20250825 - 재전송을 위해 + fos.write(dataBytes); + + } finally { + try { + if (randomFile != null) randomFile.close(); + if (fos != null) fos.close(); + } catch (IOException ioe) { + logger.debug(ioe.getMessage(),ioe); + } + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + } + + return fileInfo; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0303.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0303.java new file mode 100644 index 0000000..8185b66 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0303.java @@ -0,0 +1,419 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0303 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private File file; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_FIUSC_0303() { + //파일 데이터 송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setData(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + // 시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID + byte[] userId = new byte[20]; + Arrays.fill(userId, (byte)' '); + + // checked file에서 가져온 사용자 ID + String fileHeaderInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + fileHeaderInfo = fileHeaderInfo.substring(38); + String checkedFileUserId = fileHeaderInfo.substring(SEND_FIUSC_HEAD.USER_ID.getStrPos(),SEND_FIUSC_HEAD.USER_ID.getEndPos()); + System.arraycopy(checkedFileUserId.getBytes(), 0, userId, 0, Math.min(checkedFileUserId.getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //시퀀스번호 + compileField(++i, ""+SEQUENCE_NO, this.al_FieldProps[i]); + + //기송신 크기 + compileField(++i, ""+(batchDoc.getBatchMsg().getBody().getCurFileSize()- REAL_BYTE), this.al_FieldProps[i]); + + //실 DATA BYTE 수 + compileField(++i, ""+REAL_BYTE, this.al_FieldProps[i]); + + //<< XX를 제외한 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + //data = fileData; + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return -1; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정현 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + this.getSeparator(); + } + + String fileName = fileDir + fileNm; + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( fin == null) { + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + logger.info("{} File [" + file.getName() + "] Size =" + file.length(), logHeader); + + return true; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + } + + private boolean setData () + { + try { + if (!createFile()) { + logger.info("{} file open failed", logHeader); + return false; + } + + int sequence_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + SEQUENCE_NO = seq_no + 1; + + // 블럭 크기에 도달하면 BLOCKEND 하여 다음 03000040전문으로 넘어가게 함 + if (( this.SEQUENCE_NO % block_size) == 0 ) { + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + + // 파일 크기에 도달하면 EOF하여 파일확인(0304/0314)전문 수행 후 업무종료 + if (batchDoc.getBatchMsg().getBody().getCurFileSize() + sequence_size >= batchDoc.getBatchMsg().getHeader().getFileSize()) { + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + + // 저장된 메모리 정보 참조 하기 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + fileData = block_data.get(new Integer(SEQUENCE_NO-1)); + + if ( fileData == null ){ + fileData = new byte[sequence_size]; + REAL_BYTE = fin.read(fileData); + + if (REAL_BYTE < sequence_size) { + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + byte[] retryFileData = new byte[REAL_BYTE]; + int bytesRead = bin.read(retryFileData); + if (bytesRead == REAL_BYTE) { + block_data.put(new Integer(SEQUENCE_NO-1), retryFileData); + } + } else { + block_data.put(new Integer(SEQUENCE_NO-1), fileData); + } + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + } else { + REAL_BYTE = fileData.length; // 재처리 + } + + // 전송 상태 처리 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0304.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0304.java new file mode 100644 index 0000000..57d4eb5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0304.java @@ -0,0 +1,189 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0304 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_FIUSC_0304() { + //파일 확인 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + // 시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID + byte[] userId = new byte[20]; + Arrays.fill(userId, (byte)' '); + + // checked file에서 가져온 사용자 ID + String fileHeaderInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + fileHeaderInfo = fileHeaderInfo.substring(38); + String checkedFileUserId = fileHeaderInfo.substring(SEND_FIUSC_HEAD.USER_ID.getStrPos(),SEND_FIUSC_HEAD.USER_ID.getEndPos()); + System.arraycopy(checkedFileUserId.getBytes(), 0, userId, 0, Math.min(checkedFileUserId.getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //SEQUENCE-NO + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //기송신 크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0305.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0305.java new file mode 100644 index 0000000..97899ba --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0305.java @@ -0,0 +1,218 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.Arrays; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0305 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_FIUSC_0305() { + //파일 종료 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + // 시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID + byte[] userId = new byte[20]; + Arrays.fill(userId, (byte)' '); + + // checked file에서 가져온 사용자 ID + String fileHeaderInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + fileHeaderInfo = fileHeaderInfo.substring(38); + String checkedFileUserId = fileHeaderInfo.substring(SEND_FIUSC_HEAD.USER_ID.getStrPos(),SEND_FIUSC_HEAD.USER_ID.getEndPos()); + System.arraycopy(checkedFileUserId.getBytes(), 0, userId, 0, Math.min(checkedFileUserId.getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //SEQUENCE-NO + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //기송신 크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + + //종료 일시 + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + FileInputStream fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fin != null ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + //재전송을 위해 원본파일(전송정보(100byte)길이 + 전자서명길이(가변) + 데이터(가변))을 처리파일명으로 변경 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + this.getSeparator(); + } + + String fileName = fileDir + fileNm; + String orgFileName = fileName + ".org"; + + File file = new File(fileName); + File orgFile = new File(orgFileName); + + if (file.exists()) file.delete(); + orgFile.renameTo(file); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0312.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0312.java new file mode 100644 index 0000000..69480f9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0312.java @@ -0,0 +1,252 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0312 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_FIUSC_0312() { + //파일 시작 응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + String fileHeaderInfo = batchDoc.getBatchMsg().getTelegramBody(); // 응답수신 송신전문(0312) BODY정보 추출 + + int i = -1; + + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + //시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID + byte[] userId = new byte[20]; + for ( int inx = 0; inx < userId.length; inx++ ){ + userId[inx] = ' '; + } + + System.arraycopy(batchDoc.getBatchMsg().getHeader().getUserID().getBytes(), 0, userId, 0, + Math.min(batchDoc.getBatchMsg().getHeader().getUserID().getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //문서종류코드(6) + compileField(++i, fileHeaderInfo.substring(0,6), this.al_FieldProps[i]); + + //보고메시지유형코드(2) + compileField(++i, fileHeaderInfo.substring(6,8), this.al_FieldProps[i]); + + //문서번호(17) + compileField(++i, fileHeaderInfo.substring(8,25), this.al_FieldProps[i]); + + //보고일자(8) + compileField(++i, fileHeaderInfo.substring(25,33), this.al_FieldProps[i]); + + //종전문서번호(17) + compileField(++i, fileHeaderInfo.substring(33,50), this.al_FieldProps[i]); + + //보고파일명(40) + compileField(++i, fileHeaderInfo.substring(50,90), this.al_FieldProps[i]); + + //거래순번(15) + compileField(++i, fileHeaderInfo.substring(90,105), this.al_FieldProps[i]); + + //기본보고문서번호(17) + compileField(++i, fileHeaderInfo.substring(105,122), this.al_FieldProps[i]); + + //중계기관코드(6) + compileField(++i, telegramInfo.getProperty(TelegramKeys.FIUSC_EAI_CD), this.al_FieldProps[i]); + + //레코드 길이(4) + compileField(++i, "0001", this.al_FieldProps[i]); + + //압축사용여부(1) + String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String compGb = "0"; + if ( ( renamedFileName.indexOf(".ZIP_") > -1 ) || ( renamedFileName.indexOf(".zip_")) > -1 ){ + compGb = "2"; + } + if ( renamedFileName.indexOf(".Z_") > -1 ){ + compGb = "1"; + } + compileField(++i, compGb, this.al_FieldProps[i]); + + //파일전체크기(10) + compileField(++i, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[i]); + + //이어받기 사용여부(1) + compileField(++i, TelegramKeys.FIUSC_RESUME_YN, this.al_FieldProps[i]); + + //수신한 길이(10) + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + // 하나라고 설정해 준다. + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + //응답수신 파일 Start DB로그 + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0314.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0314.java new file mode 100644 index 0000000..b8eb638 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0314.java @@ -0,0 +1,326 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0314 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + private String RTN_CD; + private int block_data_size = 0; + + /** + * 생성자 + */ + public SEND_FIUSC_0314() { + //결번확인통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = compareSeqNSize(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + // 시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID + byte[] userId = new byte[20]; + for ( int inx = 0; inx < userId.length; inx++ ){ + userId[inx] = ' '; + } + + System.arraycopy(batchDoc.getBatchMsg().getHeader().getUserID().getBytes(), 0, userId, 0, + Math.min(batchDoc.getBatchMsg().getHeader().getUserID().getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //결과 + compileField(++i, RTN_CD, this.al_FieldProps[i]); + + //시퀀스 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //수신크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if ( fout != null ){ + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //확인결과 정상(RTN_CD='00')이 아닌 경우 재처리를 위해 기수신파일크기 리셋 + if (RTN_CD != "00") { + long cur_size = this.batchDoc.getBatchMsg().getBody().getCurFileSize(); + batchDoc.getBatchMsg().getBody().setCurFileSize(cur_size-block_data_size); + } + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error(e.getMessage(),e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + if (RTN_CD.equals("00")) { + if (batchDoc.getBatchMsg().getBody().getCurFileSize() >= batchDoc.getBatchMsg().getHeader().getFileSize()) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + return true; + } + + private boolean compareSeqNSize() { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + long cur_size = this.batchDoc.getBatchMsg().getBody().getCurFileSize(); + + // 이전 전문에서 저장한 전문 내용을 꺼내어 본다. 17 자리라고 가정 + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + int recv_seq_no = Integer.parseInt(recvTelegramBody.substring(0, 7).trim()); + long recv_cur_size = Integer.parseInt(recvTelegramBody.substring(7,17)); // 기송신크기 + + // RTN_CD 비정상에 대한 재처리 테스트 (RECV_FIUSC_0303 처리 시 setRecLen(+1)) + /* if (batchDoc.getBatchMsg().getHeader().getRecLen() == 14) { + recv_cur_size = recv_cur_size - 1; + recv_seq_no = recv_seq_no - 1; + }*/ + + if ( cur_size == recv_cur_size){ + if ( seq_no == recv_seq_no ){ + RTN_CD = "00"; + } else { + RTN_CD = "01"; + } + } else { + if ( seq_no == recv_seq_no ){ + RTN_CD = "10"; + } else { + RTN_CD = "11"; + } + } + + HashMap hm = JobProcessData.getInstance().getBatchStageData(uuid); + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("RECIVED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + // 파일 스트림은 한번만 생성 + if (RTN_CD.equals("00")) { + if (!createFile()) return false; + } + + //받은 seq_no만큼만 데이터 확인하여 정상이면 파일에 기록하고, 비정상이면 받은 데이터 길이만 저장 + for (int i=0; i < seq_no; i++) { + byte[] data = (byte[]) block_data.get(new Integer(i)); + if (data != null ) { + if (RTN_CD.equals("00")) { + fout.write(data); + } else { + block_data_size += block_data.get(i).length; + } + } + } + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); //데이터 기록 여부와 관계 없이 Vector 초기화 + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI027"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + private boolean createFile () { + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + this.getSeparator(); + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0315.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0315.java new file mode 100644 index 0000000..073e4e7 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0315.java @@ -0,0 +1,346 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0315 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + private FileOutputStream fout; + private String RTN_CD; + + /** + * 생성자 + */ + public SEND_FIUSC_0315() { + //파일 종료 응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = compareSeqNSize(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + // 시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID + byte[] userId = new byte[20]; + for ( int inx = 0; inx < userId.length; inx++ ){ + userId[inx] = ' '; + } + + System.arraycopy(batchDoc.getBatchMsg().getHeader().getUserID().getBytes(), 0, userId, 0, + Math.min(batchDoc.getBatchMsg().getHeader().getUserID().getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //결과 + compileField(++i, RTN_CD, this.al_FieldProps[i]); + + //시퀀스 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]); + + //수신크기 + compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]); + + //종료 일시 + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if ( fout != null ){ + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); +// batchDoc.getBatchMsg().getHeader().setBizCode(new String((byte[])this.al_Field.get(2))); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error(e.getMessage(),e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + + return true; + } + + private boolean compareSeqNSize() { + try { + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + long cur_size = this.batchDoc.getBatchMsg().getBody().getCurFileSize(); + + // 이전 전문에서 저장한 전문 내용을 꺼내어 본다. 17 자리라고 가정 + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + int recv_seq_no = Integer.parseInt(recvTelegramBody.substring(0, 7)); + long recv_cur_size = Integer.parseInt(recvTelegramBody.substring(7,17)); + + if ( cur_size == recv_cur_size){ + if ( seq_no == recv_seq_no ){ + RTN_CD = "00"; + } else { + RTN_CD = "01"; + } + } else { + if ( seq_no == recv_seq_no ){ + RTN_CD = "10"; + } else { + RTN_CD = "11"; + } + } + + if (RTN_CD.equals("00")) { + // 수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir.trim() + this.getSeparator(); + } + String fileName = fileDir + fileNm.trim(); + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + + if (rcvRealFile.exists()) { + // DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + // DB로그에 남길 파일 사이즈 설정 + batchDoc.getBatchMsg().getHeader().setFileSize(rcvRealFile.length()); + + // 수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + + if (rcvArchFile.exists()) rcvArchFile.delete(); // 기존에 수신된 동일한 파일이 있으면 삭제 +// boolean isSuccessMoveFile = moveRealFile(rcvRealFile,rcvArchFile); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("UNDEFINED_CD", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + + RTN_CD = "99"; + } + + // 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 수신 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(fileName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + // DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileNm); + + // 수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI027"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + private boolean moveRealFile(File rcvRealFile, File rcvArchFile) { + + boolean result = false; + + //InputStream ios = null;// 20250910 obl + InputStream ioss = null; + FileOutputStream fos = null; + try { + + byte[] realFileInfo = new byte[(int)rcvRealFile.length()]; + ioss = new FileInputStream(rcvRealFile); + ioss.read(realFileInfo); + ioss.close(); + ioss = null; + + fos = new FileOutputStream(rcvArchFile); + fos.write(realFileInfo); + + if (rcvArchFile.exists() && rcvArchFile.length() > 0) { + result = rcvRealFile.delete(); + } + } catch (IOException e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + + } finally { + try { + //if (ios != null) ios.close(); + if (ioss != null) ioss.close(); + if (fos != null) fos.close(); + } catch (IOException ioe) { + logger.debug(ioe.getMessage(),ioe); + } + } + + return result; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0610.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0610.java new file mode 100644 index 0000000..0ba6f73 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0610.java @@ -0,0 +1,281 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FilenameFilter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FIUSC_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_FIUSC_0610() { + //업무개시요구 및 응답 (0600/0010, 0610/0010) + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + //전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + // 시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 참가기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + //사용자ID + byte[] userId = new byte[20]; + for ( int inx = 0; inx < userId.length; inx++ ){ + userId[inx] = ' '; + } + + System.arraycopy(batchDoc.getBatchMsg().getHeader().getUserID().getBytes(), 0, userId, 0, + Math.min(batchDoc.getBatchMsg().getHeader().getUserID().getBytes().length, 20)); + + al_Field.set(++i, userId); + + //전문종별코드. + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + //송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //전문 전송일시 YYYYMMDDHHMMSS + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + if (this.getFldOpCode().endsWith("4")){ + return true; + } + + //파일 확인 요구 간격 +// compileField(++i, ""+batchDoc.getBatchMsg().getHeader().getPacketSize(), this.al_FieldProps[i]); + compileField(++i, ""+this.batchDoc.getBatchMsg().getHeader().getBlockSize(), this.al_FieldProps[i]); + + //전송방법 + compileField(++i, TelegramKeys.FIUSC_DATA_FLAG_BIN, this.al_FieldProps[i]); + + //압축사용여부 + String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String compGb = "0"; + if ( ( renamedFileName.indexOf(".ZIP_") > -1 ) || ( renamedFileName.indexOf(".zip_")) > -1 ){ + compGb = "2"; + } + if ( renamedFileName.indexOf(".Z_") > -1 ){ + compGb = "1"; + } + compileField(++i, compGb, this.al_FieldProps[i]); + + //이어받기 사용여부 + compileField(++i, TelegramKeys.FIUSC_RESUME_YN, this.al_FieldProps[i]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //송신파일 일괄 암호화를 위해 송신파일목록 저장 + if (this.batchDoc.getBatchMsg().getHeader().getProcessType().equals("RS")) { + addRenamedFileList(); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + private boolean addRenamedFileList() { + + boolean result = false; + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i 0) { +// this.batchDoc.getBatchMsg().setFileList(Arrays.asList(fileList)); +// result = true; +// } + + return result; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0640.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0640.java new file mode 100644 index 0000000..2ec0d0d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_0640.java @@ -0,0 +1,212 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class SEND_FIUSC_0640 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이) + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_FIUSC_0640() { + //업무종료요구 및 응답(0600/0040, 0610/0040) + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + int i = -1; + // 전문송신 전체 Byte 수 + compileField(++i, ""+REAL_SEND_LENGTH, this.al_FieldProps[i]); + + // Transaction Code + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]); + + // 시스템명칭 (FIU) + compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]); + + // 보고기관코드 + compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]); + + // 사용자ID + byte[] userId = new byte[20]; + for ( int inx = 0; inx < userId.length; inx++ ){ + userId[inx] = ' '; + } + + System.arraycopy(batchDoc.getBatchMsg().getHeader().getUserID().getBytes(), 0, userId, 0, + Math.min(batchDoc.getBatchMsg().getHeader().getUserID().getBytes().length, 20)); + + al_Field.set(++i, userId); + + // 전문종별코드 + compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]); + + // 송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다. + compileField(++i, getFldTrClass(), this.al_FieldProps[i]); + + //기관구분 + compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]); + + //계속여부 + compileField(++i, "Y", this.al_FieldProps[i]); + + //응답코드 + compileField(++i, getSendResponseCode(), this.al_FieldProps[i]); + // 여기 까지 공통부 + + //업무종료일시 (YYYYMMDDHHMMSS) + compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]); + + //<< 전문 완성 + + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return -1; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + + //BATCH작업구분코드 (processCode)에 따른 프로퍼티 정보 가져오기 + telegramInfo = getTelegramInfo(); + + String filename = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( filename.length() == 14){ // 스케쥴 관리 화면에서 기동 된 경우 + batchDoc.getBatchMsg().getHeader().setBaseDate( filename.substring(6)); + } else { + batchDoc.getBatchMsg().getHeader().setBaseDate( TelegramKeys.getYYYYMMDD() ); + } + try { + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE)) { + batchDoc.getBatchMsg().getHeader().setScheduleCode(" "); + batchDoc.getBatchMsg().getHeader().setBizCode(""); + batchDoc.getBatchMsg().getHeader().setFileName(""); + } + + } catch (Exception e) {} // 에러 시 무시 + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(ex.getMessage(),ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(e.getMessage(),e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String telegramNo = super.getFieldValueString(5); + if ( telegramNo.length() < 8 ) return ""; + return telegramNo.substring(0,3) + telegramNo.substring(6,7); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(9); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_HEAD.java b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_HEAD.java new file mode 100644 index 0000000..680b740 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/fiusc/SEND_FIUSC_HEAD.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.fiusc; + +public enum SEND_FIUSC_HEAD { + + DOC_CODE ("문서종류코드", "AN",0,6,6), + MSG_GBN_CD ("보고메시지유형코드", "NN",6,8,2), + DOC_NO ("문서번호", "AN",8,25,17), + DOC_DATETIME ("문서일자", "NN",25,33,8), + PRE_DOC_NO ("종전문서번호", "AN",33,50,17), + TGRA_SEQ ("거래순번", "AN",50,65,15), + DEF_DOC_NO ("기본보고문서번호", "AN",65,82,17), + HASH_SIZE ("전자서명데이터길이", "NN",82,86,4), + USER_ID ("사용자ID", "AN",86,106,4); + + private String name; + private String type; + private int strPos; + private int endPos; + private int length; + + private SEND_FIUSC_HEAD(String name, String type, int strPos, int endPos, int length) { + this.name = name; + this.type = type; + this.strPos = strPos; + this.endPos = endPos; + this.length = length; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public int getStrPos() { + return strPos; + } + public void setStrPos(int strPos) { + this.strPos = strPos; + } + public int getEndPos() { + return endPos; + } + public void setEndPos(int endPos) { + this.endPos = endPos; + } + public int getLength() { + return length; + } + public void setLength(int length) { + this.length = length; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT.java new file mode 100644 index 0000000..8983984 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT.java @@ -0,0 +1,57 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_FTBAT extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 : FTManager 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_FTBAT() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(4); +// } +// //응답코드 필드값 리턴 +// public String getResCode() +// { +// return super.getFieldValueString(7); +// } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(9); +// } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + if ( getTelegramType().equals("0200")) + return 72; + return 1024; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0200.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0200.java new file mode 100644 index 0000000..7b1a650 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0200.java @@ -0,0 +1,292 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.net.Socket; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoManager; +import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FTBAT_0200 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + private ByteArrayOutputStream bout; + + public RECV_FTBAT_0200() { + //업무개시요구 및 업무개시통보 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + int fileNameLen = bout.toByteArray().length - 1; + byte[] filename = new byte[fileNameLen]; + System.arraycopy(bout.toByteArray(), 0, filename, 0, fileNameLen); + setFieldDataByIndex(4,filename); + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + setResolveResponseCode("0000"); + logger.info("{} BATCH JOB : start request received", logHeader); + // 거래구분코드(송수신 구분 코드) 체크 + String recvTrGbCd = getFieldValueString(2); + String recvKikwanCode = getFieldValueString(3).trim(); + + String recvFileName = getFieldValueString(4).trim(); + if ( "100010".equals(recvTrGbCd)){ + logger.info("{} BATCH JOB : send request received", logHeader); + batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND); + checkMoreFileinDB(recvFileName); + }else if ( "100020".equals(recvTrGbCd)){ + logger.info("{} BATCH JOB : recv request received", logHeader); + setConditionTxt(TelegramKeys.RECV); + batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE); + if ( !procRecv(recvFileName) ) + return true; + }else{ + logger.info("{} BATCH JOB : send/recv request error", logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_FORMAT_ERROR); + setConditionTxt(TelegramKeys.ERROR); + } + KikwanInfoVO vo = KikwanInfoManager.getInstance().getKikwanInfo(recvKikwanCode); + batchDoc.getBatchMsg().getHeader().setTRXID(recvKikwanCode); + + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + Socket socket = BatchRunningJobManager.getInstance().getRunningSocket(strUUID); + batchDoc.getBatchMsg().getHeader().setRemoteIP(socket.getRemoteSocketAddress().toString().substring(1,socket.getRemoteSocketAddress().toString().indexOf(":") )); + + if ( vo == null || !vo.getSysIp().equals(batchDoc.getBatchMsg().getHeader().getRemoteIP()) ){ + setConditionTxt(TelegramKeys.NOFILE); + setResolveResponseCode("B001"); + batchDoc.getBatchMsg().getBody().setErrorMsg("Your IP is not authorized[" + batchDoc.getBatchMsg().getHeader().getRemoteIP()+ "]"); + }else{ + } + + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=1; i<2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=2; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return 51; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + bout.write(data, 0, length); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + private void checkMoreFileinDB(String fileName){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode, fileName ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + setResolveResponseCode("F001"); + batchDoc.getBatchMsg().getBody().setErrorMsg("File not found [" + fileName + "]"); + return; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(0); + this.setConditionTxt(TelegramKeys.SEND); + LogUtil.updateLogMaster(batchDoc); + LogUtil.setLogFileStart(batchDoc); + } catch ( Exception e){} + } + + + private boolean procRecv(String fileName){ + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + setResolveResponseCode("F003"); + batchDoc.getBatchMsg().getBody().setErrorMsg("This is not a REGISTERED FILE[" + fileName+ "]"); + return false; + } + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + + String recvFileName = FileUtil.getRecvFileName(fileName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fileName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(0); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + //수신 파일 End DB로그 + try { + LogUtil.setLogFileStart(batchDoc); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + return true; + + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType(){ + return super.getFieldValueString(1); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0220.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0220.java new file mode 100644 index 0000000..6392387 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0220.java @@ -0,0 +1,179 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FTBAT_0220 extends DefaultTelegram implements TelegramService +{ + + private FileOutputStream fout; + /** + * 생성자 + */ + public RECV_FTBAT_0220() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _seq_no = new String ((byte[]) al_Field.get(2)); + int recv_seq_no = Integer.parseInt(_seq_no); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (recv_seq_no != seq_no + 1 ){ + logger.debug("{} doExecute >> recived seq no isn't match current seq no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _seq_no; + msgArgs[2] = ""+_seq_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + if (!createFile()) { + return false; + } + + String _size = new String ((byte[]) al_Field.get(3)); + int recv_size = Integer.parseInt(_size); + byte[] data = al_Field.get(4); + fout.write(data, 0, recv_size); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + recv_size; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + batchDoc.getBatchMsg().getHeader().setFileSize(lnCurSize); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=1; i<2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=2; i< al_Field.size()-2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + }finally{ + if ( fout != null ) + try { + fout.close(); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean createFile () { + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(4); +// } +// //응답코드 필드값 리턴 +// public String getResCode() +// { +// return super.getFieldValueString(7); +// } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getOpCode(); +// } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0230.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0230.java new file mode 100644 index 0000000..79b625d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/RECV_FTBAT_0230.java @@ -0,0 +1,106 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_FTBAT_0230 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_FTBAT_0230() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _size = new String ((byte[]) al_Field.get(2)); + int recv_size = Integer.parseInt(_size); + + if (recv_size != batchDoc.getBatchMsg().getBody().getCurFileSize() ){ + setResolveResponseCode("F002"); + batchDoc.getBatchMsg().getBody().setErrorMsg("수신된 파일 사이즈[" + batchDoc.getBatchMsg().getBody().getCurFileSize()+ "]"); + }else{ + setResolveResponseCode("0000"); + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=1; i<2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=2; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(4); +// } +// //응답코드 필드값 리턴 +// public String getResCode() +// { +// return super.getFieldValueString(7); +// } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getOpCode(); +// } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0210.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0210.java new file mode 100644 index 0000000..8bd45e2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0210.java @@ -0,0 +1,221 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoManager; +import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FTBAT_0210 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public SEND_FTBAT_0210() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + byte[] som = new byte[1]; + byte[] eom = new byte[1]; + som[0] = 0x02; + eom[0] = 0x03; + + String kikwanCode = batchDoc.getBatchMsg().getHeader().getTRXID(); + KikwanInfoVO vo = KikwanInfoManager.getInstance().getKikwanInfo(kikwanCode); + + + //메시지 시작 문자 + al_Field.set(0, som); + + //메시지 타입 + compileField(1, this.getFldTelegramType(), this.al_FieldProps[1]); + + //트랜잭션코드 + compileField(2, "100" + this.getFldOpCode(), this.al_FieldProps[2]); + + //기관코드 + compileField(3, kikwanCode, this.al_FieldProps[3]); + + //IP주소 + if ( vo != null ){ + compileField(4, vo.getEncIp(), this.al_FieldProps[3]); + } else { + compileField(4, "", this.al_FieldProps[3]); + } + + //오류코드 + compileField(5, getSendResponseCode(), this.al_FieldProps[3]); + + //오류메시지 + compileField(6, batchDoc.getBatchMsg().getBody().getErrorMsg(), this.al_FieldProps[3]); + + //filler + compileField(7, "", this.al_FieldProps[3]); + + //메시지 종료 문자 + al_Field.set(8, eom); + + //<< 전문 완성 + return true; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return 1024; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + try { + //Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=1; i<2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=2; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + +// //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 +// //수신 파일 관련 처리 +// String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); +// String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); +// if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { +// fileDir = fileDir + File.separator; +// } +// String fileName = fileDir + fileNm; +// +// File rcvRealFile = new File( fileName ); +// File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); +// File rcvRootFile = new File( StringUtil.getCheckFileName(fileName) ); +// +// if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { +// +// //DB로그에 남길 파일 헤더,트레일러 내용 설정 +// super.setFileHeaderAndTrailer(rcvRealFile); +// +// //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); +// //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) +// logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); +// boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); +// if (!isSuccessMoveFile) { +// String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] +// super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); +// //수신 파일 End DB로그 +// LogUtil.setLogFileEnd(batchDoc); +// return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 +// } +// +// logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); +// try { +// isSuccessMoveFile = rcvRootFile.createNewFile(); +// } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... +// +// if (!isSuccessMoveFile) { +// String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] +// } +// +// //수신 파일 End DB로그 +// LogUtil.setLogFileEnd(batchDoc); +// } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(2); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(5); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(2); +// } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0220.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0220.java new file mode 100644 index 0000000..42b47a2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0220.java @@ -0,0 +1,262 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FTBAT_0220 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int SEQUENCE_NO; + private int REAL_BYTE; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_FTBAT_0220() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + if (!setData()) return false; + + byte[] som = new byte[1]; + byte[] eom = new byte[1]; + som[0] = 0x02; + eom[0] = 0x03; + + //메시지 시작 문자 + al_Field.set(0, som); + + //메시지 타입 + compileField(1, this.getFldTelegramType(), this.al_FieldProps[1]); + + compileField(2, ""+SEQUENCE_NO, this.al_FieldProps[2]); + //실 DATA BYTE 수 + compileField(3, ""+REAL_BYTE, this.al_FieldProps[3]); + + al_Field.set(4, fileData); + + //메시지 종료 문자 + al_Field.set(5, eom); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=1; i<2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=2; i< al_Field.size()-2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + try { + Thread.sleep(300); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength(){ + return 1024; + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID()); + if( fin != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + batchDoc.getBatchMsg().getHeader().setFileSize(file.length()); + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setData () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum() + 1; + + long fileSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + + fileData = new byte[1008]; + REAL_BYTE = Math.min((int)(fileSize - lnCurSize),fileData.length); + fin.read(fileData, 0, REAL_BYTE); + if ( REAL_BYTE < fileData.length ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + this.setConditionTxt(TelegramKeys.EOF); + } + + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize + REAL_BYTE); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0230.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0230.java new file mode 100644 index 0000000..c11182e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0230.java @@ -0,0 +1,134 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FTBAT_0230 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public SEND_FTBAT_0230() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + byte[] som = new byte[1]; + byte[] eom = new byte[1]; + som[0] = 0x02; + eom[0] = 0x03; + + //메시지 시작 문자 + al_Field.set(0, som); + + //메시지 타입 + compileField(1, this.getFldTelegramType(), this.al_FieldProps[1]); + + compileField(2, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[2]); + + //실 DATA BYTE 수 + compileField(3, "0000", this.al_FieldProps[3]); + + compileField(4, "", this.al_FieldProps[4]); + + compileField(5, "", this.al_FieldProps[5]); + + //메시지 종료 문자 + al_Field.set(6, eom); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=1; i<2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=2; i< al_Field.size()-2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + //송신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + int sleepTime = 1000; + try { + sleepTime = Integer.parseInt(getTelegramInfo().getProperty(TelegramKeys.SLEEP_TIME_POST)); + } catch (Exception e) {} + try { + Thread.sleep(sleepTime); + } catch (Exception e) {} + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + try { + Thread.sleep(300); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength(){ + return 1024; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType(){ + return super.getFieldValueString(1); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0240.java b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0240.java new file mode 100644 index 0000000..f1160f1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ftbat/SEND_FTBAT_0240.java @@ -0,0 +1,207 @@ +package com.eactive.eai.batch.job.jobItem.ftbat; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_FTBAT_0240 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public SEND_FTBAT_0240() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + byte[] som = new byte[1]; + byte[] eom = new byte[1]; + som[0] = 0x02; + eom[0] = 0x03; + + //메시지 시작 문자 + al_Field.set(0, som); + + //메시지 타입 + compileField(1, this.getFldTelegramType(), this.al_FieldProps[1]); + + //파일사이즈 + compileField(2, "" + batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[2]); + + //오류코드 + compileField(3, getSendResponseCode(), this.al_FieldProps[3]); + + //오류메시지 + compileField(4, batchDoc.getBatchMsg().getBody().getErrorMsg(), this.al_FieldProps[4]); + + //filler + compileField(5, "", this.al_FieldProps[5]); + + //메시지 종료 문자 + al_Field.set(6, eom); + + //<< 전문 완성 + return true; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return 1024; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + try { + //Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=1; i<2; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=2; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists()) && getSendResponseCode().equals("0000")) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(2); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(5); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(2); +// } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE.java new file mode 100644 index 0000000..5f3de5a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE.java @@ -0,0 +1,75 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_HOUSE extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 주택금융공사(X.25) 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_HOUSE() { + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(4).equalsIgnoreCase("0600") ||super.getFieldValueString(4).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(13); + } + else { + return super.getOpCode(); + } + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkFileEOF() { + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() + + batchDoc.getBatchMsg().getHeader().getRecLen() + >= batchDoc.getBatchMsg().getHeader().getFileSize() ){ + this.setConditionTxt(TelegramKeys.EOF); + } + return; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0310.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0310.java new file mode 100644 index 0000000..7e7cc8f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0310.java @@ -0,0 +1,231 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_HOUSE_0310 extends DefaultTelegram implements TelegramService { + + private int INFORMALFIELD_INDEX = 15; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_HOUSE_0310() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(12)); + String _seq_no = new String ((byte[]) al_Field.get(13)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ( recv_block_no != 9999 && recv_block_no != block_no ){ + return true; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + batchDoc.getBatchMsg().getHeader().setRecLen(Integer.parseInt(super.getFieldValueString(9))); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(12)); + String _seq_no = new String ((byte[]) al_Field.get(13)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ( recv_block_no == block_no ){ + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0320.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0320.java new file mode 100644 index 0000000..c3123ce --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0320.java @@ -0,0 +1,373 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_HOUSE_0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 15; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; + + /** + * 생성자 + */ + public RECV_HOUSE_0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String fName = new String ((byte[]) al_Field.get(5)); + String baseDate = new String ((byte[]) al_Field.get(8)); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(12)); + String _seq_no = new String ((byte[]) al_Field.get(13)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( recv_block_no != 9999 && recv_block_no != block_no ){ + return true; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + batchDoc.getBatchMsg().getHeader().setRecLen(Integer.parseInt(super.getFieldValueString(9))); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(12)); + String _seq_no = new String ((byte[]) al_Field.get(13)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ +// } else if ( ( recv_block_no > 0) && (recv_seq_no > 1) ){ // 강제 결번 테스트용 + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + if ( recv_block_no == block_no ){ + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + //DB로그에 남길 파일 사이즈 설정 + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getBody().getCurFileSize()); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recLen > 0 ){ + int recCnt = (int)batchDoc.getBatchMsg().getBody().getCurFileSize()/recLen; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + } + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.KFB_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0330.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0330.java new file mode 100644 index 0000000..ca069ff --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0330.java @@ -0,0 +1,194 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_HOUSE_0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_HOUSE_0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(12).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + } else if (super.getFieldValueString(12).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + this.setConditionTxt(TelegramKeys.NOFILE); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + /* + private boolean checkMoreFile(){ + return false; + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return false; + } + String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID(); + String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + logger.debug("UUID추적:[ScheduleHandlerProcess]:uuid["+info.getUUID() +"]"); + logger.debug("UUID추적:[ScheduleHandlerProcess]:subuuid["+info.getSubUUID() +"]"); + + //BatchMsgDoc 값 설정 + batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath()); + batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName()); + batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode()); + batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW()); + + + + } catch ( Exception e){ + return false; + + } + return true; + } + */ + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0600.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0600.java new file mode 100644 index 0000000..1eac95b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0600.java @@ -0,0 +1,188 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_HOUSE_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_snd_req = "008"; //송신시작요구 + private final String OpCode_chk_down = "301"; //업무 장애 회복 확인 + + /** + * 생성자 + */ + public RECV_HOUSE_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_snd_req)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_chk_down)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.KFB_RET_CODE_TGRAM_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + batchDoc.getBatchMsg().getHeader().setTRXID(new String((byte[])this.al_Field.get(1))); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(13); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0610.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0610.java new file mode 100644 index 0000000..6be89b5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0610.java @@ -0,0 +1,187 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_HOUSE_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_snd_req = "008"; //송신시작요구 + private final String OpCode_chk_down = "301"; //업무 장애 회복 확인 + + /** + * 생성자 + */ + public RECV_HOUSE_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_snd_req)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_chk_down)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.KFB_RET_CODE_TGRAM_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(13); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0620.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0620.java new file mode 100644 index 0000000..329c71e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0620.java @@ -0,0 +1,121 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_HOUSE_0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_HOUSE_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(12)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(13)); // 0 base 인덱스 + + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0800.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0800.java new file mode 100644 index 0000000..a7082f9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0800.java @@ -0,0 +1,90 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_HOUSE_0800 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_HOUSE_0800() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(5)); + batchDoc.getBatchMsg().getHeader().setRecLen(Integer.parseInt(super.getFieldValueString(9))); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0810.java b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0810.java new file mode 100644 index 0000000..1689e51 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/RECV_HOUSE_0810.java @@ -0,0 +1,90 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_HOUSE_0810 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_HOUSE_0810() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(5)); + batchDoc.getBatchMsg().getHeader().setRecLen(Integer.parseInt(super.getFieldValueString(9))); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0300.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0300.java new file mode 100644 index 0000000..20409ff --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0300.java @@ -0,0 +1,422 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0300 extends DefaultTelegram implements TelegramService { + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_HOUSE_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //아데나 장비를 위한 전문 길이 필드 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //Transaction Code - 해당 Transaction을 기동하는 코드. LU가 구분 되어 있을 것으로 예상 + // 모기지론 유동화 자료 - HR00FTP + // 주택위탁보증 자료 - HW00FTP + // 학자금 유동화 자료 - SR00FTP + // 학자금위탁보증 자료 - SW00FTP + // U보금자리 - BM00FTP/BM01FTP + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //업무구분코드 - 업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 대외기관을 나타내는 코드로서 세부사항은 표준화 사항의 대외기관코드를 참조한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 - 각 업무 및 화일의 종류를 구분하기 위한 코드로 구성되며 세부내용은 표준화 사항을 참조한다. + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG - 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + // “C” : 한국주택금융공사에서 전문을 발생할 시 + // “B” : 위탁기관에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 - 전문의 처리 결과를 나타내는 응답코드로 세부내용은 표준화 사항의 응답코드를 참조한다. + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //일자 (자료기준일자) - 은행에서 자료보고(위탁기관→주택금융공사) 및 주택금융공사자료통보(주택금융공사→위탁기관) 시에는 자료의 기준일자를 Set한다. + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전체 전문 길이 + //공통부와 업무정보부를 합한 전체길이. + //프로토콜이 TCP/IP 인 경우만 Set 한다. + //compileField(10, ""+SEND_LENGTH, this.al_FieldProps[10]); + compileField(10, "0", this.al_FieldProps[10]); + + //송수신 업무 구분코드. 한국주택금융공사를 기준으로 하여 해당전문이 송.수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래값 중 해당코드를 Set한다. + //“S” : 화일 송신업무 관련 전문 (한국주택금융공사→위탁기관) + //“R” : 화일 수신업무 관련 전문 (위탁기관→한국주택금융공사) + compileField(11, getFldTrClass() , this.al_FieldProps[11]); + + //Block-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[12]); + + //Sequence-NO + compileField(13, ""+SEQUENCE_NO , this.al_FieldProps[13]); + + //결번갯수 + compileField(14, ""+MISSING_COUNT, this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + batchDoc.getBatchMsg().getBody().setBlockNum(block_no + 1); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return MISSING_FIELD.length(); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + //mod by khs data = MISSING_FIELD.getBytes(); + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i> byte[] data = (byte[]) block_data.get( i ); + byte[] data = null; + if ( block_data != null ){ + data = (byte[]) block_data.get( new Integer(i) ); + } + if (data == null ) { + _missingNm[i] = '0'; //결번이 발생한 seq만 '0' 설정 + MISSING_COUNT++; + logger.info("{} calculateMissingCount >> missing telegram : [" + i + "]", logHeader); + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0310.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0310.java new file mode 100644 index 0000000..69004a1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0310.java @@ -0,0 +1,363 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0310 extends DefaultTelegram implements TelegramService { + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_HOUSE_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //아데나 장비를 위한 전문 길이 필드 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //Transaction Code - 해당 Transaction을 기동하는 코드. LU가 구분 되어 있을 것으로 예상 + // 모기지론 유동화 자료 - HR00FTP + // 주택위탁보증 자료 - HW00FTP + // 학자금 유동화 자료 - SR00FTP + // 학자금위탁보증 자료 - SW00FTP + // U보금자리 - BM00FTP/BM01FTP + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //업무구분코드 - 업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 대외기관을 나타내는 코드로서 세부사항은 표준화 사항의 대외기관코드를 참조한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 - 각 업무 및 화일의 종류를 구분하기 위한 코드로 구성되며 세부내용은 표준화 사항을 참조한다. + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG - 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + // “C” : 한국주택금융공사에서 전문을 발생할 시 + // “B” : 위탁기관에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 - 전문의 처리 결과를 나타내는 응답코드로 세부내용은 표준화 사항의 응답코드를 참조한다. + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //일자 (자료기준일자) - 은행에서 자료보고(위탁기관→주택금융공사) 및 주택금융공사자료통보(주택금융공사→위탁기관) 시에는 자료의 기준일자를 Set한다. + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전체 전문 길이 + //공통부와 업무정보부를 합한 전체길이. + //프로토콜이 TCP/IP 인 경우만 Set 한다. + //compileField(10, ""+SEND_LENGTH, this.al_FieldProps[10]); + compileField(10, "0", this.al_FieldProps[10]); + + //송수신 업무 구분코드. 한국주택금융공사를 기준으로 하여 해당전문이 송.수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래값 중 해당코드를 Set한다. + //“S” : 화일 송신업무 관련 전문 (한국주택금융공사→위탁기관) + //“R” : 화일 수신업무 관련 전문 (위탁기관→한국주택금융공사) + compileField(11, getFldTrClass() , this.al_FieldProps[11]); + + //Block-NO + compileField(12, ""+BLOCK_NO , this.al_FieldProps[12]); + + //Sequence-NO + compileField(13, ""+SEQUENCE_NO , this.al_FieldProps[13]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(14, "" + recCnt, this.al_FieldProps[14]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0320.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0320.java new file mode 100644 index 0000000..e3355bf --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0320.java @@ -0,0 +1,538 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_HOUSE_0320 extends DefaultTelegram implements TelegramService { + + private FileInputStream fin; + private File file; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //개별필드 길이의 총 합(길이필드 제외) + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + private boolean retry = false; + + /** + * 생성자 + */ + public SEND_HOUSE_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //아데나 장비를 위한 전문 길이 필드 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //Transaction Code - 해당 Transaction을 기동하는 코드. LU가 구분 되어 있을 것으로 예상 + // 모기지론 유동화 자료 - HR00FTP + // 주택위탁보증 자료 - HW00FTP + // 학자금 유동화 자료 - SR00FTP + // 학자금위탁보증 자료 - SW00FTP + // U보금자리 - BM00FTP/BM01FTP + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //업무구분코드 - 업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 대외기관을 나타내는 코드로서 세부사항은 표준화 사항의 대외기관코드를 참조한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 - 각 업무 및 화일의 종류를 구분하기 위한 코드로 구성되며 세부내용은 표준화 사항을 참조한다. + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG - 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + // “C” : 한국주택금융공사에서 전문을 발생할 시 + // “B” : 위탁기관에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 - 전문의 처리 결과를 나타내는 응답코드로 세부내용은 표준화 사항의 응답코드를 참조한다. + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //일자 (자료기준일자) - 은행에서 자료보고(위탁기관→주택금융공사) 및 주택금융공사자료통보(주택금융공사→위탁기관) 시에는 자료의 기준일자를 Set한다. + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전체 전문 길이 + //공통부와 업무정보부를 합한 전체길이. + //프로토콜이 TCP/IP 인 경우만 Set 한다. + //compileField(10, ""+SEND_LENGTH, this.al_FieldProps[10]); + compileField(10, "0", this.al_FieldProps[10]); + + //송수신 업무 구분코드. 한국주택금융공사를 기준으로 하여 해당전문이 송.수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래값 중 해당코드를 Set한다. + //“S” : 화일 송신업무 관련 전문 (한국주택금융공사→위탁기관) + //“R” : 화일 수신업무 관련 전문 (위탁기관→한국주택금융공사) + compileField(11, getFldTrClass() , this.al_FieldProps[11]); + + //Block-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[12]); + + //Sequence-NO + compileField(13, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[13]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(14, "" + recCnt, this.al_FieldProps[14]); + + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num > 0 && block_num < 9999) { + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + if ( !retry ){ + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + } + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (fin != null ) { + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + private boolean createFile () + { + + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int sequence_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + this.setConditionTxt(""); + + +// // 헤더를 재 송신 하는 경우 +// String recvTelegramHeader = new String(batchDoc.getBatchMsg().getTelegramHeader()); +// int telegramTypeOffset = 0; +// for (int i=0; i<4; i++) { +// byte[] fld = this.al_Field.get(i); +// telegramTypeOffset += fld.length; +// } +// byte[] byteRecvTelegramType = new byte[4]; +// System.arraycopy(recvTelegramHeader.getBytes(), telegramTypeOffset, byteRecvTelegramType, 0, byteRecvTelegramType.length); +// String recvTelegramType = new String ( byteRecvTelegramType ); +// if ( !recvTelegramType.equals("0330") ){ +// fileData = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; +// System.arraycopy(this.batchDoc.getBatchMsg().getFileHeader().getBytes(), 0, fileData, 0, Math.min(fileData.length, this.batchDoc.getBatchMsg().getFileHeader().getBytes().length)); +// REAL_BYTE = fileData.length; +// return true; +// } + + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + fileData = new byte[sequence_size + 1]; // 파일의 한 라인당 길이 + 개행문자 1바이트 + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + byte[] fileLine = null; + if ( this.batchDoc.getBatchMsg().getFileHeader() != null && !this.batchDoc.getBatchMsg().getFileHeader().trim().equals("") ){ + fileLine = this.batchDoc.getBatchMsg().getFileHeader().getBytes(); + retry = true; + }else{ + fileLine = FileUtil.readLine(fin); + } + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + + fileData = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + if ( seqCnt < remainCnt - 1){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)(remainCnt - 1) * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1) , fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + REAL_BYTE = fileData.length; + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + if ( BLOCK_NO == 0 ){ + this.batchDoc.getBatchMsg().setFileHeader( new String(fileData)); + }else if ( BLOCK_NO == 9999 ){ + this.batchDoc.getBatchMsg().setFileTrailer( new String(fileData)); + } + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0330.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0330.java new file mode 100644 index 0000000..28f7e6b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0330.java @@ -0,0 +1,327 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_HOUSE_0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + + REAL_BYTE = recvTelegramBody.length() - 11; + + boolean result = calculateSendLength(); + if (!result) return false; + + //아데나 장비를 위한 전문 길이 필드 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //Transaction Code - 해당 Transaction을 기동하는 코드. LU가 구분 되어 있을 것으로 예상 + // 모기지론 유동화 자료 - HR00FTP + // 주택위탁보증 자료 - HW00FTP + // 학자금 유동화 자료 - SR00FTP + // 학자금위탁보증 자료 - SW00FTP + // U보금자리 - BM00FTP/BM01FTP + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //업무구분코드 - 업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 대외기관을 나타내는 코드로서 세부사항은 표준화 사항의 대외기관코드를 참조한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 - 각 업무 및 화일의 종류를 구분하기 위한 코드로 구성되며 세부내용은 표준화 사항을 참조한다. + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG - 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + // “C” : 한국주택금융공사에서 전문을 발생할 시 + // “B” : 위탁기관에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 - 전문의 처리 결과를 나타내는 응답코드로 세부내용은 표준화 사항의 응답코드를 참조한다. + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //일자 (자료기준일자) - 은행에서 자료보고(위탁기관→주택금융공사) 및 주택금융공사자료통보(주택금융공사→위탁기관) 시에는 자료의 기준일자를 Set한다. + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전체 전문 길이 + //공통부와 업무정보부를 합한 전체길이. + //프로토콜이 TCP/IP 인 경우만 Set 한다. + //compileField(10, ""+SEND_LENGTH, this.al_FieldProps[10]); + compileField(10, "0", this.al_FieldProps[10]); + + //송수신 업무 구분코드. 한국주택금융공사를 기준으로 하여 해당전문이 송.수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래값 중 해당코드를 Set한다. + //“S” : 화일 송신업무 관련 전문 (한국주택금융공사→위탁기관) + //“R” : 화일 수신업무 관련 전문 (위탁기관→한국주택금융공사) + compileField(11, getFldTrClass() , this.al_FieldProps[11]); + + //Block-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[12]); + + //Sequence-NO + compileField(13, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[13]); + + //Record 수 --받은 내용을 그대로 돌려 보내기 + compileField(14, recvTelegramBody.substring(8,11), this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + batchDoc.getBatchMsg().getBody().setBlockNum(1); + } else if ( recv_block_no == 9999 ) { + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getBody().getCurFileSize()); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recLen > 0 ){ + int recCnt = (int)batchDoc.getBatchMsg().getBody().getCurFileSize()/recLen; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + } + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + +// bin.read(data, 0, REAL_BYTE); + System.arraycopy(recvTelegramBody.getBytes(), 11, data, 0, REAL_BYTE ); + + // 20060419 add by khs for 전송상태 확인 +// long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; +// batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0600.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0600.java new file mode 100644 index 0000000..c70aae1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0600.java @@ -0,0 +1,276 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //개별필드 길이의 총 합(길이필드 제외) + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_HOUSE_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //아데나 장비를 위한 전문 길이 필드 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //Transaction Code - 해당 Transaction을 기동하는 코드. LU가 구분 되어 있을 것으로 예상 + // 모기지론 유동화 자료 - HR00FTP + // 주택위탁보증 자료 - HW00FTP + // 학자금 유동화 자료 - SR00FTP + // 학자금위탁보증 자료 - SW00FTP + // U보금자리 - BM00FTP/BM01FTP + try { + String trxCode = getJobInfo().getProperty(TelegramKeys.TRANSACTION_CODE); + batchDoc.getBatchMsg().getHeader().setTRXID(trxCode); + } catch (Exception e) { + + } + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //업무구분코드 - 업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 대외기관을 나타내는 코드로서 세부사항은 표준화 사항의 대외기관코드를 참조한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 - 각 업무 및 화일의 종류를 구분하기 위한 코드로 구성되며 세부내용은 표준화 사항을 참조한다. + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG - 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + // “C” : 한국주택금융공사에서 전문을 발생할 시 + // “B” : 위탁기관에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 - 전문의 처리 결과를 나타내는 응답코드로 세부내용은 표준화 사항의 응답코드를 참조한다. + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //일자 (자료기준일자) - 은행에서 자료보고(위탁기관→주택금융공사) 및 주택금융공사자료통보(주택금융공사→위탁기관) 시에는 자료의 기준일자를 Set한다. + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전체 전문 길이 + //공통부와 업무정보부를 합한 전체길이. + //프로토콜이 TCP/IP 인 경우만 Set 한다. + //compileField(10, ""+SEND_LENGTH, this.al_FieldProps[10]); + compileField(10, "0", this.al_FieldProps[10]); + + //송수신 업무 구분코드. 한국주택금융공사를 기준으로 하여 해당전문이 송.수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래값 중 해당코드를 Set한다. + //“S” : 화일 송신업무 관련 전문 (한국주택금융공사→위탁기관) + //“R” : 화일 수신업무 관련 전문 (위탁기관→한국주택금융공사) + compileField(11, getFldTrClass() , this.al_FieldProps[11]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(12, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[12]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “008”: 송신 시작 요구 + // “301”: 업무 장애 회복 확인 + compileField(13, this.getFldOpCode(), this.al_FieldProps[13]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(14, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[14]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(15, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[15]); + + //송신 집계 내역 - 개별업무 종료(0600/003)시만 사용하는 Field로 전송된 Record Count를 Set한다. + if ( this.getFldOpCode().equalsIgnoreCase(OpCode_unit_end) ) + compileField(16, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[16]); + else + compileField(16, "" ,this.al_FieldProps[16]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return 0; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + + if (CommonKeys.PROCESS_REQUEST_RECEIVE.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + String filename = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( filename.length() == 14){ + batchDoc.getBatchMsg().getHeader().setBaseDate( filename.substring(6)); + } else { + batchDoc.getBatchMsg().getHeader().setBaseDate( TelegramKeys.getYYYYMMDD( -1 ) ); + } + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(13); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0610.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0610.java new file mode 100644 index 0000000..d02fa49 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0610.java @@ -0,0 +1,256 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //개별필드 길이의 총 합(길이필드 제외) + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_HOUSE_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //아데나 장비를 위한 전문 길이 필드 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //Transaction Code - 해당 Transaction을 기동하는 코드. LU가 구분 되어 있을 것으로 예상 + // 모기지론 유동화 자료 - HR00FTP + // 주택위탁보증 자료 - HW00FTP + // 학자금 유동화 자료 - SR00FTP + // 학자금위탁보증 자료 - SW00FTP + // U보금자리 - BM00FTP/BM01FTP + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //업무구분코드 - 업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 대외기관을 나타내는 코드로서 세부사항은 표준화 사항의 대외기관코드를 참조한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 - 각 업무 및 화일의 종류를 구분하기 위한 코드로 구성되며 세부내용은 표준화 사항을 참조한다. + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG - 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + // “C” : 한국주택금융공사에서 전문을 발생할 시 + // “B” : 위탁기관에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 - 전문의 처리 결과를 나타내는 응답코드로 세부내용은 표준화 사항의 응답코드를 참조한다. + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //일자 (자료기준일자) - 은행에서 자료보고(위탁기관→주택금융공사) 및 주택금융공사자료통보(주택금융공사→위탁기관) 시에는 자료의 기준일자를 Set한다. + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전체 전문 길이 + //공통부와 업무정보부를 합한 전체길이. + //프로토콜이 TCP/IP 인 경우만 Set 한다. + //compileField(10, ""+SEND_LENGTH, this.al_FieldProps[10]); + compileField(10, "0", this.al_FieldProps[10]); + + + //송수신 업무 구분코드. 한국주택금융공사를 기준으로 하여 해당전문이 송.수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래값 중 해당코드를 Set한다. + //“S” : 화일 송신업무 관련 전문 (한국주택금융공사→위탁기관) + //“R” : 화일 수신업무 관련 전문 (위탁기관→한국주택금융공사) + compileField(11, getFldTrClass() , this.al_FieldProps[11]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(12, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[12]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “008”: 송신 시작 요구 + // “301”: 업무 장애 회복 확인 + compileField(13, this.getFldOpCode(), this.al_FieldProps[13]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(14, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[14]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(15, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[15]); + + //송신 집계 내역 - 개별업무 종료(0600/003)시만 사용하는 Field로 전송된 Record Count를 Set한다. + compileField(16, "" ,this.al_FieldProps[16]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return 0; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(13); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0620.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0620.java new file mode 100644 index 0000000..04170d5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0620.java @@ -0,0 +1,219 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_HOUSE_0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //아데나 장비를 위한 전문 길이 필드 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + //Transaction Code - 해당 Transaction을 기동하는 코드. LU가 구분 되어 있을 것으로 예상 + // 모기지론 유동화 자료 - HR00FTP + // 주택위탁보증 자료 - HW00FTP + // 학자금 유동화 자료 - SR00FTP + // 학자금위탁보증 자료 - SW00FTP + // U보금자리 - BM00FTP/BM01FTP + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //업무구분코드 - 업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 대외기관을 나타내는 코드로서 세부사항은 표준화 사항의 대외기관코드를 참조한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 - 각 업무 및 화일의 종류를 구분하기 위한 코드로 구성되며 세부내용은 표준화 사항을 참조한다. + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG - 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + // “C” : 한국주택금융공사에서 전문을 발생할 시 + // “B” : 위탁기관에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 - 전문의 처리 결과를 나타내는 응답코드로 세부내용은 표준화 사항의 응답코드를 참조한다. + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //일자 (자료기준일자) - 은행에서 자료보고(위탁기관→주택금융공사) 및 주택금융공사자료통보(주택금융공사→위탁기관) 시에는 자료의 기준일자를 Set한다. + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전체 전문 길이 + //공통부와 업무정보부를 합한 전체길이. + //프로토콜이 TCP/IP 인 경우만 Set 한다. + //compileField(10, ""+SEND_LENGTH, this.al_FieldProps[10]); + compileField(10, "0", this.al_FieldProps[10]); + + //송수신 업무 구분코드. 한국주택금융공사를 기준으로 하여 해당전문이 송.수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래값 중 해당코드를 Set한다. + //“S” : 화일 송신업무 관련 전문 (한국주택금융공사→위탁기관) + //“R” : 화일 수신업무 관련 전문 (위탁기관→한국주택금융공사) + compileField(11, getFldTrClass() , this.al_FieldProps[11]); + + //Block-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[12]); + + //Sequence-NO + compileField(13, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[13]); + + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.debug("[SEND_HOUSE_0620]" + e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0800.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0800.java new file mode 100644 index 0000000..7525185 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0800.java @@ -0,0 +1,205 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; +import java.util.Random; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0800 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_HOUSE_0800() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 --일단은 오늘날짜를 보내도록하자 + compileField(8, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(10, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[11]); + + //전문 추적 번호 - + compileField(11, "" + this.getTrcNo(), this.al_FieldProps[12]); + + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private long getTrcNo(){ + long randomLong = 0; + randomLong = ( new Random().nextLong()) % 100000000; + + return randomLong; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0810.java b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0810.java new file mode 100644 index 0000000..1bedde1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/house/SEND_HOUSE_0810.java @@ -0,0 +1,205 @@ +package com.eactive.eai.batch.job.jobItem.house; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_HOUSE_0810 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_HOUSE_0810() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 --일단은 오늘날짜를 보내도록하자 + compileField(8, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(10, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[10]); + + //전문 추적 번호 - + compileField(11, "" + this.getTrcNo(), this.al_FieldProps[11]); + + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { //한국주택금융공사 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private long getTrcNo(){ + String recvTrcNo = batchDoc.getBatchMsg().getTelegramBody().substring( 10 ); + try{ + long randomLong = Long.parseLong( recvTrcNo ); + return randomLong; + } catch ( Exception e){ + return 0; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(11); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT.java b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT.java new file mode 100644 index 0000000..2f75eb0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT.java @@ -0,0 +1,77 @@ +package com.eactive.eai.batch.job.jobItem.insure; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +public class RECV_INSBT extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : 퇴직연금용 길이결정용 텔레그램 클래스 이다. + */ + public RECV_INSBT() { + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(7); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(11); + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=2; i getCalculatedLength() -> doInformalField() -> doExecute() -> doValidation() -> doPostExecute() + //============================================================================================================================ + + /** + * doPreExecute() 부모클래스의 기본 수행을 호출해 준 후, 0600 전문 수신의 특이 사항을 수행한다. + * 0600 전문의 특이사항은 실질적인 파일 수신시 Write할 파일을 열어주는 것이다. (FileOutputStream) + */ + public boolean doPreExecute() + { + if (!super.doPreExecute()) return false; + return true; + } + + public boolean doPreExecuteAfterCopy() + { + if (!super.doPreExecuteAfterCopy()) return false; + + //1. 파일명 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '파일명' 전문필드 값 Checking......", logHeader); + String bizCode = new String((byte[])al_Field.get( 8)).trim(); //거래구분코드 + String fileName = new String((byte[])al_Field.get(19)).trim(); //파일명 + + batchDoc.getBatchMsg().getHeader().setFileName(fileName); //배치메시지에 파일명 설정 + + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + + //2. 수신파일 저장 경로 설정 + //저장 디렉토리는 Inbound Server 에서 설정됨 (응답수신 Real 또는 응답송신 Real) + this.strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + String dirDelimiter = StringUtil.getDirDelimiter(this.strFullPathName); + if (!this.strFullPathName.endsWith(dirDelimiter)) this.strFullPathName += dirDelimiter; + + + //3. 거래구분코드에 대한 작업구분코드 설정 + BatchJobInfoVO jobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + logger.info("{} 거래구분코드 : ["+ bizCode +"]", logHeader); + if (jobInfo == null) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI040", new String[] {fileName, processCode, bizCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일 [{1}] 에 해당하는 JOB_CODE를 찾을수 없습니다. [ProcessCode: {2}] [BizCode: {3}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + logger.info("{} 작업구분코드 : ["+ jobInfo.getMsgDstCode() +"]", logHeader); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + batchDoc.getBatchMsg().getHeader().setJobCode(jobInfo.getMsgDstCode()); + batchDoc.getBatchMsg().getHeader().setRecLen((int)jobInfo.getFileRecSize()); + + + + this.strFullPathName += fileName; + logger.info("{} 응답수신 파일 저장 경로 : [" + this.strFullPathName + "]", logHeader); + rcvRealFile = new File( this.strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + try { + rcvArchFile = new File( StringUtil.replaceStr(this.strFullPathName, BatchDirUtil.getResponseRealDir(), BatchDirUtil.getResponseArchDir()) ); + rcvErrorFile = new File( StringUtil.replaceStr(this.strFullPathName, BatchDirUtil.getResponseRealDir(), BatchDirUtil.getResponseErrorDir()) ); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + + + //7. 응답수신 파일 생성 + logger.info("{} >>>>> 응답수신 파일 생성...... ("+ this.strFullPathName +")", logHeader); + try { + fout = new FileOutputStream(rcvRealFile); + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI041", new String[] {rcvRealFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 해당 경로에 생성시 오류가 발생하였습니다. [Path : {1}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); //기타오류 + return false; + } + + + //8. 응답수신 파일 Start DB로그 + logger.info("{} >>>>> 응답수신 파일 Start DB로그......", logHeader); + try { + LogUtil.setLogFileStart(batchDoc); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 Start DB로그 수행시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI021", new String[] {processCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); //기타오류 + return false; + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + try { + int nDefiniteLength = 0; + //퇴직연금에서는 마지막에 define 되어 있는 것으로 한다. + for (int i=0; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + nDefiniteLength += aField.length; + } + logger.info("{} INFORMAL 필드 이전에 읽어들인 Byte Length : [" + nDefiniteLength + "]", logHeader); + + String strLength = super.getFieldValueString(batchDoc.getBatchMsg().getPhaseinfo().getLengthFieldIndex()-1); + logger.info("{} HEADER 의 '전문길이' 필드 값 : [" + nDefiniteLength + "]", logHeader); + + int nTotalLength = Integer.parseInt(strLength); + batchDoc.getBatchMsg().getHeader().setFileSize(nTotalLength - nDefiniteLength); //파일사이즈 설정 (전송 진행상태 확인용) + logger.info("{} INFORMAL 필드에서 읽어들일 Byte Length : [" + (nTotalLength - nDefiniteLength) + "]", logHeader); + return (nTotalLength - nDefiniteLength); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 수신 파일 사이즈 계산 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + //파일 끝에 append + fout.write(data, 0, length); + + //읽어 들인 파일 사이즈 저장 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch (Exception ex) { + logger.error("{} ★★★★★ 수신 파일 데이터 WRITE 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //1. 수신 파일 Close =========================================================== + if (fout != null) fout.close(); + + //2. 수신 파일 End DB로그 ====================================================== + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //DB로그에 남길 파일 사이즈 설정 + batchDoc.getBatchMsg().getHeader().setFileSize(rcvRealFile.length()); + try { + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(rcvRealFile.length()/recLen); + } catch (Exception e) { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + } + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + } + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) ) { + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(퇴직연금 서버에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPathName) ); + rcvRootFile.createNewFile(); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + + return true; + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(7); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(11); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0610.java b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0610.java new file mode 100644 index 0000000..4227005 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0610.java @@ -0,0 +1,67 @@ +package com.eactive.eai.batch.job.jobItem.insure; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; + + +public class RECV_INSBT_0610 extends DefaultTelegram implements TelegramService +{ + public RECV_INSBT_0610() { + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + if (!super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) return false; + + return true; + } + + /** + * doPostExecute + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + ///////////////////////////////////////////////////////////// + logger.info("{} doPostExecute called : 파일전송 성공 ", logHeader); + // File Open LOG + LogUtil.setLogFileEnd(batchDoc); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(7); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(11); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0800.java b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0800.java new file mode 100644 index 0000000..248774d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0800.java @@ -0,0 +1,97 @@ +package com.eactive.eai.batch.job.jobItem.insure; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * 퇴직연금용 0800 전문 수신용 텔레그램 클래스 + */ +public class RECV_INSBT_0800 extends DefaultTelegram implements TelegramService +{ + //>> 거래구분코드 정의 + // 업무개시 + private final String TrClass_start = "061000"; + private final String TrClass_end = "063000"; + + /** + * 생성자 + */ + public RECV_INSBT_0800() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + //거래구분코드 체크 + String bizCode = this.getTrClass(); + if (bizCode.equalsIgnoreCase(this.TrClass_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + + } else if(bizCode.equalsIgnoreCase(this.TrClass_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + + } else { + logger.info("{} 0800 telegram : unknown trasaction classification code received >> "+this.getTrClass(), logHeader); + } + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * doPostExecute + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 수신길이 계산 + */ + public int getCalculatedLength(int idx) { + logger.info("{} getCalculatedLength unexpectedly called : idx = " + idx, logHeader); + return 0; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(7); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(11); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0810.java b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0810.java new file mode 100644 index 0000000..6adea28 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/insure/RECV_INSBT_0810.java @@ -0,0 +1,101 @@ +package com.eactive.eai.batch.job.jobItem.insure; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_INSBT_0810 extends DefaultTelegram implements TelegramService +{ + //>> 거래구분코드 정의 + // 업무개시 + private final String TrClass_start = "061000"; + private final String TrClass_end = "063000"; + + /** + * 생성자 + */ + public RECV_INSBT_0810() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + if (this.getTrClass().equalsIgnoreCase(this.TrClass_start)) { + logger.info("{} BATCH JOB : START request received", logHeader); + } else if (this.getTrClass().equalsIgnoreCase(this.TrClass_end)) { + logger.info("{} BATCH JOB : END request received", logHeader); + } else { + logger.info("{} 0810 telegram : unknown trasaction classification code received >> "+this.getTrClass(), logHeader); + String errMsg = ExceptionUtil.getErrorCode ("BECEAIFJI015", new String[] { this.batchDoc.getBatchMsg().getHeader().getProcessCode(), this.getTrClass() }); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + + // 응답코드에 대한 처리는 RULE 로 처리됨. + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //요구전문의 응답전문에 대한 Validation 실패시 요구송신 Process 종료 (return false) + //(전문헤더 Validation은 RECV_T_RTMPS 클래스에서 수행되어 응답코드가 설정됨) + if (!super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) return false; + + return true; + } + + /** + * doPostExecute + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + ///////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////// + logger.info("{} doPostExecute called", logHeader); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 수신길이 계산 + */ + public int getCalculatedLength(int idx) { + logger.info("{} getCalculatedLength unexpectedly called : idx = " + idx, logHeader); + return 0; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(7); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(8); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(11); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/insure/SEND_INSBT_0600.java b/src/com/eactive/eai/batch/job/jobItem/insure/SEND_INSBT_0600.java new file mode 100644 index 0000000..e677447 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/insure/SEND_INSBT_0600.java @@ -0,0 +1,262 @@ +package com.eactive.eai.batch.job.jobItem.insure; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_INSBT_0600 extends DefaultTelegram implements TelegramService +{ + private Properties telegramInfo; + private String filename; + private File f; + private FileInputStream fin ; + private long fileSize = 0; + + public SEND_INSBT_0600() { + } + + + /** + * 지정된 전문의 구성 필드 배열 선언, 요구송신 파일 Start DB로그 + */ + public boolean doPreExecute() { + if (!super.doPreExecute()) return false; + + //요구송신 파일 Start DB로그 + try { + telegramInfo = getTelegramInfo(); + LogUtil.setLogFileStart(batchDoc); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI021"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + return true; + } + + public boolean doExecute() { + try { + + String strFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} [0600] telegram : filename [" + strFileName + "]", logHeader); + // + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + long lnLength = this.getSendLength(); + compileField(2, String.valueOf(lnLength), this.al_FieldProps[2]); + // 자료구분 (HDB_DAT_GBN), "T" + compileField(3, telegramInfo.getProperty(TelegramKeys.DAT_GBN), this.al_FieldProps[3]); + // ins_id 보험사기관 ID char 3 AN MY_INST_CODE false 0 0 KHG + compileField(4, telegramInfo.getProperty(TelegramKeys.HDB_SND_ID), this.al_FieldProps[4]); + // bak_cls 은행 구분 char 2 AN INST_TYPE false 0 0 bak_cls + compileField(5, telegramInfo.getProperty(TelegramKeys.HDB_SND_CLS), this.al_FieldProps[5]); + // bak_id 은행 ID char 3 AN OTHER_INST_CODE false 0 0 bak_id + compileField(6, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[6]); + // doc_code 전문종별 코드 char 4 AN KIND_CODE false 0 0 doc_code + compileField(7, this.getFldTelegramType(), this.al_FieldProps[7]); + // biz_code 거래구분 코드 char 6 AN TX_CODE false 0 0 biz_code + compileField(8, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[8]); + // tra_flag 송수신 FLAG numeric 1 NN SNR_TYPE false 0 0 tra_flag 5 + compileField(9, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[9]); + // doc_status STATUS numeric 3 NN false 0 0 000 + compileField(10, "000", this.al_FieldProps[10]); + // ret_code 응답코드 char 3 AN RESPONSE_CODE false 0 0 ret_code + compileField(11, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[11]); + // snd_date 전문전송일 numeric 8 NN false 0 0 $DATE(YYYYMMDD) + compileField(12, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[12]); + // snd_time 전문전송시간 numeric 6 NN false 0 0 $TIME(hhmmss) + compileField(13, TelegramKeys.getHHMMSS(), this.al_FieldProps[13]); + // bak_docseq 은행 전문번호 numeric 8 NN false 0 0 00000000 + compileField(14, "0000000", this.al_FieldProps[14]); + // ins_docseq 보험사 전문번호 numeric 8 NN false 0 0 00000000 + compileField(15, TelegramKeys.RPS_HDB_RSV_DOCSEQ, this.al_FieldProps[15]); + // txn_date 거래발생일 numeric 8 NN TX_DATE false 0 0 txn_date + compileField(16, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[16]); + // tot_file 전체 파일 수 numeric 2 NN false 0 0 01 + compileField(17, "01", this.al_FieldProps[17]); + // cur_file 현재 파일 순번 numeric 2 NN false 0 0 01 + compileField(18, "01", this.al_FieldProps[18]); + // doc_name 현재 파일명 char 30 AN FILE_NAME false 0 0 doc_name + compileField(19, strFileName, this.al_FieldProps[19]); + // cur_tot 현재파일전체전문수 numeric 2 NN TOT_BLOCK_NO false 0 0 cur_tot + compileField(20, "01", this.al_FieldProps[20]); + // cur_now 현재파일현재순번 numeric 2 NN CUR_BLOCK_NO false 0 0 cur_now + compileField(21, "01", this.al_FieldProps[21]); + // doc_case 전문CASE명 char 6 AN false 0 0 doc_case + compileField(22, "", this.al_FieldProps[22]); + // bak_ext 은행추가정의 char 30 AN false 0 0 bak_ext + compileField(23, TelegramKeys.RPS_HDB_SND_EXT, this.al_FieldProps[23]); + // ins_ext 보험사추가정의 char 30 AN false 0 0 ins_ext + compileField(24, TelegramKeys.RPS_HDB_RSV_EXT, this.al_FieldProps[24]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + return false; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + int nSumFormalField = 0; + for (int i=0; i 이전문은 실질 응답 전문이다. 따라서.. 대부분의 값은 복사해서 사용하고 + * 응답 코드만 잘 처리해주면 된다. + */ + public String getSendResponseCode() + { + return TelegramKeys.RPS_HDB_RET_CODE_SUCCESS; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() { + int nSumFormalField = 0; + for (int i=0; i 정영우 과장과 협의하여 현재 처리방식 검토후 결정 : 일단 정상처리 + // + // 퇴직연금 만의 응답코드 계산 로직을 만들 것... + // + return TelegramKeys.RPS_HDB_RET_CODE_SUCCESS; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() { + int nSumFormalField = 0; + for (int i=0; i= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i" + seq_cnt); + logger.debug("[RECV_KEDBT_0300]recv_missing_count--->" + recv_missing_count); + + if (recv_missing_count == 0 ) { + if (!checkFileEOF()) { + return false; + } + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + + } else if (recv_missing_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_missing_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + logger.debug("[RECV_KEDBT_0300]batchDoc.getBatchMsg().getHeader().getFileSize() --->" + batchDoc.getBatchMsg().getHeader().getFileSize()); + logger.debug("[RECV_KEDBT_0300]batchDoc.getBatchMsg().getBody().getCurFileSize()--->" + batchDoc.getBatchMsg().getBody().getCurFileSize()); + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.EOF); + return; + + /* + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + LogUtil.setLogFileEnd(batchDoc); + String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID(); + String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath()); + batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName()); + batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getEAIBatchMessage().getHeader().setFileSize(0); + batchDoc.getEAIBatchMessage().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + + } + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0310.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0310.java new file mode 100644 index 0000000..94e8369 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0310.java @@ -0,0 +1,237 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0310 extends DefaultTelegram implements TelegramService +{ + + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_KEDBT_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(6)); + String _seq_no = new String ((byte[]) al_Field.get(7)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_no == 0 ){ + block_no = 1; + } + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + if ( recv_block_no != block_no ){ + // 현재 처리중인 블럭이 아니면 무시 + return true; + } + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + //결번 테스트용 +// if ( Math.random() > 0.6 ){ +// } + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + bout.write(data, 0, length); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0320.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0320.java new file mode 100644 index 0000000..566e82e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0320.java @@ -0,0 +1,232 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0320 extends DefaultTelegram implements TelegramService +{ + + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_KEDBT_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(6)); + String _seq_no = new String ((byte[]) al_Field.get(7)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_no == 0 ){ + block_no = 1; + } + + if ( recv_block_no != block_no ){ + +// this.setConditionTxt(TelegramKeys.ERROR); +// +// String[] msgArgs = new String[3]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = _block_no; +// msgArgs[2] = ""+block_no; +// String errCode = "BECEAIFJI024"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return true; + + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + //결번 테스트용 +// if ( Math.random() > 0.6 ){ +// } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + bout.write(data, 0, length); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0600.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0600.java new file mode 100644 index 0000000..5392fe4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0600.java @@ -0,0 +1,148 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0600 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setTRXID(new String((byte[])this.al_Field.get(1))); + batchDoc.getBatchMsg().getHeader().setBaseDate(new String((byte[])this.al_Field.get(8))); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0610.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0610.java new file mode 100644 index 0000000..12acc94 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0610.java @@ -0,0 +1,145 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0610 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0620.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0620.java new file mode 100644 index 0000000..b5b7168 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0620.java @@ -0,0 +1,185 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(7)); + String _seq_no = new String ((byte[]) al_Field.get(8)); + + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0700.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0700.java new file mode 100644 index 0000000..683808a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0700.java @@ -0,0 +1,200 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0700 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0700() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + + String fileName = new String ((byte[]) al_Field.get(5)); + batchDoc.getBatchMsg().getHeader().setBizCode(fileName); + long recCnt = 0; + try { + recCnt = Long.parseLong(new String ((byte[]) al_Field.get(10))) + 2; + } catch (Exception e) {} + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), fileName); + if (info != null) { + batchDoc.getBatchMsg().getHeader().setJobCode(info.getMsgDstCode()); + int recSize = (int)info.getFileRecSize(); + batchDoc.getBatchMsg().getHeader().setRecLen(recSize); + batchDoc.getBatchMsg().getHeader().setFileSize(recSize * recCnt); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + + } else { + logger.debug("{} " + batchDoc.getBatchMsg().getHeader().getUUID()+ "'s Job Code is null", logHeader); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + batchDoc.getBatchMsg().getHeader().setJobCode((processCode+"00000")); //dummy code + // TEST 용 return false; + } + + batchDoc.getBatchMsg().getHeader().setFileName(fileName); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+fileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + fileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + file.createNewFile(); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0710.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0710.java new file mode 100644 index 0000000..748dbbc --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0710.java @@ -0,0 +1,155 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0710 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0710() { + //화일정보수신통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + if ( !getResCode().equals("000") ){ + String[] msgArgs = new String[1]; + msgArgs[0] = getResCode(); + String errCode = "BECEAIFRS021"; + String errMsg = ExceptionUtil.getErrorCode ( errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0720.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0720.java new file mode 100644 index 0000000..73cf1e0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0720.java @@ -0,0 +1,145 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0720 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0720() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + batchDoc.getBatchMsg().getBody().setRecvFld01(new String((byte[])this.al_Field.get(1))); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0730.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0730.java new file mode 100644 index 0000000..ea6fbee --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0730.java @@ -0,0 +1,169 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0730 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0730() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + // File Open LOG + File ff = new File(fileName); + + if (ff.exists()) { + logger.info("{} FILE SIZE ("+ ff.length() + "]", logHeader); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(ff); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileEnd(batchDoc); + this.setConditionTxt(TelegramKeys.NOFILE); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0800.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0800.java new file mode 100644 index 0000000..78e383b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0800.java @@ -0,0 +1,145 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0800 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0800() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + batchDoc.getBatchMsg().getBody().setRecvFld01(new String((byte[])this.al_Field.get(1))); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0810.java b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0810.java new file mode 100644 index 0000000..a524fb9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/RECV_KEDBT_0810.java @@ -0,0 +1,144 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KEDBT_0810 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KEDBT_0810() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0300.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0300.java new file mode 100644 index 0000000..022d477 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0300.java @@ -0,0 +1,395 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_KEDBT_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + + //BLOCK-NO + compileField(7, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[7]); + + //SEQUENCE-NO + compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]); + + //결번갯수 + compileField(9, MISSING_FIELD, this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + batchDoc.getBatchMsg().getBody().setBlockNum(block_no + 1); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int telegramSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + + return telegramSize - preFldTotSize; + + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. + SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); +// int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[block_size]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + int dataOffset = 0; + try { + dataOffset = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.KED_DATA_OFFSET)); + } catch (Exception e) { + logger.info( e.getMessage(), e); + } + + for (int i = 0; i < SEQUENCE_NO; i++) { //받은 seq_no만큼만 데이터 확인하여 기록 + byte[] data = (byte[]) block_data.get(new Integer(i)); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recLen < 1 ){ + recLen = data.length; + } + byte[]layout = new byte[recLen]; + for (int inx = 0; inx < layout.length; inx++) { + layout[inx] = ' '; + } + + int dataCnt = data.length / recLen ; + for (int jnx = 0; jnx < dataCnt; jnx++) { + System.arraycopy( data,jnx*layout.length + dataOffset,layout,0,layout.length); + if ( !(new String(layout)).trim().equals("") ){ + fout.write(layout); + fout.write( '\n' ); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+recLen; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + } + } + + } + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); //데이터 기록후 Vector 초기화 + } + + this.MISSING_FIELD = new String (_missingNm); + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(MISSING_COUNT); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(MISSING_FIELD); + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI027"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean createFile () { + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0310.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0310.java new file mode 100644 index 0000000..ad46f76 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0310.java @@ -0,0 +1,322 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KEDBT_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //BLOCK-NO + compileField(6, ""+BLOCK_NO, this.al_FieldProps[6]); + //SEQUENCE-NO + compileField(7, ""+SEQUENCE_NO, this.al_FieldProps[7]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + for (int inx = REAL_BYTE; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int telegramSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + + return telegramSize - preFldTotSize; + + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. + SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0320.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0320.java new file mode 100644 index 0000000..4f524f6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0320.java @@ -0,0 +1,408 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0320 extends DefaultTelegram implements TelegramService +{ + + private BufferedInputStream bis; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KEDBT_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //BLOCK-NO + compileField(6, ""+BLOCK_NO, this.al_FieldProps[6]); + //SEQUENCE-NO + compileField(7, ""+SEQUENCE_NO, this.al_FieldProps[7]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + for (int inx = REAL_BYTE; inx < fldLen; inx++) { + data[inx] = ' '; + } + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int telegramSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + + return telegramSize - preFldTotSize; + + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( getCalculatedLength(al_Field.size()-1) / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(bis); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + if ( isLastSeq ){ + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. + SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0600.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0600.java new file mode 100644 index 0000000..8e2cb6c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0600.java @@ -0,0 +1,259 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, "", this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + + //관리 Command - 사용하지 않는 Field로 Space로 처리 + compileField(7, "", this.al_FieldProps[7]); + + //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. + SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + int telegramSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + logger.debug("[" + i + "]-->" + aField.length ); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0610.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0610.java new file mode 100644 index 0000000..f4a93f4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0610.java @@ -0,0 +1,257 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, "", this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + +// //관리 Command - 사용하지 않는 Field로 Space로 처리 +// compileField(7, "", this.al_FieldProps[7]); +// +// //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) +// compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + SEND_LENGTH = 0; + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 22; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0620.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0620.java new file mode 100644 index 0000000..a663c58 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0620.java @@ -0,0 +1,258 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + + //BLOCK-NO + compileField(7, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[7]); + + //SEQUENCE-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[8]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. + SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int telegramSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + + return telegramSize - preFldTotSize; + + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0700.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0700.java new file mode 100644 index 0000000..2d02621 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0700.java @@ -0,0 +1,269 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0700 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0700() { + //개별업무 개시 통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + + //관리 Command - 사용하지 않는 Field로 Space로 처리 + compileField(7, "", this.al_FieldProps[7]); + + //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //자료명칭 - 사용하지 않는 Field로 Space로 처리 + compileField(9, "", this.al_FieldProps[9]); + + //자료수 - 전송할 Data 총 건수(0700,0710 전문에만 적용) + compileField(10, ""+ (batchDoc.getBatchMsg().getHeader().getTotRecCnt() - 2 ), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. + SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int telegramSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + + return telegramSize - preFldTotSize; + + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0710.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0710.java new file mode 100644 index 0000000..ef1da04 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0710.java @@ -0,0 +1,271 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0710 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_KEDBT_0710() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + + //관리 Command - 사용하지 않는 Field로 Space로 처리 + compileField(7, "", this.al_FieldProps[7]); + + //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //자료명칭 - 사용하지 않는 Field로 Space로 처리 + compileField(9, "", this.al_FieldProps[9]); + + //자료수 - 전송할 Data 총 건수(0700,0710 전문에만 적용) + compileField(10, ""+ batchDoc.getBatchMsg().getHeader().getTotRecCnt(), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. + SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int telegramSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + + return telegramSize - preFldTotSize; + + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0720.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0720.java new file mode 100644 index 0000000..27040d9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0720.java @@ -0,0 +1,259 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0720 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0720() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, "", this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + +// //관리 Command - 사용하지 않는 Field로 Space로 처리 +// compileField(7, "", this.al_FieldProps[7]); +// +// //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) +// compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { +// // KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. +// SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + SEND_LENGTH = 0; + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return 0; + + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0730.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0730.java new file mode 100644 index 0000000..da21a99 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0730.java @@ -0,0 +1,304 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0730 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0730() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, batchDoc.getBatchMsg().getBody().getRecvFld01(), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, "", this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + +// //관리 Command - 사용하지 않는 Field로 Space로 처리 +// compileField(7, "", this.al_FieldProps[7]); +// +// //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) +// compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + SEND_LENGTH = 0; + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return 0; + + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0800.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0800.java new file mode 100644 index 0000000..430b4ba --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0800.java @@ -0,0 +1,259 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0800 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0800() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, "", this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + +// //관리 Command - 사용하지 않는 Field로 Space로 처리 +// compileField(7, "", this.al_FieldProps[7]); +// +// //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) +// compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { +// KED 모든 전문은 길이가 4000바이트로 고정되어 있으며 이를 SequenceSize 로 지정하기로 한다. +// SEND_LENGTH = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + SEND_LENGTH = 0; + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return 0; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0810.java b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0810.java new file mode 100644 index 0000000..9619af8 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ked/SEND_KEDBT_0810.java @@ -0,0 +1,258 @@ +package com.eactive.eai.batch.job.jobItem.ked; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KEDBT_0810 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KEDBT_0810() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션ID - KED 및 회원사에서 업무구분을 위하여 SET하는 문자이다. + // 회원사에서 KED에 파일 송신시 : “CB02" + // KED에서 회원사에 파일 송신시 : “RB02" + compileField(1, batchDoc.getBatchMsg().getBody().getRecvFld01(), this.al_FieldProps[1]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 - 전문의 처리결과를 나타내는 코드로 REQUEST전문(지시 및 요구전문)에는 “000”을 SET하며 RESPONSE전문(통보 및 보고전문)에서는 해당내용을 SET한다. + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //회원사 코드 - 전문을 전송한 기관을 확인하기 위한 회원사 코드 이다. + compileField(4, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[4]); + + //파일명 - 0600/0610/0800/0810 전문의 경우 Space 처리함 + compileField(5, "", this.al_FieldProps[5]); + + //전문전송 일시 - 전문을 발신하는 회원사에서 전문을 전송하는 일자와 시간을 SET 한다. + compileField(6, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[6]); + +// //관리 Command - 사용하지 않는 Field로 Space로 처리 +// compileField(7, "", this.al_FieldProps[7]); +// +// //자료일자 - 전문을 송/수신하는 기준 연월일(YYYYMMDD) +// compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<6; i++) { //KED전문의 헤더는 파일명까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=6; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + SEND_LENGTH = 0; + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + // X.25 이므로 아데나 장비용 길이 바이트를 추가 + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return 0; + + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(10); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0300.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0300.java new file mode 100644 index 0000000..3dc122b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0300.java @@ -0,0 +1,196 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KFB0300 extends DefaultTelegram implements TelegramService { + + private int INFORMALFIELD_INDEX = 14; + + /** + * 생성자 + */ + public RECV_KFB0300() { + //결번확인통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _missing_count = new String ((byte[]) al_Field.get(13)); + String missing_field = new String ((byte[]) al_Field.get(14)); + + int recv_migging_count = Integer.parseInt(_missing_count); + + if (recv_migging_count == 0 ) { + checkFileEOF(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String byte_size = new String ((byte[]) al_Field.get(1)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkFileEOF() { + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() + + batchDoc.getBatchMsg().getHeader().getRecLen() + >= batchDoc.getBatchMsg().getHeader().getFileSize() ){ + this.setConditionTxt(TelegramKeys.EOF); + } + return; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0310.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0310.java new file mode 100644 index 0000000..d3eaf8b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0310.java @@ -0,0 +1,247 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFB0310 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 14; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_KFB0310() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(11)); + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (((recv_block_no - block_no) > 1 ) || ((recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + return false; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(1)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0320.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0320.java new file mode 100644 index 0000000..dae12f6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0320.java @@ -0,0 +1,384 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFB0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 14; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; + + /** + * 생성자 + */ + public RECV_KFB0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + String fName = new String ((byte[]) al_Field.get(5)); + String baseDate = new String ((byte[]) al_Field.get(8)); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bJobInfo.getFileRecSize()); + }else{ + batchDoc.getBatchMsg().getHeader().setRecLen(Integer.parseInt(super.getFieldValueString(9))); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(11)); + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (( recv_block_no != 9999 ) && ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(11)); + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ +// } else if ( ( recv_block_no > 0) && (recv_seq_no > 1) ){ // 강제 결번 테스트용 + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(1)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + al_Field.set(idx, bout.toByteArray()); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + //DB로그에 남길 파일 사이즈 설정 + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getBody().getCurFileSize()); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recLen > 0 ){ + int recCnt = (int)batchDoc.getBatchMsg().getBody().getCurFileSize()/recLen; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + } + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.KFB_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0330.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0330.java new file mode 100644 index 0000000..262f5c7 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0330.java @@ -0,0 +1,193 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_KFB0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_KFB0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(11).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + } else if (super.getFieldValueString(11).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + this.setConditionTxt(TelegramKeys.NOFILE); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(1)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + /* + private boolean checkMoreFile(){ + return false; + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return false; + } + String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID(); + String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + logger.debug("UUID추적:[ScheduleHandlerProcess]:uuid["+info.getUUID() +"]"); + logger.debug("UUID추적:[ScheduleHandlerProcess]:subuuid["+info.getSubUUID() +"]"); + + //BatchMsgDoc 값 설정 + batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath()); + batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName()); + batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode()); + batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW()); + + + + } catch ( Exception e){ + return false; + + } + return true; + } + */ + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0600.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0600.java new file mode 100644 index 0000000..36d8c5f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0600.java @@ -0,0 +1,121 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KFB0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_snd_req = "008"; //송신시작요구 + private final String OpCode_chk_down = "301"; //업무 장애 회복 확인 + + /** + * 생성자 + */ + public RECV_KFB0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_snd_req)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_chk_down)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.KFB_RET_CODE_TGRAM_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0610.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0610.java new file mode 100644 index 0000000..1a8dc02 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0610.java @@ -0,0 +1,121 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KFB0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_snd_req = "008"; //송신시작요구 + private final String OpCode_chk_down = "301"; //업무 장애 회복 확인 + + /** + * 생성자 + */ + public RECV_KFB0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_snd_req)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_chk_down)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.KFB_RET_CODE_TGRAM_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0620.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0620.java new file mode 100644 index 0000000..5dc6f75 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0620.java @@ -0,0 +1,120 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KFB0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_KFB0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(11)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(12)); // 0 base 인덱스 + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0800.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0800.java new file mode 100644 index 0000000..f641cdc --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0800.java @@ -0,0 +1,88 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KFB0800 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_KFB0800() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(5)); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0810.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0810.java new file mode 100644 index 0000000..abe4ad2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_KFB0810.java @@ -0,0 +1,88 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KFB0810 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_KFB0810() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().getHeader().setBizCode(super.getFieldValueString(5)); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_T_KFB.java b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_T_KFB.java new file mode 100644 index 0000000..6ba1e38 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/RECV_T_KFB.java @@ -0,0 +1,75 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_T_KFB extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 은행연합회 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_T_KFB() { + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(4).equalsIgnoreCase("0600") ||super.getFieldValueString(4).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(12); + } + else { + return super.getOpCode(); + } + } + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=2; i= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return MISSING_FIELD.length(); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0310.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0310.java new file mode 100644 index 0000000..24ba739 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0310.java @@ -0,0 +1,346 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFB0310 extends DefaultTelegram implements TelegramService { + + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KFB0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+SEQUENCE_NO , this.al_FieldProps[12]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(13, "" + recCnt, this.al_FieldProps[13]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug( logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0320.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0320.java new file mode 100644 index 0000000..3b2f357 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0320.java @@ -0,0 +1,500 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_KFB0320 extends DefaultTelegram implements TelegramService { + + private BufferedInputStream bis; + private File file; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KFB0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[12]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(13, "" + recCnt, this.al_FieldProps[13]); + + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num > 0 && block_num < 9999) { + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (bis != null ) { + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + private boolean createFile () + { + + try { + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( bis == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int sequence_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + this.setConditionTxt(""); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + fileData = new byte[sequence_size + 1]; // 파일의 한 라인당 길이 + 개행문자 1바이트 + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + byte[] fileLine = FileUtil.readLine(bis); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + + fileData = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + byte[] fileLine = FileUtil.readLine(bis); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + try{ + Properties jobInfo = getJobInfo(); + seqCnt = Integer.parseInt(jobInfo.getProperty(TelegramKeys.BLOCKING_COUNT)); + }catch (Exception e){} + + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + if ( seqCnt < remainCnt - 1){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)(remainCnt - 1) * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(bis); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1) , fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + REAL_BYTE = fileData.length; + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0330.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0330.java new file mode 100644 index 0000000..577bf3a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0330.java @@ -0,0 +1,314 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFB0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFB0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + recvTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + + REAL_BYTE = recvTelegramBody.length() - 11; + + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + // --받은 내용을 그대로 돌려 보내기 + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[12]); + + //Record 수 --받은 내용을 그대로 돌려 보내기 + compileField(13, recvTelegramBody.substring(8,11), this.al_FieldProps[13]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(11)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + } else if ( recv_block_no == 9999 ) { + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getBody().getCurFileSize()); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recLen > 0 ){ + int recCnt = (int)batchDoc.getBatchMsg().getBody().getCurFileSize()/recLen; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + } + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + //여기에서 파일을 연다. + return REAL_BYTE; + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + System.arraycopy(recvTelegramBody.getBytes(), 11, data, 0, REAL_BYTE ); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0600.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0600.java new file mode 100644 index 0000000..c4a791c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0600.java @@ -0,0 +1,227 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFB0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFB0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(11, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[11]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “008”: 송신 시작 요구 + // “301”: 업무 장애 회복 확인 + compileField(12, this.getFldOpCode(), this.al_FieldProps[12]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(13, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[13]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(14, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[14]); + + //송신 집계 내역 - 개별업무 종료(0600/003)시만 사용하는 Field로 전송된 Record Count를 Set한다. + if ( this.getFldOpCode().equalsIgnoreCase(OpCode_unit_end) ) + compileField(15, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[15]); + else + compileField(15, "" ,this.al_FieldProps[15]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + + if (CommonKeys.PROCESS_REQUEST_RECEIVE.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + String filename = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( filename.length() == 14){ + batchDoc.getBatchMsg().getHeader().setBaseDate( filename.substring(6)); + } else { + batchDoc.getBatchMsg().getHeader().setBaseDate( TelegramKeys.getYYYYMMDD( 0 ) ); + } + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0610.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0610.java new file mode 100644 index 0000000..615610a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0610.java @@ -0,0 +1,212 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFB0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_KFB0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+SEND_LENGTH, this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(11, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[11]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송?수신 계속 + // “003”: 개별 업무 종료 “008”: 송신 시작 요구 + // “301”: 업무 장애 회복 확인 + compileField(12, this.getFldOpCode(), this.al_FieldProps[12]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(13, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[13]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(14, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[14]); + + //송신 집계 내역 - 개별업무 종료(0600/003)시만 사용하는 Field로 전송된 Record Count를 Set한다. + compileField(15, "", this.al_FieldProps[15]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0620.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0620.java new file mode 100644 index 0000000..f37f8ba --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0620.java @@ -0,0 +1,202 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFB0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFB0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[12]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0800.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0800.java new file mode 100644 index 0000000..82ad1e4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0800.java @@ -0,0 +1,203 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; +import java.util.Random; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFB0800 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFB0800() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 --일단은 오늘날짜를 보내도록하자 + compileField(8, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(10, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[11]); + + //전문 추적 번호 - + compileField(11, "" + this.getTrcNo(), this.al_FieldProps[12]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private long getTrcNo(){ + long randomLong = 0; + randomLong = ( new Random().nextLong()) % 100000000; + + return randomLong; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0810.java b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0810.java new file mode 100644 index 0000000..db99734 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kfb/SEND_KFB0810.java @@ -0,0 +1,204 @@ +package com.eactive.eai.batch.job.jobItem.kfb; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFB0810 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFB0810() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. + compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]); + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 --일단은 오늘날짜를 보내도록하자 + compileField(8, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(10, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[10]); + + //전문 추적 번호 - + compileField(11, "" + this.getTrcNo(), this.al_FieldProps[11]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i < 2 ; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private long getTrcNo(){ + String recvTrcNo = batchDoc.getBatchMsg().getTelegramBody().substring( 10 ); + try{ + long randomLong = Long.parseLong( recvTrcNo ); + return randomLong; + } catch ( Exception e){ + return 0; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB.java new file mode 100644 index 0000000..d6e2b89 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB.java @@ -0,0 +1,167 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_KFTCB extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 : CMS쪽 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_KFTCB() { + } + + public boolean doValidation() + { + if (!super.doValidation()) return false; + + try { + logger.info("{} >>>>> 응답코드 Checking......", logHeader); + int currFiledIndex = 8; + String currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.RES_CODE_SUCESS)) { + String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getCmsRetDescription(currFieldValue); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); // + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + }catch (Exception e){ + logger.error( e.getMessage(), e); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString()); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + return Integer.parseInt( getTelegramInfo().getProperty(propKey) ); + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + idx = vo.getLengthField(); + if (idx == 0) return -1; + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=2; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(1)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=2; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + return; + } + LogUtil.setLogFileEnd(batchDoc); + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){} + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0310.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0310.java new file mode 100644 index 0000000..011349d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0310.java @@ -0,0 +1,254 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFTCB_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_KFTCB_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + try { + if ( getTelegramInfo().getProperty(TelegramKeys.IGNORE_DATA_LEN).equals("Y") ){ + String byte_size = new String ((byte[]) al_Field.get(1)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=2; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } + } catch (Exception e) {} + String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0320.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0320.java new file mode 100644 index 0000000..4614328 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0320.java @@ -0,0 +1,241 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFTCB_0320 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_KFTCB_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + try { + if ( getTelegramInfo().getProperty(TelegramKeys.IGNORE_DATA_LEN).equals("Y") ){ + String byte_size = new String ((byte[]) al_Field.get(1)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=2; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } + } catch (Exception e) {} + String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0600.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0600.java new file mode 100644 index 0000000..16b0d3b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0600.java @@ -0,0 +1,118 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFTCB_0600 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_KFTCB_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0610.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0610.java new file mode 100644 index 0000000..12eb697 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0610.java @@ -0,0 +1,143 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFTCB_0610 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_KFTCB_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + // File Open LOG + File ff = new File(fileName); + + //응답송신이 아니고 0610/0004를 수신하면 (응답송신의 경우 recv0300일경우에 파일을 이동시키므로 이단계에서는 파일이 존재하지 않음 + if (!CommonKeys.PROCESS_RESPONSE_SEND.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + if (ff.exists() && OpCode_noexsist.equals(this.getOpCode())) { + logger.info("{} FILE SIZE ("+ ff.length() + "]", logHeader); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(ff); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + if (OpCode_noexsist.equals(this.getOpCode()) && fileNm != null && !fileNm.trim().equals("")) { + //응답수신 파일 Start DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0620.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0620.java new file mode 100644 index 0000000..e085b97 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0620.java @@ -0,0 +1,129 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFTCB_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KFTCB_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_no == 0 ) + block_no = 1; + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + /// 2013.05.16 + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum (recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0630.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0630.java new file mode 100644 index 0000000..a3311b7 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0630.java @@ -0,0 +1,184 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFTCB_0630 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_KFTCB_0630() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + + String fileInfo = new String ((byte[]) al_Field.get(9)); + String fName = fileInfo.substring(0, 8).trim(); + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_CDCMS_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + } + + String pattern = null; + long recLen = 0; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + +// String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); +// logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if(fileDir.length() < 1) {// FilePath 셋팅없이 온경우 20231124 + String strPathName = BatchDirUtil.getResponseRealDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + StringBuffer sb = new StringBuffer(); + sb.append(processCode); + sb.append("/"); + sb.append(institutionCode); + fileDir = strPathName + sb.toString(); + } + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getHeader().setFileSize(fSize); + long recCnt = 0; + if ( recLen > 0 ){ + recCnt = fSize / recLen; + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0640.java b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0640.java new file mode 100644 index 0000000..406522f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/RECV_KFTCB_0640.java @@ -0,0 +1,310 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KFTCB_0640 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KFTCB_0640() { + //화일정보수신통보 + } + + BufferedInputStream bis; + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String fileInfo = new String ((byte[]) al_Field.get(9)); // 화일정보내역 + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + if (getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_ALREADY_RECEIVED) + ||getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_NOT_REGISTERED)) { //기송신 파일이면 + checkMoreFileinDB(); + } else { + if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면 + + // 레코드 크기 150 + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + // 한번에 블러킹 할 건수 26 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recLen ); + + // 1887600 % ( 150 * 26 ) + if ( fSize % ( recLen * seqCnt ) != 0 ){ + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } + if ( !createFile() ){ + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } + + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + + // 1887600/150= 12584 + int blockSize = batchDoc.getBatchMsg().getHeader().getBlockSize(); + long skipBlockCnt = fSize / ( blockSize * seqCnt * recLen); + + if ( skipBlockCnt > 0 ){ + long iLoopCnt = skipBlockCnt * blockSize * seqCnt; + for( int inx = 0; inx < iLoopCnt; inx++){ + FileUtil.readLine(bis); + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen); + } + batchDoc.getBatchMsg().getBody().setBlockNum((int)skipBlockCnt+1); //기 송신된 블럭 다음부터 송신 + }else{ + batchDoc.getBatchMsg().getBody().setBlockNum(1); + } + + // + int seqSize = recLen * seqCnt; // 3900 + int blockDataSize = blockSize * seqSize; // 390000 + int seqNo = (int)( fSize % blockDataSize ) / seqSize; + + int appendLen = 0; + try { + appendLen = Integer.parseInt(getJobInfo().getProperty(TelegramKeys.APPEND_LL_LEN)); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + for (int inx = 0; inx < seqNo; inx++) { + byte[] fileData = new byte[seqSize]; + for (int jnx = 0; jnx < seqCnt; jnx++) { + byte[] fileLine = FileUtil.readLine(bis); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, jnx * recLen, Math.min(recLen, fileLine.length)); + if ( appendLen > 0 ){ + fileData[((jnx+1) * recLen)-1] = '\n'; + } + if ( appendLen > 1 ){ + fileData[((jnx+1) * recLen)-2] = '\r'; + } + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen); + + } + + block_data.put( new Integer(inx), fileData); + } + batchDoc.getBatchMsg().getBody().setSeqNum(seqNo); + + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + logger.error( e.getMessage(), e); + } + */ + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() ); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream(new FileInputStream(file)); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0300.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0300.java new file mode 100644 index 0000000..3de4fe8 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0300.java @@ -0,0 +1,477 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_KFTCB_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //결번갯수 + compileField(11, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + String jobCode = this.batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 12: + return MISSING_FIELD.length(); + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 12: + //mod by khs data = MISSING_FIELD.getBytes(); + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); +// int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + String writeNoLf = ""; + try { + writeNoLf = getJobInfo().getProperty(TelegramKeys.SKIP_LF); + } catch (Exception e) {} + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0310.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0310.java new file mode 100644 index 0000000..cf8f6ca --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0310.java @@ -0,0 +1,393 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KFTCB_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0320.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0320.java new file mode 100644 index 0000000..5dae28c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0320.java @@ -0,0 +1,520 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0320 extends DefaultTelegram implements TelegramService +{ + + private BufferedInputStream bis; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KFTCB_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + int appendLen = 0; + try { + appendLen = Integer.parseInt(getJobInfo().getProperty(TelegramKeys.APPEND_LL_LEN)); + } catch (Exception e) {} + + boolean isBinary = false; + try { + if ( "Y".equals(getJobInfo().getProperty(TelegramKeys.SKIP_LF)) ) + isBinary = true; + } catch (Exception e) {} + + fileData = new byte[REAL_BYTE]; + if ( isBinary ){ + bis.read(fileData, 0, REAL_BYTE ); + }else{ + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(bis); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), + Math.min(batchDoc.getBatchMsg().getHeader().getRecLen(), fileLine.length)); + if ( appendLen > 0 ){ + fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-1] = '\n'; + } + if ( appendLen > 1 ){ + fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-2] = '\r'; + } + } + } + + if ( isLastSeq ){ + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0600.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0600.java new file mode 100644 index 0000000..a8d92c0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0600.java @@ -0,0 +1,355 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_KFTCB_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + if ( this.al_Field.size() == 11){ + return true; + } + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + String orgCd = telegramInfo.getProperty(TelegramKeys.BANK_CODE); + String orgCd2 = orgCd.substring(1); + if ( orgCd.length() == 8 ) + orgCd2 = orgCd.substring(0,1)+orgCd.substring(7,8); + String passwd = EncryptManager.getInstance().getEncrypt(batchDoc.getBatchMsg().getHeader().getUserID(), + (batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6), + //telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1), + orgCd2, + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(12, passwd, this.al_FieldProps[12]); + }else{ + compileField(12, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[12]); + } + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0610.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0610.java new file mode 100644 index 0000000..be969f6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0610.java @@ -0,0 +1,395 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFTCB_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + logger.info("{} Process Type : ["+this.batchDoc.getBatchMsg().getHeader().getProcessType()+"]", logHeader); + logger.info("{} FldOpCode : ["+this.getFldOpCode()+"]", logHeader); + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + if ( this.al_Field.size() == 11){ + return true; + } + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(12, "", this.al_FieldProps[12]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (this.getFldOpCode().equals("001")) return true; + + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0620.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0620.java new file mode 100644 index 0000000..04d6a37 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0620.java @@ -0,0 +1,317 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFTCB_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0630.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0630.java new file mode 100644 index 0000000..88313e8 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0630.java @@ -0,0 +1,327 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0630 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KFTCB_0630() { + //화일정보수신요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + int seqSize = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ) * batchDoc.getBatchMsg().getHeader().getRecLen(); + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(fileName, 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12)); + // 0630 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + fileInfo.append(makeZero(""+(SEND_LENGTH + seqSize - 13), 4)); + + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0640.java b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0640.java new file mode 100644 index 0000000..66c1201 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kftc/SEND_KFTCB_0640.java @@ -0,0 +1,381 @@ +package com.eactive.eai.batch.job.jobItem.kftc; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KFTCB_0640 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_KFTCB_0640() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(batchDoc.getBatchMsg().getHeader().getFileName(), 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getBody().getCurFileSize(),12)); + fileInfo.append(makeZero(""+calculateTelegramSize(), 4)); + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + //해당 거래구분에 대한 Job_Code 값 설정 + //거래구분코드 조회 BizCode 조회 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + if (info != null) { + batchDoc.getBatchMsg().getHeader().setJobCode(info.getMsgDstCode());; + } else { + logger.debug("{} " + batchDoc.getBatchMsg().getHeader().getUUID()+ "'s Job Code is null", logHeader); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + batchDoc.getBatchMsg().getHeader().setJobCode((processCode+"00000")); //dummy code + // TEST 용 return false; + } + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private int calculateTelegramSize(){ + int recSize = 200; + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo != null && bJobInfo.getFileRecSize() > 0 ){ + //recSize = (int)Math.min(bJobInfo.getFileRecSize(), 4000); 20140317 + recSize = (int)Math.min(bJobInfo.getFileRecSize(), batchDoc.getBatchMsg().getHeader().getSequenceSize()); + } + + int diff = 0; + try { + diff = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.LENGTH_OFFSET)); + } catch (Exception e) { + // 아무것도 안함 + } + + // 0630/0640 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630/0640 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + return (batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize) * recSize + SEND_LENGTH - 13 + diff; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB.java new file mode 100644 index 0000000..214e53d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB.java @@ -0,0 +1,144 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_KOFCB extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 : CMS쪽 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_KOFCB() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + return Integer.parseInt( getTelegramInfo().getProperty(propKey) ); + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + idx = vo.getLengthField(); + if (idx == 0) return -1; + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=2; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(1)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=2; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + return; + } + LogUtil.setLogFileEnd(batchDoc); + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){} + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0310.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0310.java new file mode 100644 index 0000000..6f55c63 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0310.java @@ -0,0 +1,243 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KOFCB_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_KOFCB_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0320.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0320.java new file mode 100644 index 0000000..25db61b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0320.java @@ -0,0 +1,230 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KOFCB_0320 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_KOFCB_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0600.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0600.java new file mode 100644 index 0000000..6dac2e3 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0600.java @@ -0,0 +1,118 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KOFCB_0600 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_KOFCB_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0610.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0610.java new file mode 100644 index 0000000..a30bfa1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0610.java @@ -0,0 +1,143 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KOFCB_0610 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_KOFCB_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + // File Open LOG + File ff = new File(fileName); + + //응답송신이 아니고 0610/0004를 수신하면 (응답송신의 경우 recv0300일경우에 파일을 이동시키므로 이단계에서는 파일이 존재하지 않음 + if (!CommonKeys.PROCESS_RESPONSE_SEND.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + if (ff.exists() && OpCode_noexsist.equals(this.getOpCode())) { + logger.info("{} FILE SIZE ("+ ff.length() + "]", logHeader); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(ff); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + if (OpCode_noexsist.equals(this.getOpCode()) && fileNm != null && !fileNm.trim().equals("")) { + //응답수신 파일 Start DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0620.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0620.java new file mode 100644 index 0000000..14cb4be --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0620.java @@ -0,0 +1,130 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KOFCB_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KOFCB_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_no == 0 ){ + block_no = 1; + } + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + //여기까지 넘어오면 620 전문에서 받은 LAST SEQUENCE를 최종으로 SET + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0630.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0630.java new file mode 100644 index 0000000..5cf3e7d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0630.java @@ -0,0 +1,175 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KOFCB_0630 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_KOFCB_0630() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + + String fileInfo = new String ((byte[]) al_Field.get(9)); + String fName = fileInfo.trim(); + String strFsize = new String ((byte[]) al_Field.get(10)); + long fSize = Long.parseLong(strFsize); //화일 size + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + String pattern = null; + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_KOFCB_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); +// this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + } + + long recLen = 0; + if ( bJobInfo == null ){ + batchDoc.getBatchMsg().getHeader().setRecLen(-1); + }else{ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bJobInfo.getFileRecSize()); + batchDoc.getBatchMsg().getHeader().setJobCode(bJobInfo.getMsgDstCode()); + } + + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getHeader().setFileSize(fSize); + long recCnt = 0; + if ( recLen > 0 ){ + recCnt = fSize / recLen; + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0640.java b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0640.java new file mode 100644 index 0000000..1c017b1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/RECV_KOFCB_0640.java @@ -0,0 +1,166 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KOFCB_0640 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_KOFCB_0640() { + //화일정보수신통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + //파일Size는 정책금융공사에서 받은 싸이즈만큼 리턴됨 + long fSize = Long.parseLong(new String( (byte[]) al_Field.get(10))); + if (getResCode().equalsIgnoreCase(TelegramKeys.BOKJJ_RET_CODE_ALREADY_RECEIVED) ) { //기송신 파일이면 + checkMoreFileinDB(); + } else { + if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면 + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID(); + String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath()); + batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName()); + batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getEAIBatchMessage().getHeader().setFileSize(0); + batchDoc.getEAIBatchMessage().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + + } + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0300.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0300.java new file mode 100644 index 0000000..7b2cf90 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0300.java @@ -0,0 +1,447 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_KOFCB_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //결번갯수 + compileField(11, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 12: + return MISSING_FIELD.length(); + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 12: + //mod by khs data = MISSING_FIELD.getBytes(); + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0310.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0310.java new file mode 100644 index 0000000..99849b0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0310.java @@ -0,0 +1,380 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KOFCB_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0320.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0320.java new file mode 100644 index 0000000..bec4c9e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0320.java @@ -0,0 +1,465 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0320 extends DefaultTelegram implements TelegramService +{ + + private BufferedInputStream bis; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_KOFCB_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(bis); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + if ( isLastSeq ){ + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0600.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0600.java new file mode 100644 index 0000000..2602e0b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0600.java @@ -0,0 +1,341 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_KOFCB_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + String orgCd = telegramInfo.getProperty(TelegramKeys.BANK_CODE); + String orgCd2 = orgCd.substring(1); + if ( orgCd.length() == 8 ) + orgCd2 = orgCd.substring(0,1)+orgCd.substring(7,8); + String passwd = EncryptManager.getInstance().getEncrypt(batchDoc.getBatchMsg().getHeader().getUserID(), + (batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6), + //telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1), + orgCd2, + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(12, passwd, this.al_FieldProps[12]); + }else{ + compileField(12, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[12]); + } + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + if ( this.getFldOpCode().equals("001")){ + batchDoc.getBatchMsg().getBody().setErrorMsg(""); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0610.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0610.java new file mode 100644 index 0000000..70316b6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0610.java @@ -0,0 +1,378 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KOFCB_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + logger.info("{} Process Type : ["+this.batchDoc.getBatchMsg().getHeader().getProcessType()+"]", logHeader); + logger.info("{} FldOpCode : ["+this.getFldOpCode()+"]", logHeader); + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(12, "", this.al_FieldProps[12]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (this.getFldOpCode().equals("001")) return true; + + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0620.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0620.java new file mode 100644 index 0000000..bd906ae --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0620.java @@ -0,0 +1,310 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KOFCB_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0630.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0630.java new file mode 100644 index 0000000..bb71db2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0630.java @@ -0,0 +1,306 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0630 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_KOFCB_0630() { + //화일정보수신요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + compileField(9, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[9]); + compileField(10, makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12), this.al_FieldProps[10]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0640.java b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0640.java new file mode 100644 index 0000000..13d72dd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/kofc/SEND_KOFCB_0640.java @@ -0,0 +1,319 @@ +package com.eactive.eai.batch.job.jobItem.kofc; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KOFCB_0640 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_KOFCB_0640() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(1, "" + SEND_LENGTH, this.al_FieldProps[1]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //파일 정보 내역을 보내기 위해서 XXX_bizcode형식으로 파일명을 맞춰주어야하며, TelegramKey안에 있는 은행코드를 참고하도록 함. + //Edited by ChaeSH + compileField(9, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[9]); + + //정책금융공사의 경우 받은 파일 싸이즈를 요청함. + //따라서 현재 받은 싸이즈 "0"를 리턴하도록 설정 + //Edited by ChaeSH + String fSize = "0"; + compileField(10, fSize, this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + getCalculatedLength(0) + ((byte[]) this.al_Field.get(1)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 0: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT.java b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT.java new file mode 100644 index 0000000..cd52b52 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT.java @@ -0,0 +1,82 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_KSDBT extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : KSD전문 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_KSDBT() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=0; i organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + String pattern = ""; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bJobInfo.getFileRecSize()); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(bout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int preLen = 0; + for (int inx = 0; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch (Exception ex) { + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0210.java b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0210.java new file mode 100644 index 0000000..20659c2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0210.java @@ -0,0 +1,270 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import java.lang.String; +import java.util.ArrayList; +import java.util.Arrays; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.io.File; + +public class RECV_KSDBT_0210 extends DefaultTelegram implements TelegramService +{ + + final String errCode01 = "수신일련번호 에러 발생"; + final String errCode02 = "수신데이터 건수 에러 발생"; + final String errCode09 = "배치전문 기 수신완료"; + final String errCode90 = "헤더부분 중 항목 에러 발생"; + /** + * 생성자 + */ + public RECV_KSDBT_0210() { + //DATA응답 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String str_seq = new String ((byte[]) al_Field.get(8)); + int recv_seq = Integer.parseInt(str_seq); + this.batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq); + + if ( this.getOpCode().equals("999")){ + this.setConditionTxt(TelegramKeys.NOFILE); + } + //에러처리 로직 + if ( this.getResCode().charAt(0) == '9' ) { + throw new Exception(errCode90); + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String byte_size = new String ((byte[]) al_Field.get(0)); + int preLen = 0; + for (int inx = 0; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + if ( getOpCode().equals("999")){ //개별업무 종료 응답이면 + //요구송신 파일 END DB로그 + try { + LogUtil.setLogFileEnd(batchDoc); + if ( checkMoreFileInDir()){ + this.setConditionTxt(""); + } else { + this.setConditionTxt(TelegramKeys.NOFILE); + } + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI021"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + +// //DB로그에 남길 전문 바디 설정 +// baout = new ByteArrayOutputStream(); +// for (int i=10; i< al_Field.size(); i++) { +// baout.write((byte[])this.al_Field.get(i)); +// } + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkMoreFileInDir(){ + + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + try{ + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i 0) { + for (int inx=0; inx= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bjvo != null ) { + if (bjvo.getPriority() < msgPriority ){ + msgPriority = bjvo.getPriority(); + sndRealFile = fileList[inx]; + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + } + } + } + if ( sndRealFile == null ) { + return false; + } + String strFileName = sndRealFile.getName(); + String renamedFileName = strFileName + "_" + CalendarUtil.getCurrentTimeNoDash(); + File sndArchFile = new File( batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + renamedFileName ); + logger.info("{} >>>>> 송신 대기 파일을 송신 Real 디렉토리 -> 송신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = sndRealFile.renameTo(sndArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI044", new String[] {sndRealFile.getAbsolutePath(), sndArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //송신 대기중인 파일을 송신 Real 디렉토리 -> 송신 Arch 디렉토리로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + batchDoc.getBatchMsg().getHeader().setFileName(strFileName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(renamedFileName); + + } else { + return false; + } + + } catch ( Exception e){ + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0800.java b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0800.java new file mode 100644 index 0000000..5bf3610 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0800.java @@ -0,0 +1,130 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KSDBT_0800 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_restart = "002"; //업무재개시 + private final String OpCode_end = "040"; //업무종료 + private final String OpCode_teset = "301"; //회선시험 + + + /** + * 생성자 + */ + public RECV_KSDBT_0800() { + //증권 예탁원 개시/종료/통신망 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + batchDoc.getBatchMsg().getHeader().setBizCode(""); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_restart)) { + String bizCode = super.getFieldValueString(5); + String seqNum = super.getFieldValueString(8); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( jvo != null ){ + batchDoc.getBatchMsg().getBody().setSeqNum(Integer.parseInt(seqNum)); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + batchDoc.getBatchMsg().getHeader().setJobCode(jvo.getMsgDstCode()); + } + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_teset)) { + } + else { + logger.info("{} 0800 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode("95"); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + +// //DB로그에 남길 전문 바디 설정 +// baout = new ByteArrayOutputStream(); +// for (int i=9; i< al_Field.size(); i++) { +// baout.write((byte[])this.al_Field.get(i)); +// } + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0810.java b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0810.java new file mode 100644 index 0000000..d5e13bd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/RECV_KSDBT_0810.java @@ -0,0 +1,113 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KSDBT_0810 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_restart = "002"; //업무재개시 + private final String OpCode_end = "040"; //업무종료 + private final String OpCode_teset = "301"; //회선시험 + + + /** + * 생성자 + */ + public RECV_KSDBT_0810() { + //증권 예탁원 개시/종료/통신망 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_restart)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_teset)) { + } + else { + logger.info("{} 0800 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode("95"); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + +// //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0200.java b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0200.java new file mode 100644 index 0000000..ae471b3 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0200.java @@ -0,0 +1,428 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KSDBT_0200 extends DefaultTelegram implements TelegramService +{ + + private BufferedInputStream bis; + private File file; + private int SEQUENCE_NO; + private int LAST_SEQ; //일련번호 + private int REC_CNT; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //실제 송신할 전문의 총길이 + private boolean isReSend = false; + + private Properties telegramInfo; + private byte[] fileData; + private int retryCnt; + + /** + * 생성자 + */ + public SEND_KSDBT_0200() { + //DATA전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = makeSendData(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //송신전문의 총 Byte 수 + compileField(0, String.valueOf(SEND_LENGTH), this.al_FieldProps[0]); + //TR CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + //기관 ID + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + //전문종별코드 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //통신망관리정보 + //001-업무개시, 002-재개시, 040-종료, 301-회선시험 + compileField(4, this.getFldOpCode(), this.al_FieldProps[4]); + //데이터전문코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + //전문전송일시 + compileField(7, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[7]); + //전문일련번호 + compileField(8, "" + SEQUENCE_NO, this.al_FieldProps[8]); + compileField(9, "" + REC_CNT, this.al_FieldProps[9]); + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if ( file != null ){ // 처음 전송이면 + LogUtil.setLogFileStart(batchDoc); + } +// if ( this.getOpCode().equals("000") ){ // DATA전송인 경우 +//// this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO + REC_CNT - 1); +// } +// if ( this.getFldOpCode().equals("999") ) { //DATA를 보낸 후 보낸 SEQ RESET +//// batchDoc.getBatchMsg().getHeader().setSequenceSize(0); +//// batchDoc.getBatchMsg().getHeader().setBlockSize(0); +// } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + isReSend = false; + String prevTelegramHeader = batchDoc.getBatchMsg().getTelegramHeader(); + String prevTelegramType = ""; + String prevTelegramRescd = ""; + String prevTelegramSeqNo = ""; + + if ( prevTelegramHeader.length() >= 49 ){ + prevTelegramType = prevTelegramHeader.substring(18, 22); + prevTelegramRescd = prevTelegramHeader.substring(35, 37); + prevTelegramSeqNo = prevTelegramHeader.substring(51, 59); + } + + if ( prevTelegramType.equals("0200")){ /// TIMEOUT이후 재전송이면 + retryCnt = 1; + batchDoc.getBatchMsg().getBody().setErrorMsg(""); + }else{ + //1. 데이터 수신 일련번호 에러인 경우 + if ( prevTelegramRescd.equals("01") || prevTelegramRescd.equals("02") ) { + isReSend = true; + LAST_SEQ = Integer.parseInt(prevTelegramSeqNo); + + retryCnt = 0; + } + } + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + + } + + private boolean createFile () + { + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( bis == null ){ + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + } + return !( bis == null); + } + + private boolean makeSendData() + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + if ( retryCnt > 0 ){ // 타임오버 이후의 재 전송인 경우, 이전에 DATA가 있었던 경우에만 + if ( batchDoc.getBatchMsg().getTelegramBody() != null && !batchDoc.getBatchMsg().getTelegramBody().equals("") ){ + fileData = batchDoc.getBatchMsg().getTelegramBody().getBytes(); + } + }else{ + if ( isReSend ){ // 중단된 이후 재 송신인 경우 + skipLine(); + } + + // 레코드 크기 + int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / recSize; + logger.debug("[SEND_KSDBT_0200]seqCnt -->" + seqCnt); + logger.debug("[SEND_KSDBT_0200]remainCnt-->" + remainCnt); + if ( seqCnt < remainCnt ){ + REC_CNT = seqCnt; + }else{ + REC_CNT = (int)remainCnt; + } + REAL_BYTE = REC_CNT * recSize; + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < REC_CNT ; inx++){ + byte[] fileLine = FileUtil.readLine(bis); + if ( file != null && inx == 0 ){ + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + if ( inx == REC_CNT -1 ){ + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + } + System.arraycopy( fileLine, 0, fileData, inx * recSize, recSize); + byte[] seqArea = new byte[8]; + System.arraycopy( fileLine, 0, seqArea, 0, 8 ); + try { + SEQUENCE_NO = Integer.parseInt( new String(seqArea)); + } catch (Exception e) { + SEQUENCE_NO = 0; + } + } + } + + if ( REAL_BYTE == 0 ){ + this.setFldOpCode("999"); + bis.close(); + SEQUENCE_NO = batchDoc.getBatchMsg().getBody().getSeqNum(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private void skipLine() throws Exception{ + byte[] fileLine = null; + byte[] byte_sequence = new byte[8]; + int iSequence = 0; + while ( ( fileLine = FileUtil.readLine(bis) ) != null ){ + System.arraycopy( fileLine, 0, byte_sequence, 0, 8); + iSequence = Integer.parseInt( new String(byte_sequence)); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + batchDoc.getBatchMsg().getHeader().getRecLen(); + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + if ( LAST_SEQ == iSequence ) + return; + } + throw new Exception("재전송 시작할 위치를 찾지 못하였습니다."); + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0210.java b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0210.java new file mode 100644 index 0000000..e41851f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0210.java @@ -0,0 +1,507 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; + +public class SEND_KSDBT_0210 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private File file; + private BufferedOutputStream bos; + private String strFullPath; + + /** + * 생성자 + */ + public SEND_KSDBT_0210() { + //DATA응답 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //SEQUENCE_NO = this.batchDoc.getEAIBatchMessage().getBody().getSeqNum(); + + //송신전문의 총 Byte 수 + compileField(0, String.valueOf(SEND_LENGTH), this.al_FieldProps[0]); + //TR CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + //기관 ID + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + //전문종별코드 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //통신망관리정보 + //001-업무개시, 002-재개시, 040-종료, 301-회선시험 + compileField(4, this.getFldOpCode(), this.al_FieldProps[4]); + //데이터전문코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + //전문전송일시 + compileField(7, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[7]); + //전문일련번호 + compileField(8, ""+ batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[8]); + //데이터 건수 + compileField(9, "00", this.al_FieldProps[9]); + //<<전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + +// //DB로그에 남길 전문 바디 설정 +// baout = new ByteArrayOutputStream(); +// for (int i=10; i< al_Field.size(); i++) { +// baout.write((byte[])this.al_Field.get(i)); +// } + batchDoc.getBatchMsg().setTelegramBody(""); + + if ( this.getFldOpCode().equals("999") ){ + batchDoc.getBatchMsg().getBody().setSeqNum(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(-1); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + String jobCode = this.batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + if ( bjvo != null ){ + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + } + checkPrevRecvFile(); + processPrevData(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private void checkPrevRecvFile(){ + if ( !createFile() ){ + // 이전 수신 파일 없음!! SKIP!!! + SEQUENCE_NO = 0; + return; + } + BufferedInputStream bis = null; + try { + bis = new BufferedInputStream( new FileInputStream(file)); + byte[] fileLine = null; + byte[] lastLine = null; + while (( fileLine = FileUtil.readLine(bis)) != null ){ + lastLine = fileLine; + } + //logger.debug("lastLine-->" + new String(lastLine)); + byte[] byte_seq = new byte[8]; + System.arraycopy(lastLine, 0, byte_seq, 0, 8); + SEQUENCE_NO = Integer.parseInt( new String(byte_seq)); + + //일련번호 에러와 함께 최종 받은 SEQNUM 재전송 + batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + } catch (FileNotFoundException fne) { + return; + } catch (Exception e) { + logger.error( e.getMessage(), e); + return; + }finally{ + try { + if ( bis != null ) { + bis.close(); + } + } catch (Exception e) {} + } + + } + + private void processPrevData(){ + String prevTelegramHeader = batchDoc.getBatchMsg().getTelegramHeader(); + String recvOpCode = prevTelegramHeader.substring(22,25); + + + // 1. 받은 시퀀스 체크 + int recvSeq = 0; + try { + recvSeq = Integer.parseInt(prevTelegramHeader.substring(51,59)); + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = "" + batchDoc.getBatchMsg().getBody().getSeqNum(); + msgArgs[1] = prevTelegramHeader.substring(51,59); + String errCode = "BECEAIFJI045"; + String errMsg = ExceptionUtil.getErrorCode ( errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + this.setResolveResponseCode("99"); + return; + } + + if ( recvOpCode.equals("000")){ +// if ( SEQUENCE_NO + 1 != recvSeq ){ +// String[] msgArgs = new String[2]; +// msgArgs[0] = "" + SEQUENCE_NO; +// msgArgs[1] = "" + recvSeq; +// String errCode = "BECEAIFJI045"; +// String errMsg = ExceptionUtil.getErrorCode ( errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// this.setResolveResponseCode("99"); +// return; +// } + }else if ( recvOpCode.equals("999")){ + if ( batchDoc.getBatchMsg().getBody().getSeqNum() != recvSeq ){ + String[] msgArgs = new String[2]; + msgArgs[0] = "" + batchDoc.getBatchMsg().getBody().getSeqNum(); + msgArgs[1] = "" + recvSeq; + String errCode = "BECEAIFJI045"; + String errMsg = ExceptionUtil.getErrorCode ( errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + this.setResolveResponseCode("99"); + return; + } + } + + // 2. 건수 체크 + @SuppressWarnings("unused") + int recCount = 0; + try { + recCount = Integer.parseInt(prevTelegramHeader.substring(59,61)); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = prevTelegramHeader.substring(59,61); + String errCode = "BECEAIFJI046"; + String errMsg = ExceptionUtil.getErrorCode ( errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + this.setResolveResponseCode("9A"); + return; + } + + try { + if ( !createFile() ){ + logger.error( "수신 파일 생성 오류" ); + this.setResolveResponseCode("09"); + return ; + } + if ( recvOpCode.equals("000")){ + bos = new BufferedOutputStream (new FileOutputStream(file, true)); //bytes will be written to the end of the file rather than the beginning + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + if ( lnCurSize < 1 ) { + LogUtil.setLogFileStart(batchDoc); + } + + // 레코드 크기 + int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); + String prevTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + byte [] fileData = new byte[recSize]; + byte [] byteCnt = new byte[2]; + System.arraycopy(prevTelegramHeader.getBytes(), 59, byteCnt, 0, 2); + int recCnt = 0; + try { + recCnt = Integer.parseInt(new String(byteCnt)); + } catch (Exception e) {} + + for (int inx = 0; inx < recCnt; inx++) { + System.arraycopy(prevTelegramBody.getBytes(), ( inx * (recSize + 8)) + 8, fileData, 0, recSize); + bos.write(fileData); + bos.write('\n'); + if ( lnCurSize < 1 ) { + batchDoc.getBatchMsg().setFileHeader(new String(fileData)); + } + if ( inx == recCnt -1 ){ + batchDoc.getBatchMsg().setFileTrailer(new String(fileData)); + } + lnCurSize += recSize; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + try { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(lnCurSize/recSize); + } catch (Exception e) { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + } + } + bos.close(); + SEQUENCE_NO = recvSeq + recCnt -1; + batchDoc.getBatchMsg().getBody().setSeqNum( SEQUENCE_NO ); + + + }else if (recvOpCode.equals("999")){ + + String strArchFileName = StringUtil.realToArchDir(this.strFullPath); + File rcvArchFile = new File( strArchFileName ); +// if ( rcvArchFile.exists() ) { +// String strHHMMSS = CalendarUtil.getCurrentTimeNoDash(); +// strArchFileName = strArchFileName + "_" + strHHMMSS; +// rcvArchFile = new File( strArchFileName ); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName() + "_" + CalendarUtil.getCurrentTimeNoDash()); +// }else{ +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); +// } + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + if ( !file.exists() ){ + file.createNewFile(); + } + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis()); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getBody().getCurFileSize()); + // 레코드 크기 + int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recSize <= 0 ){ + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + }else{ + int recCnt = (int)batchDoc.getBatchMsg().getBody().getCurFileSize() / recSize; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + } + + + if ( file.length()==0 ){ + LogUtil.setLogFileStart(batchDoc); + } + + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + this.setResolveResponseCode("09"); + return ; + } + //수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(업무 서버에 자동 송신하도록 수신 File Event 발생)", logHeader); + File rcvRootFile = new File( StringUtil.realToRootDir(strFullPath) ); + + if (!rcvRootFile.createNewFile()) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + this.setResolveResponseCode("09"); + return ; + } + + LogUtil.setLogFileEnd(batchDoc); + + }else{ // 발생가능성은 없으나 혹시나 하여.. + bos.close(); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + this.setResolveResponseCode("09"); + return ; + } + //에러 상황이 해제되면 에러가 아닌 정상 거래로 처리 + this.batchDoc.getBatchMsg().getBody().setErrorMsg(""); + this.setResolveResponseCode("00"); + + } + + private boolean createFile () { + try { + + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + fileName; + file = new File(strFullPath); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0800.java b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0800.java new file mode 100644 index 0000000..afd6c85 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0800.java @@ -0,0 +1,243 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KSDBT_0800 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private final String OpCode_restart = "002"; //업무재개시 + + + /** + * 생성자 + */ + public SEND_KSDBT_0800() { + //증권 예탁원 개시/종료/통신망 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //송신전문의 총 Byte 수 + compileField(0, String.valueOf(SEND_LENGTH), this.al_FieldProps[0]); + //TR CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + //기관 ID + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + //전문종별코드 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //통신망관리정보 + //001-업무개시, 002-재개시, 040-종료, 301-회선시험 + compileField(4, this.getFldOpCode(), this.al_FieldProps[4]); + //데이터전문코드 + if ( this.getFldOpCode().equals(OpCode_restart) ) { + //재개시인 경우 재개시 이전 배치 전문 데이터전문코드와 최종 수신된 일련번호 SET + compileField(5, "", this.al_FieldProps[5]); + //전문일련번호 + compileField(8, "", this.al_FieldProps[8]); + } + else { + compileField(5, "", this.al_FieldProps[5]); + //전문일련번호 + compileField(8, "", this.al_FieldProps[8]); + } + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + //전문전송일시 + compileField(7, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[7]); + //데이터 건수 + compileField(9, "", this.al_FieldProps[9]); + //<<전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + SEND_LENGTH = 0; + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0810.java b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0810.java new file mode 100644 index 0000000..81b119f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksd/SEND_KSDBT_0810.java @@ -0,0 +1,266 @@ +package com.eactive.eai.batch.job.jobItem.ksd; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KSDBT_0810 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private final String OpCode_restart = "002"; //업무재개시 + + + /** + * 생성자 + */ + public SEND_KSDBT_0810() { + //증권 예탁원 개시/종료/통신망 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + +// 송신전문의 총 Byte 수 + compileField(0, String.valueOf(SEND_LENGTH), this.al_FieldProps[0]); + //TR CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + //기관 ID + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + //전문종별코드 + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + //통신망관리정보 + //001-업무개시, 002-재개시, 040-종료, 301-회선시험 + compileField(4, this.getFldOpCode(), this.al_FieldProps[4]); + //데이터전문코드 + if ( this.getFldOpCode().equals(OpCode_restart) ) { + //재개시인 경우 재개시 이전 배치 전문 데이터전문코드와 최종 수신된 일련번호 SET + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode() , this.al_FieldProps[5]); + //전문일련번호 + //compileField(8, ""+batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[8]); + } + else { + compileField(5, "", this.al_FieldProps[5]); + //전문일련번호 + } + //응답코드 + compileField(6, this.getResolveResponseCode(), this.al_FieldProps[6]); + //전문전송일시 + compileField(7, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[7]); + + // 개시/재개시/종료이던 수신 파일이 존재하면 삭제 하고 다시 받는다. + // 따라서 기존에 받은 건수는 0이다. + compileField(8, "", this.al_FieldProps[8]); + + //데이터 건수 + compileField(9, "", this.al_FieldProps[9]); + //<<전문 완성 + + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + + // 개시/재개시/종료이던 수신 파일이 존재하면 삭제 하고 다시 받는다. + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + fileName; + File file = new File(strFullPath); + if ( file.isFile() && file.exists() ){ + file.delete(); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //KSD전문의 헤더는 DATA건수까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + +// //DB로그에 남길 전문 바디 설정 +// baout = new ByteArrayOutputStream(); +// for (int i=9; i< al_Field.size(); i++) { +// baout.write((byte[])this.al_Field.get(i)); +// } + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + SEND_LENGTH = 0; + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return 0; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4).substring(3); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(6); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDAT.java b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDAT.java new file mode 100644 index 0000000..a1a87a0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDAT.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.ksdps; + +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KSDAT extends DefaultTelegram implements TelegramService +{ + + public RECV_KSDAT() { + } + + public boolean doExecute() { + + return true; + } + /** + * RULE의 TelegramType만 가지고, 다음 텔레그램의 ID를 결정한다. + */ + public String getRealRecvTelegram() { + + PhaseInfoVO info = (PhaseInfoVO) this.al_NextStage.get(0); + if ( info == null ) return ""; + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (info.getPhaseSeq() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(info.getTelegramID()); //Stage Logging 용 + return info.getTelegramID(); + } + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS.java b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS.java new file mode 100644 index 0000000..fab8fff --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS.java @@ -0,0 +1,79 @@ +package com.eactive.eai.batch.job.jobItem.ksdps; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_KSDPS extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : KSD전문 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_KSDPS() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(0); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(4).substring(3); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(1); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(4); +// } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ +// public int getRemainDataLength() +// { +// try { +// int idx; +// String strLength; +// +// String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); +// String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); +// NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); +// +// idx = vo.getLengthField(); +// if (idx == 0) return -1; +// +// strLength = new String((byte[])this.al_Field.get(idx-1)); +// int nDocLen = Integer.parseInt(strLength); +// int nReceivedLen = 0; +// for (int i=0; i getCalculatedLength() -> doInformalField() -> doExecute() -> doValidation() -> doPostExecute() + //============================================================================================================================ + + public boolean doPreExecute() + { + if (!super.doPreExecute()) return false; + return true; + } + + public boolean doPreExecuteAfterCopy() + { + if (!super.doPreExecuteAfterCopy()) return false; + + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + + + //1. 수신파일 저장 경로 설정 + //저장 디렉토리는 Inbound Server 에서 설정됨 (응답수신 Real 또는 응답송신 Real) + strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separatorChar; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + logger.info("{} 응답수신 파일 저장 경로 : [" + this.strFullPathName + "]", logHeader); + rcvRealFile = new File( this.strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPathName) ); + + + //2. 응답수신 파일 생성 + logger.info("{} >>>>> 응답수신 파일 생성...... ("+ this.strFullPathName +")", logHeader); + try { + fout = new FileOutputStream(rcvRealFile); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI041", new String[] {rcvRealFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 해당 경로에 생성시 오류가 발생하였습니다. [Path : {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + + + //3. 응답수신 파일 Start DB로그 + logger.info("{} >>>>> 응답수신 파일 Start DB로그......", logHeader); + try { + LogUtil.setLogFileStart(batchDoc); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 Start DB로그 수행시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI021", new String[] {processCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + return (int)batchDoc.getBatchMsg().getHeader().getFileSize(); + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + //파일 끝에 append + fout.write(data, 0, length); + + //읽어 들인 파일 사이즈 저장 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch (Exception ex) { + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.error("{} ★★★★★ 수신 파일 데이터 WRITE 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * 이전문처리에서는 doPostExecute에서 열어놓았던 파일을 닫아준다. + */ + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //1. 수신 파일 Close =========================================================== + if (fout != null) fout.close(); + + //2. 수신 파일 End DB로그 ====================================================== + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //사이즈 비교 + long recvSize = rcvRealFile.length(); + if ( recvSize != batchDoc.getBatchMsg().getHeader().getFileSize() ){ + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SEND_BYTE_ERROR); + return false; + } + super.setFileHeaderAndTrailer(rcvRealFile); + } + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + +// //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 +// if ( !super.getResolveResponseCode().equals("0000") ) { +// //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) +// Logging(INFO, ">>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동....."); +// boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); +// if (!isSuccessMoveFile) { +// String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); +// if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { +// errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); +// } +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] +// } +// return false; +// } + + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + + //4. 자료구분 필드 값 체크 (Real 일때만 퇴직연금 서버로 파일 전송) + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPathName) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + + return true; + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + ex.printStackTrace(); + return false; + } + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS_H000.java b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS_H000.java new file mode 100644 index 0000000..adf1014 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS_H000.java @@ -0,0 +1,121 @@ +package com.eactive.eai.batch.job.jobItem.ksdps; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KSDPS_H000 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public RECV_KSDPS_H000() { + //증권 예탁원 개시/종료/통신망 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + String fileName = new String ((byte[]) al_Field.get(2)); + String fileSize = new String ((byte[]) al_Field.get(3)); + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_RECEIVE)) { + batchDoc.getBatchMsg().getHeader().setFileName(fileName); + batchDoc.getBatchMsg().getHeader().setFileSize(Long.parseLong(fileSize)); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + long recSize = 100; + if ( bJobInfo != null ){ + batchDoc.getBatchMsg().getHeader().setJobCode(bJobInfo.getBatchCode());// 20250910 npe + recSize = bJobInfo.getFileRecSize(); + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(Long.parseLong(fileSize)/recSize); + + + }else{ + batchDoc.getBatchMsg().getBody().setSendSummary(fileSize); + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<4; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(0); + } + //응답코드 필드값 리턴 + public String getResCode() + { + if (super.getFieldValueString(1).equals("0000")) + return "000"; + return super.getFieldValueString(1).substring(1); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS_T000.java b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS_T000.java new file mode 100644 index 0000000..f27d9b2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksdps/RECV_KSDPS_T000.java @@ -0,0 +1,107 @@ +package com.eactive.eai.batch.job.jobItem.ksdps; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KSDPS_T000 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public RECV_KSDPS_T000() { + //증권 예탁원 개시/종료/통신망 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; +// String fileName = new String ((byte[]) al_Field.get(2)); +// String fileSize = new String ((byte[]) al_Field.get(3)); +// String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); +// if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE) || +// procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_RECEIVE)) { +// batchDoc.getBatchMsg().getHeader().setFileName(fileName); +// batchDoc.getBatchMsg().getHeader().setFileSize(Long.parseLong(fileSize)); +// //파일명으로 부터 거래 구분 코드 추출 +// int bizCodeStartIndex = 0; +// int bizCodeEndIndex = 0; +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); +// for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; +// if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); +// String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); +// batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); +// +// BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); +// batchDoc.getBatchMsg().getHeader().setJobCode(bJobInfo.getBatchCode()); +// +// } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<4; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(0); + } + //응답코드 필드값 리턴 + public String getResCode() + { + if (super.getFieldValueString(1).equals("0000")) + return "000"; + return super.getFieldValueString(1).substring(1); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_ACKR.java b/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_ACKR.java new file mode 100644 index 0000000..5a66489 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_ACKR.java @@ -0,0 +1,140 @@ +package com.eactive.eai.batch.job.jobItem.ksdps; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KSDPS_ACKR extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //실제 송신할 전문의 총길이 + + /** + * 생성자 + */ + public SEND_KSDPS_ACKR() { + //DATA전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if (!calculateSendLength()) return false; + + //TR Code H or T + compileField(0, this.getFldTelegramType(), this.al_FieldProps[0]); + + //응답코드 + compileField(1, "0000", this.al_FieldProps[1]); + + //File Name + compileField(2, "00000000000000000000000000000000000", this.al_FieldProps[2]); + + compileField(3, "", this.al_FieldProps[3]); + + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<4; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + this.setResolveResponseCode("0000"); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(0); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(1); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_DATA.java b/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_DATA.java new file mode 100644 index 0000000..e553cf6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_DATA.java @@ -0,0 +1,208 @@ +package com.eactive.eai.batch.job.jobItem.ksdps; + +import java.io.File; +import java.io.FileInputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_KSDPS_DATA extends DefaultTelegram implements TelegramService +{ + private String filename; + private File f; + private FileInputStream fin = null; + private long fileSize = 0; + + public SEND_KSDPS_DATA() { + } + + + /** + * 지정된 전문의 구성 필드 배열 선언, 요구송신 파일 Start DB로그 + */ + public boolean doPreExecute() { + if (!super.doPreExecute()) return false; + return true; + } + + public boolean doExecute() { + return true; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { +// int nSumFormalField = 0; +// for (int i=0; i 0){ + l_recvBytes = Math.min(l_recvBytes, this.fileSize); + fin.skip(l_recvBytes); + batchDoc.getBatchMsg().getBody().setCurFileSize(l_recvBytes); + } + + return nLength - (int)l_recvBytes; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송수신 길이를 계산해서 리턴해준다. + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) + { + if ( idx == 0 ) return 0; + + try { + // 여기서는 전송대상인 파일의 크기를 리턴해준다. + logger.info("{} batch transefet job : Target file size = ["+this.fileSize+"]", logHeader); + + batchDoc.getBatchMsg().getHeader().setFileSize(this.fileSize); + + String recvBytes = batchDoc.getBatchMsg().getBody().getSendSummary(); + long l_recvBytes = 0; + try { + l_recvBytes = Long.parseLong(recvBytes); + } catch (Exception e) { + return 0; + } + if ( l_recvBytes > 0){ + l_recvBytes = Math.min(l_recvBytes, this.fileSize); + } + + + return (int)this.fileSize - (int)l_recvBytes; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 여기서는 파일을 닫는다. + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(f); + +// //DB로그에 남길 전문 헤더 설정 +// ByteArrayOutputStream baout = new ByteArrayOutputStream(); +// for (int i=0; i= this.getFieldCount() ) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI011"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if (data.length < fldLen) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI014"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// +// ByteArrayInputStream bin = new ByteArrayInputStream(fileData); +// bin.read(data, 0, REAL_BYTE); +// // 20060419 add by khs for 전송상태 확인 +// long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; +// batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); +// +// // 로깅을 위해 +// byte[] fieldData = new byte[fldLen]; +// System.arraycopy(data, 0, fieldData, 0, fldLen); +// this.al_Field.set( idx, fieldData); +// return fldLen; +// } catch (Exception ex) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI006"; +// String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( ex.getMessage(), ex); +// return -1; +// } +// } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + LogUtil.setLogFileStart(batchDoc); + +// if ( file != null ){ // 처음 전송이면 +// } +// if ( this.getOpCode().equals("000") ){ // DATA전송인 경우 +//// this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO + REC_CNT - 1); +// } +// if ( this.getFldOpCode().equals("999") ) { //DATA를 보낸 후 보낸 SEQ RESET +//// batchDoc.getBatchMsg().getHeader().setSequenceSize(0); +//// batchDoc.getBatchMsg().getHeader().setBlockSize(0); +// } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<4; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 +// baout = new ByteArrayOutputStream(); +// for (int i=10; i< al_Field.size(); i++) { +// baout.write((byte[])this.al_Field.get(i)); +// } +// batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + this.setResolveResponseCode("0000"); + if ( batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) || + batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND ) ){ + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + String filename = fileDir+ File.separator + fileNm; + File f = new File(filename); + batchDoc.getBatchMsg().getHeader().setFileSize(f.length()); + } + +// isReSend = false; +// String prevTelegramHeader = batchDoc.getBatchMsg().getTelegramHeader(); +// String prevTelegramType = ""; +// String prevTelegramRescd = ""; +// String prevTelegramSeqNo = ""; +// +// if ( prevTelegramHeader.length() >= 49 ){ +// prevTelegramType = prevTelegramHeader.substring(18, 22); +// prevTelegramRescd = prevTelegramHeader.substring(35, 37); +// prevTelegramSeqNo = prevTelegramHeader.substring(51, 59); +// } +// +// if ( prevTelegramType.equals("0200")){ /// TIMEOUT이후 재전송이면 +// retryCnt = 1; +// batchDoc.getBatchMsg().getBody().setErrorMsg(""); +// }else{ +// //1. 데이터 수신 일련번호 에러인 경우 +// if ( prevTelegramRescd.equals("01") || prevTelegramRescd.equals("02") ) { +// isReSend = true; +// LAST_SEQ = Integer.parseInt(prevTelegramSeqNo); +// +// retryCnt = 0; +// } +// } +// telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ +// public int getCalculatedLength(int idx) { +// +// if (idx >= this.getFieldCount()) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI011"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI012"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// return REAL_BYTE; +// +// } + +// private boolean createFile () +// { +// fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); +// +// if ( fin == null ){ +// try { +// String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); +// String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); +// +// if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { +// fileDir = fileDir + File.separator; +// } +// +// String fileName = fileDir + fileNm; +// +// file = new File(fileName); +// if (!file.exists()) // 파일이 없으면 리턴 False +// { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = fileName; +// String errCode = "BECEAIFJI022"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// throw new Exception(" the File["+fileName+"] does not exist!!!"); +// } +// fin = new FileInputStream(file); +// BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); +// } catch (Exception e) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI028"; +// String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( e.getMessage(), e); +// } +// } +// return !( fin == null); +// } +// +// private boolean makeSendData() +// { +// try { +// if (!createFile()) { +// Logging (ERROR, " file open failed"); +// return false; +// } +// +// if ( retryCnt > 0 ){ // 타임오버 이후의 재 전송인 경우, 이전에 DATA가 있었던 경우에만 +// if ( batchDoc.getBatchMsg().getTelegramBody() != null && !batchDoc.getBatchMsg().getTelegramBody().equals("") ){ +// fileData = batchDoc.getBatchMsg().getTelegramBody().getBytes(); +// } +// }else{ +// if ( isReSend ){ // 중단된 이후 재 송신인 경우 +// skipLine(); +// } +// +// // 레코드 크기 +// int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); +// // 한번에 블러킹 할 건수 +// int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize ); +// // 남은 바이트 수 +// long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); +// // 남은 건수 +// long remainCnt = remainSize / recSize; +// logger.debug("[SEND_KSDBT_0200]seqCnt -->" + seqCnt); +// logger.debug("[SEND_KSDBT_0200]remainCnt-->" + remainCnt); +// if ( seqCnt < remainCnt ){ +// REC_CNT = seqCnt; +// }else{ +// REC_CNT = (int)remainCnt; +// } +// REAL_BYTE = REC_CNT * recSize; +// fileData = new byte[REAL_BYTE]; +// for ( int inx = 0 ; inx < REC_CNT ; inx++){ +// byte[] fileLine = FileUtil.readLine(fin); +// if ( file != null && inx == 0 ){ +// batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); +// } +// if ( inx == REC_CNT -1 ){ +// batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); +// } +// System.arraycopy( fileLine, 0, fileData, inx * recSize, recSize); +// byte[] seqArea = new byte[8]; +// System.arraycopy( fileLine, 0, seqArea, 0, 8 ); +// try { +// SEQUENCE_NO = Integer.parseInt( new String(seqArea)); +// } catch (Exception e) { +// SEQUENCE_NO = 0; +// } +// } +// } +// +// if ( REAL_BYTE == 0 ){ +// this.setFldOpCode("999"); +// fin.close(); +// SEQUENCE_NO = batchDoc.getBatchMsg().getBody().getSeqNum(); +// BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); +// } +// +// return true; +// } catch (Exception e ) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI029"; +// String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( e.getMessage(), e); +// return false; +// } +// } + +// private void skipLine() throws Exception{ +// byte[] fileLine = null; +// byte[] byte_sequence = new byte[8]; +// int iSequence = 0; +// while ( ( fileLine = FileUtil.readLine(fin) ) != null ){ +// System.arraycopy( fileLine, 0, byte_sequence, 0, 8); +// iSequence = Integer.parseInt( new String(byte_sequence)); +// long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + batchDoc.getBatchMsg().getHeader().getRecLen(); +// batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); +// if ( LAST_SEQ == iSequence ) +// return; +// } +// throw new Exception("재전송 시작할 위치를 찾지 못하였습니다."); +// } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } +// SEND_LENGTH += REAL_BYTE; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(0); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(4).substring(3); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(1); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(4); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_T000.java b/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_T000.java new file mode 100644 index 0000000..9218e44 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksdps/SEND_KSDPS_T000.java @@ -0,0 +1,412 @@ +package com.eactive.eai.batch.job.jobItem.ksdps; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KSDPS_T000 extends DefaultTelegram implements TelegramService +{ + +// private FileInputStream fin ; +// private File file; +// private int SEQUENCE_NO; +// private int LAST_SEQ; //일련번호 +// private int REC_CNT; +// private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //실제 송신할 전문의 총길이 +// private boolean isReSend = false; + +// private Properties telegramInfo; +// private byte[] fileData; +// private int retryCnt; + + /** + * 생성자 + */ + public SEND_KSDPS_T000() { + //DATA전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { +// boolean result = makeSendData(); +// if (!result) { +// return false; +// } + if (!calculateSendLength()) return false; + + //TR Code H or T + compileField(0, this.getFldTelegramType(), this.al_FieldProps[0]); + + //응답코드 + compileField(1, this.getResolveResponseCode(), this.al_FieldProps[1]); + + //File Name + compileField(2, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[2]); + + //송수신 파일 Size + compileField(3, "" + batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[3]); + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + +// public int getInformalFieldSendData(int idx, byte[] data) { +// int fldLen = getCalculatedLength(idx); +// try { +// if (idx >= this.getFieldCount() ) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI011"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if (data.length < fldLen) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI014"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// +// ByteArrayInputStream bin = new ByteArrayInputStream(fileData); +// bin.read(data, 0, REAL_BYTE); +// // 20060419 add by khs for 전송상태 확인 +// long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; +// batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); +// +// // 로깅을 위해 +// byte[] fieldData = new byte[fldLen]; +// System.arraycopy(data, 0, fieldData, 0, fldLen); +// this.al_Field.set( idx, fieldData); +// return fldLen; +// } catch (Exception ex) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI006"; +// String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( ex.getMessage(), ex); +// return -1; +// } +// } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + LogUtil.setLogFileEnd(batchDoc); + +// if ( file != null ){ // 처음 전송이면 +// } +// if ( this.getOpCode().equals("000") ){ // DATA전송인 경우 +//// this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO + REC_CNT - 1); +// } +// if ( this.getFldOpCode().equals("999") ) { //DATA를 보낸 후 보낸 SEQ RESET +//// batchDoc.getBatchMsg().getHeader().setSequenceSize(0); +//// batchDoc.getBatchMsg().getHeader().setBlockSize(0); +// } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<4; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 +// baout = new ByteArrayOutputStream(); +// for (int i=10; i< al_Field.size(); i++) { +// baout.write((byte[])this.al_Field.get(i)); +// } +// batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + this.setResolveResponseCode("0000"); +// isReSend = false; +// String prevTelegramHeader = batchDoc.getBatchMsg().getTelegramHeader(); +// String prevTelegramType = ""; +// String prevTelegramRescd = ""; +// String prevTelegramSeqNo = ""; +// +// if ( prevTelegramHeader.length() >= 49 ){ +// prevTelegramType = prevTelegramHeader.substring(18, 22); +// prevTelegramRescd = prevTelegramHeader.substring(35, 37); +// prevTelegramSeqNo = prevTelegramHeader.substring(51, 59); +// } +// +// if ( prevTelegramType.equals("0200")){ /// TIMEOUT이후 재전송이면 +// retryCnt = 1; +// batchDoc.getBatchMsg().getBody().setErrorMsg(""); +// }else{ +// //1. 데이터 수신 일련번호 에러인 경우 +// if ( prevTelegramRescd.equals("01") || prevTelegramRescd.equals("02") ) { +// isReSend = true; +// LAST_SEQ = Integer.parseInt(prevTelegramSeqNo); +// +// retryCnt = 0; +// } +// } +// telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ +// public int getCalculatedLength(int idx) { +// +// if (idx >= this.getFieldCount()) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI011"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI012"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// return REAL_BYTE; +// +// } + +// private boolean createFile () +// { +// fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); +// +// if ( fin == null ){ +// try { +// String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); +// String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); +// +// if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { +// fileDir = fileDir + File.separator; +// } +// +// String fileName = fileDir + fileNm; +// +// file = new File(fileName); +// if (!file.exists()) // 파일이 없으면 리턴 False +// { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = fileName; +// String errCode = "BECEAIFJI022"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// throw new Exception(" the File["+fileName+"] does not exist!!!"); +// } +// fin = new FileInputStream(file); +// BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); +// } catch (Exception e) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI028"; +// String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( e.getMessage(), e); +// } +// } +// return !( fin == null); +// } +// +// private boolean makeSendData() +// { +// try { +// if (!createFile()) { +// Logging (ERROR, " file open failed"); +// return false; +// } +// +// if ( retryCnt > 0 ){ // 타임오버 이후의 재 전송인 경우, 이전에 DATA가 있었던 경우에만 +// if ( batchDoc.getBatchMsg().getTelegramBody() != null && !batchDoc.getBatchMsg().getTelegramBody().equals("") ){ +// fileData = batchDoc.getBatchMsg().getTelegramBody().getBytes(); +// } +// }else{ +// if ( isReSend ){ // 중단된 이후 재 송신인 경우 +// skipLine(); +// } +// +// // 레코드 크기 +// int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); +// // 한번에 블러킹 할 건수 +// int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize ); +// // 남은 바이트 수 +// long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); +// // 남은 건수 +// long remainCnt = remainSize / recSize; +// logger.debug("[SEND_KSDBT_0200]seqCnt -->" + seqCnt); +// logger.debug("[SEND_KSDBT_0200]remainCnt-->" + remainCnt); +// if ( seqCnt < remainCnt ){ +// REC_CNT = seqCnt; +// }else{ +// REC_CNT = (int)remainCnt; +// } +// REAL_BYTE = REC_CNT * recSize; +// fileData = new byte[REAL_BYTE]; +// for ( int inx = 0 ; inx < REC_CNT ; inx++){ +// byte[] fileLine = FileUtil.readLine(fin); +// if ( file != null && inx == 0 ){ +// batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); +// } +// if ( inx == REC_CNT -1 ){ +// batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); +// } +// System.arraycopy( fileLine, 0, fileData, inx * recSize, recSize); +// byte[] seqArea = new byte[8]; +// System.arraycopy( fileLine, 0, seqArea, 0, 8 ); +// try { +// SEQUENCE_NO = Integer.parseInt( new String(seqArea)); +// } catch (Exception e) { +// SEQUENCE_NO = 0; +// } +// } +// } +// +// if ( REAL_BYTE == 0 ){ +// this.setFldOpCode("999"); +// fin.close(); +// SEQUENCE_NO = batchDoc.getBatchMsg().getBody().getSeqNum(); +// BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); +// } +// +// return true; +// } catch (Exception e ) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI029"; +// String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( e.getMessage(), e); +// return false; +// } +// } + +// private void skipLine() throws Exception{ +// byte[] fileLine = null; +// byte[] byte_sequence = new byte[8]; +// int iSequence = 0; +// while ( ( fileLine = FileUtil.readLine(fin) ) != null ){ +// System.arraycopy( fileLine, 0, byte_sequence, 0, 8); +// iSequence = Integer.parseInt( new String(byte_sequence)); +// long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + batchDoc.getBatchMsg().getHeader().getRecLen(); +// batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); +// if ( LAST_SEQ == iSequence ) +// return; +// } +// throw new Exception("재전송 시작할 위치를 찾지 못하였습니다."); +// } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } +// SEND_LENGTH += REAL_BYTE; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(0); + } +// // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(4).substring(3); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(1); + } +// //업무관리코드 필드값 리턴 +// public String getOpCode() +// { +// return super.getFieldValueString(4); +// } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25.java b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25.java new file mode 100644 index 0000000..300c346 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25.java @@ -0,0 +1,59 @@ +package com.eactive.eai.batch.job.jobItem.ksnet; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KSN25 extends DefaultTelegram implements TelegramService +{ + + public RECV_KSN25() { + } + + public boolean doExecute() { + + return true; + } + /** + * RULE의 TelegramType만 가지고, 다음 텔레그램의 ID를 결정한다. + */ +// public String getRealRecvTelegram() { +// +// PhaseInfoVO info = (PhaseInfoVO) this.al_NextStage.get(0); +// if ( info == null ) return ""; +// batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (info.getPhaseSeq() ); //Stage Logging 용 +// batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(info.getTelegramID()); //Stage Logging 용 +// return info.getTelegramID(); +// } + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0320.java b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0320.java new file mode 100644 index 0000000..d1f8fda --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0320.java @@ -0,0 +1,238 @@ +package com.eactive.eai.batch.job.jobItem.ksnet; + +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_KSN25_0320 extends DefaultTelegram implements TelegramService +{ + private String strFullPathName = ""; + private FileOutputStream fout = null; + + private File rcvRealFile = null; + private File rcvArchFile = null; + private File rcvErrorFile = null; + + public RECV_KSN25_0320() { + } + + public boolean doPreExecute() + { + if (!super.doPreExecute()) return false; + //수신 파일 Start DB로그 + try { + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() <= 0 ){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + String pattern = bJobInfo.getSndrcvFileName(); + String recvFileName = FileUtil.getRecvFileName(bizCode, pattern, batchDoc, true); + batchDoc.getBatchMsg().getHeader().setFileName( recvFileName ); + LogUtil.setLogFileStart(batchDoc); + } + }catch (Exception ex){ + logger.error("{} ★★★★★ DB로그 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + return false; + } + + //1. 수신파일 저장 경로 설정 + //저장 디렉토리는 Inbound Server 에서 설정됨 (응답수신 Real 또는 응답송신 Real) + strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separator; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + logger.info("{} 응답수신 파일 저장 경로 : [" + this.strFullPathName + "]", logHeader); + rcvRealFile = new File( this.strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPathName) ); + rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPathName) ); + + //2. 응답수신 파일 생성 + logger.info("{} >>>>> 응답수신 파일 생성...... ("+ this.strFullPathName +")", logHeader); + try { + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() <= 0 ){ + fout = new FileOutputStream(rcvRealFile, false); + }else{ + fout = new FileOutputStream(rcvRealFile, true); + } + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI041", new String[] {rcvRealFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 해당 경로에 생성시 오류가 발생하였습니다. [Path : {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + try { + return Integer.parseInt(new String ((byte[]) al_Field.get(4))); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + //파일 끝에 append + fout.write(data, 0, length); + + //읽어 들인 파일 사이즈 저장 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch (Exception ex) { + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.error("{} ★★★★★ 수신 파일 데이터 WRITE 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + public boolean doExecute() { + if (!super.doExecute()) return false; + String eofFlag = super.getFieldValueString(6); + if (eofFlag.equals("EF") ) + setConditionTxt(TelegramKeys.EOF); + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //1. 수신 파일 Close =========================================================== + if (fout != null) fout.close(); + + if ( !getConditionTxt().equals( TelegramKeys.EOF) ){ + return true; + } + + //2. 수신 파일 End DB로그 ====================================================== + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //사이즈 비교 + long recvSize = rcvRealFile.length(); + batchDoc.getBatchMsg().getHeader().setFileSize(recvSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); +// if ( recvSize != batchDoc.getBatchMsg().getHeader().getFileSize() ){ +// super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SEND_BYTE_ERROR); +// logger.debug(this.getClass().getName() + "[doPostExecute]recvSize-->" + recvSize ); +// logger.debug(this.getClass().getName() + "[doPostExecute]batchDoc.getBatchMsg().getHeader().getFileSize()-->" + batchDoc.getBatchMsg().getHeader().getFileSize() ); +// return false; +// } + super.setFileHeaderAndTrailer(rcvRealFile); + } + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) ) { + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + logger.debug(this.getClass().getName() + "[doPostExecute]super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](1)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPathName) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](2)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + // 전문종별코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(6); + } + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String rsgubun = super.getFieldValueString(1); + if ( rsgubun.equals("RJ") || rsgubun.equals("SJ") ) + return "0320"; + return "0000"; + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0330.java b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0330.java new file mode 100644 index 0000000..edb846f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0330.java @@ -0,0 +1,85 @@ +package com.eactive.eai.batch.job.jobItem.ksnet; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KSN25_0330 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_KSN25_0330() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i= batchDoc.getBatchMsg().getHeader().getFileSize()){ + setConditionTxt(TelegramKeys.EOF); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + String rsgubun = super.getFieldValueString(1); + if ( rsgubun.equals("RJ") || rsgubun.equals("SJ") ) + return "0330"; + return "0000"; + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0600.java b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0600.java new file mode 100644 index 0000000..975feb6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksnet/RECV_KSN25_0600.java @@ -0,0 +1,50 @@ +package com.eactive.eai.batch.job.jobItem.ksnet; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_KSN25_0600 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_KSN25_0600() { + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i= batchDoc.getBatchMsg().getHeader().getFileSize()){ + compileField(6, "EF", this.al_FieldProps[6]); + }else{ + compileField(6, "", this.al_FieldProps[6]); + } + + //<< 전문 완성 + + return true; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPreExecute() { + if (!super.doPreExecute()) return false; + SEQ_NO = batchDoc.getBatchMsg().getBody().getSeqNum() + 1; + return true; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size() -1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += fileData.length; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fileData.length; + } + + /** + * 여기서는 파일을 닫는다. + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i" + curSize + "/" + totSize ); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < batchDoc.getBatchMsg().getHeader().getSequenceSize()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, fileData.length); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return fileData.length; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean setBlockAndSeqNO (){ + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + REAL_BYTE = 0; // data 버퍼에 현재까지 채워진 공간 + int bufferSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + fileData = new byte[bufferSize]; + for ( int inx = 0; inx < bufferSize; inx++){ + fileData[inx] = ' '; + } + int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); + byte[] readData = new byte[( (bufferSize - 100) / recSize ) * recSize]; + + if (fileHeader != null ){ + int headerLen = fileHeader.length; + System.arraycopy( fileHeader, 0, fileData, 0, headerLen); + REAL_BYTE = bis.read(readData); + batchDoc.getBatchMsg().setFileHeader(new String(fileHeader)); + fileHeader = null; + System.arraycopy(readData, 0, fileData, headerLen, REAL_BYTE); + REAL_BYTE += headerLen; + }else{ + REAL_BYTE = bis.read(readData); + System.arraycopy(readData, 0, fileData, 0, REAL_BYTE); + } + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + if ( lnCurSize >= batchDoc.getBatchMsg().getHeader().getFileSize()){ + batchDoc.getBatchMsg().setFileTrailer(new String(fileData)); + } + + return true; + + } catch (Exception ex) { + logger.error("{} ★★★★★ 송신 파일 데이터 READ 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + private boolean createFile() + { + try { + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( bis != null ) return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + int headerLen = TelegramKeys.KSNET_HEADER_LEN; + fileHeader = new byte[headerLen]; + for (int inx = 0; inx < headerLen - 2; inx++) { + fileHeader[inx] = ' '; + } + + // 헤더 구분 : <
> + System.arraycopy( "<
>".getBytes(), 0, fileHeader, 0, 10); + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + // 송신자 ID : 송신자의 ID 체크파일에서 처리 + System.arraycopy( hdrInfo.getBytes(), 38, fileHeader, 10, 8); + + // 업체 구분: 송신자의 업체구분 코드 + // 정보 구분: BODY의 정보구분 코드 (문서명) + String infoGb = batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( infoGb.getBytes(), 0, fileHeader, 18, 5); + + // 수신자수로 추정 + System.arraycopy( "NN001".getBytes(), 0, fileHeader, 23, 5); + + // 수신자 ID : + System.arraycopy( hdrInfo.getBytes(), 46, fileHeader, 28, 8); + // 레코드 구분자 : CR, LF + fileHeader[headerLen-2] = '\r'; + fileHeader[headerLen-1] = '\n'; + + SEQ_NO = 1; + //요구송신 파일 Start DB로그 + try { + LogUtil.setLogFileStart(batchDoc); + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + this.filename = fileDir+ File.separator + fileNm; + this.file = new File(this.filename); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File does not exist!!! ["+this.filename+"]", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , filename, bis); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI021"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ksnet/SEND_KSN25_0330.java b/src/com/eactive/eai/batch/job/jobItem/ksnet/SEND_KSN25_0330.java new file mode 100644 index 0000000..4393347 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ksnet/SEND_KSN25_0330.java @@ -0,0 +1,130 @@ +package com.eactive.eai.batch.job.jobItem.ksnet; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_KSN25_0330 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_KSN25_0330() { + //송신 파일 통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //송수신구분 수신요청[RJ] 송신요청[SJ] + compileField(1, "RJ", this.al_FieldProps[1]); + + //FILE NAME + compileField(2, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[2]); + + //전송일련번호 + compileField(3, "" + batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[3]); + + //응답코드 + compileField(4, this.getResolveResponseCode(), this.al_FieldProps[4]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i>>>> 응답코드 Checking......", logHeader); + int currFiledIndex = 8; + String currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.RES_CODE_SUCESS)) { + String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getCmsRetDescription(currFieldValue); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); // + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + }catch (Exception e){ + logger.error( e.getMessage(), e); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString()); + super.setConditionTxt(TelegramKeys.ERROR); + return false; + } + return true; + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + return Integer.parseInt( getTelegramInfo().getProperty(propKey) ); + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + idx = vo.getLengthField(); + if (idx == 0) return -1; + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + try { + if ( Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ) == 0 ) + read_byte_size -= 1; + }catch(Exception e1) {} + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + return; + } + LogUtil.setLogFileEnd(batchDoc); + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){} + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0310.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0310.java new file mode 100644 index 0000000..5d39a7c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0310.java @@ -0,0 +1,251 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGCNS_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_LGCNS_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + try { + if ( Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ) == 0 ) + read_byte_size -= 1; + }catch(Exception e1) {} + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0320.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0320.java new file mode 100644 index 0000000..c2045fb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0320.java @@ -0,0 +1,238 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGCNS_0320 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_LGCNS_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + try { + if ( Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ) == 0 ) + read_byte_size -= 1; + }catch(Exception e1) {} + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0600.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0600.java new file mode 100644 index 0000000..5a45a08 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0600.java @@ -0,0 +1,118 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGCNS_0600 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_LGCNS_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0610.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0610.java new file mode 100644 index 0000000..42750d5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0610.java @@ -0,0 +1,143 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGCNS_0610 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_LGCNS_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + // File Open LOG + File ff = new File(fileName); + + //응답송신이 아니고 0610/0004를 수신하면 (응답송신의 경우 recv0300일경우에 파일을 이동시키므로 이단계에서는 파일이 존재하지 않음 + if (!CommonKeys.PROCESS_RESPONSE_SEND.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + if (ff.exists() && OpCode_noexsist.equals(this.getOpCode())) { + logger.info("{} FILE SIZE ("+ ff.length() + "]", logHeader); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(ff); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + if (OpCode_noexsist.equals(this.getOpCode()) && fileNm != null && !fileNm.trim().equals("")) { + //응답수신 파일 Start DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0620.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0620.java new file mode 100644 index 0000000..941e2fb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0620.java @@ -0,0 +1,123 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGCNS_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_LGCNS_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0630.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0630.java new file mode 100644 index 0000000..283bc8c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0630.java @@ -0,0 +1,170 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGCNS_0630 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_LGCNS_0630() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + + String fileInfo = new String ((byte[]) al_Field.get(9)); + String fName = fileInfo.substring(0, 20).trim(); + long fSize = Long.parseLong(fileInfo.substring(20, 32)); //화일 size + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_CDCMS_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + } + + String pattern = null; + long recLen = 0; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getHeader().setFileSize(fSize); + long recCnt = 0; + if ( recLen > 0 ){ + recCnt = fSize / recLen; + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0640.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0640.java new file mode 100644 index 0000000..1c0180b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/RECV_LGCNS_0640.java @@ -0,0 +1,310 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGCNS_0640 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_LGCNS_0640() { + //화일정보수신통보 + } + + BufferedInputStream bis; + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String fileInfo = new String ((byte[]) al_Field.get(9)); // 화일정보내역 + long fSize = Long.parseLong(fileInfo.substring(20, 32)); //화일 size + if (getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_ALREADY_RECEIVED) + ||getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_NOT_REGISTERED)) { //기송신 파일이면 + checkMoreFileinDB(); + } else { + + if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면 + // 레코드 크기 150 + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + // 한번에 블러킹 할 건수 26 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recLen ); + + // 1887600 % ( 150 * 26 ) + if ( fSize % ( recLen * seqCnt ) != 0 ){ + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } + if ( !createFile() ){ + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } + + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + + // 1887600/150= 12584 + int blockSize = batchDoc.getBatchMsg().getHeader().getBlockSize(); + long skipBlockCnt = fSize / ( blockSize * seqCnt * recLen); + + if ( skipBlockCnt > 0 ){ + long iLoopCnt = skipBlockCnt * blockSize * seqCnt; + for( int inx = 0; inx < iLoopCnt; inx++){ + FileUtil.readLine(bis); + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen); + } + batchDoc.getBatchMsg().getBody().setBlockNum((int)skipBlockCnt+1); //기 송신된 블럭 다음부터 송신 + }else{ + batchDoc.getBatchMsg().getBody().setBlockNum(1); + } + + // + int seqSize = recLen * seqCnt; // 3900 + int blockDataSize = blockSize * seqSize; // 390000 + int seqNo = (int)( fSize % blockDataSize ) / seqSize; + + int appendLen = 0; + try { + appendLen = Integer.parseInt(getJobInfo().getProperty(TelegramKeys.APPEND_LL_LEN)); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + for (int inx = 0; inx < seqNo; inx++) { + byte[] fileData = new byte[seqSize]; + for (int jnx = 0; jnx < seqCnt; jnx++) { + byte[] fileLine = FileUtil.readLine(bis); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, jnx * recLen, Math.min(recLen, fileLine.length)); + if ( appendLen > 0 ){ + fileData[((jnx+1) * recLen)-1] = '\n'; + } + if ( appendLen > 1 ){ + fileData[((jnx+1) * recLen)-2] = '\r'; + } + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + batchDoc.getBatchMsg().getBody().setCurFileSize(curSize + recLen); + + } + + block_data.put( new Integer(inx), fileData); + } + batchDoc.getBatchMsg().getBody().setSeqNum(seqNo); + + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID(); + String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath()); + batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName()); + batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getEAIBatchMessage().getHeader().setFileSize(0); + batchDoc.getEAIBatchMessage().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + + } + */ + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0300.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0300.java new file mode 100644 index 0000000..57659c9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0300.java @@ -0,0 +1,376 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_LGCNS_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //결번갯수 + compileField(11, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + String jobCode = this.batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return MISSING_FIELD.length(); + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=1,3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[block_size]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0310.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0310.java new file mode 100644 index 0000000..276981e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0310.java @@ -0,0 +1,328 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_LGCNS_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return REAL_BYTE; + + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0320.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0320.java new file mode 100644 index 0000000..da195f0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0320.java @@ -0,0 +1,437 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0320 extends DefaultTelegram implements TelegramService +{ + + private BufferedInputStream bis; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_LGCNS_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + private boolean createFile () + { + + bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if( bis != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + bis = new BufferedInputStream ( new FileInputStream(file) ); + BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + + // 한번에 읽어 보낼 크기 계산 + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + REAL_BYTE = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / recLen ) * recLen; + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + + boolean isLastSeq = false; + if ( REAL_BYTE >= remainSize ){ + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + + fileData = new byte[REAL_BYTE]; + REAL_BYTE = bis.read(fileData); +// for ( int inx = 0 ; inx < readCnt ; inx++){ +// byte[] fileLine = FileUtil.readLine(fin); +// if ( fileLine == null ){ +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI029"; +// Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ +// "확인 바랍니다."); +// String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( e.getMessage(), e); +// return false; +// } +// if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){ +// Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ +// "확인 바랍니다.\n" + +// "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + +// "파일에서 읽은 길이[" + fileLine.length + "]"); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); +// logger.error( e.getMessage(), e); +// return false; +// } +// System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), +// Math.min(batchDoc.getBatchMsg().getHeader().getRecLen(), fileLine.length)); +// if ( appendLen > 0 ){ +// fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-1] = '\n'; +// } +// if ( appendLen > 1 ){ +// fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-2] = '\r'; +// } +// } + + if ( isLastSeq ){ + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0600.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0600.java new file mode 100644 index 0000000..140d8ed --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0600.java @@ -0,0 +1,231 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties jobInfo; + /** + * 생성자 + */ + public SEND_LGCNS_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //자기계정 - 사용하지 않음 + compileField(11, "", this.al_FieldProps[11]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(12, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[12]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(13, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[13]); + + //상대계정 - 사용하지 않음 + compileField(14, "", this.al_FieldProps[14]); + + //상대ID + compileField(15, jobInfo.getProperty(TelegramKeys.MLINK_DOC_RECV_ID), this.al_FieldProps[15]); + + //시작일자 + if ( this.getFldOpCode().equals("001")){ + compileField(16, TelegramKeys.getYYYYMMDD() + "0000", this.al_FieldProps[9]); + }else{ + compileField(16, "", this.al_FieldProps[16]); + } + + //종료일자 + if ( this.getFldOpCode().equals("001")){ + compileField(17, TelegramKeys.getYYYYMMDD() + "2359", this.al_FieldProps[9]); + }else{ + compileField(17, "", this.al_FieldProps[17]); + } + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0610.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0610.java new file mode 100644 index 0000000..8f72cac --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0610.java @@ -0,0 +1,272 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties jobInfo; + /** + * 생성자 + */ + public SEND_LGCNS_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //자기계정 - 사용하지 않음 + compileField(11, "", this.al_FieldProps[11]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(12, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[12]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(13, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[13]); + + //상대계정 - 사용하지 않음 + compileField(14, "", this.al_FieldProps[14]); + + //상대ID + compileField(15, jobInfo.getProperty(TelegramKeys.MLINK_DOC_RECV_ID), this.al_FieldProps[15]); + + //시작일자 + compileField(16, TelegramKeys.getYYYYMMDD() + "0000", this.al_FieldProps[9]); + + //종료일자 + compileField(17, TelegramKeys.getYYYYMMDD() + "2359", this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (this.getFldOpCode().equals("001")) return true; + + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0620.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0620.java new file mode 100644 index 0000000..eb9c195 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0620.java @@ -0,0 +1,314 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_LGCNS_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 1: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + if (telegramInfo == null) {// 20250910 uwf + telegramInfo = getTelegramInfo(); + } + + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 1: + // TR 코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + + break; + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0630.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0630.java new file mode 100644 index 0000000..b95a639 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0630.java @@ -0,0 +1,366 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0630 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + /** + * 생성자 + */ + public SEND_LGCNS_0630() { + //화일정보수신요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + int seqSize = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ) * batchDoc.getBatchMsg().getHeader().getRecLen(); + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(fileName, 20)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12)); + // 0630 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + fileInfo.append(makeZero(""+(SEND_LENGTH + seqSize - 13), 4)); + + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + + //상대ID + compileField(10, fileName, this.al_FieldProps[10]); + + //상대ID + compileField(11, makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12), this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + batchDoc.getBatchMsg().getHeader().setFileSize(getFileSize ()); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private long getFileSize () + { + + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + return file.length(); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return 0; + } + + } +// /** +// * int getCalculatedLength(int idx) +// * -------------------------------------------------------------------------------------- +// * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. +// * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. +// */ +// public int getCalculatedLength(int idx) { +// +// if (idx >= this.getFieldCount()) { +// Logging(DEBUG, "getCalculatedLength> parameter is bigger than field count"); +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI011"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI012"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// int fieldLen = -1; +//// String propKey = ""; +//// switch (idx) { +//// +//// case 1: +//// propKey = TelegramKeys.TRCD_LEN; +//// break; +//// +//// case 3: +//// propKey = TelegramKeys.ORGN_CD_LEN; +//// break; +//// +//// default: +//// String[] msgArgs = new String[2]; +//// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +//// msgArgs[1] = ""+idx; +//// String errCode = "BECEAIFJI012"; +//// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +//// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +//// return -1; +//// } +//// +//// try { +//// fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); +//// +//// } catch (Exception e) { +//// String[] msgArgs = new String[2]; +//// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +//// msgArgs[1] = propKey; +//// String errCode = "BECEAIFJI012"; +//// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +//// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +//// return -1; +//// } +// +// return fieldLen; +// } +// +// public int getInformalFieldSendData(int idx, byte[] data) { +// int fldLen = getCalculatedLength(idx); +// try { +// if (idx >= this.getFieldCount() ) { +// Logging(DEBUG, " getInformalFieldSendData> " +idx+ " is bigger than field count"); +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI011"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +// if (data.length < fldLen) { +// Logging(DEBUG, " getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size"); +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = ""+idx; +// String errCode = "BECEAIFJI014"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// return -1; +// } +//// switch (idx) { +//// case 1: +//// // TR 코드 +//// System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); +//// +//// break; +//// case 3: +//// // 기관코드 +//// System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); +//// +//// break; +//// +//// default: +//// break; +//// } +// +// // 로깅을 위해 +// byte[] fieldData = new byte[fldLen]; +// System.arraycopy(data, 0, fieldData, 0, fldLen); +// this.al_Field.set( idx, fieldData); +// return fldLen; +// } catch (Exception ex) { +// String[] msgArgs = new String[1]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String errCode = "BECEAIFJI006"; +// String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// logger.error( ex.getMessage(), ex); +// return -1; +// } +// } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0640.java b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0640.java new file mode 100644 index 0000000..d8ab149 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgcns/SEND_LGCNS_0640.java @@ -0,0 +1,249 @@ +package com.eactive.eai.batch.job.jobItem.lgcns; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGCNS_0640 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + +// private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_LGCNS_0640() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //트랜잭션코드 -- 사용하지 않음 + compileField(1, "", this.al_FieldProps[1]); + + //업무구분코드 - “CMS” + compileField(2, "CMS", this.al_FieldProps[2]); + + //기관코드 “71” + compileField(3, "71", this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 S/R : 서버송신 : S 서버수신: R + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, "R", this.al_FieldProps[5]); + }else{ + compileField(5, "S", this.al_FieldProps[5]); + } + + //송수신 FLAG B/C B:Bank, C:Center + compileField(6, "B", this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(batchDoc.getBatchMsg().getHeader().getFileName(), 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getBody().getCurFileSize(),12)); + fileInfo.append(makeZero(""+calculateTelegramSize(), 4)); + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; +// telegramInfo = getTelegramInfo(); + //해당 거래구분에 대한 Job_Code 값 설정 + //거래구분코드 조회 BizCode 조회 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + if (info != null) { + batchDoc.getBatchMsg().getHeader().setJobCode(info.getMsgDstCode());; + } else { + logger.debug("{} " + batchDoc.getBatchMsg().getHeader().getUUID()+ "'s Job Code is null", logHeader); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + batchDoc.getBatchMsg().getHeader().setJobCode((processCode+"00000")); //dummy code + // TEST 용 return false; + } +// try { +// int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); +// Thread.sleep(sleepTime); +// } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private int calculateTelegramSize(){ + int recSize = 200; + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo != null && bJobInfo.getFileRecSize() > 0 ){ + recSize = (int)Math.min(bJobInfo.getFileRecSize(), 4000); + } + + // 0630/0640 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630/0640 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + return (batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize) * recSize + SEND_LENGTH - 13; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LG12X.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LG12X.java new file mode 100644 index 0000000..065f35b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LG12X.java @@ -0,0 +1,67 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LG12X extends DefaultTelegram implements TelegramService +{ + + public RECV_LG12X() { + } + + public boolean doExecute() { + + return true; + } + /** + * RULE의 TelegramType만 가지고, 다음 텔레그램의 ID를 결정한다. + */ + public String getRealRecvTelegram() { + + PhaseInfoVO info = (PhaseInfoVO) this.al_NextStage.get(0); + if ( info == null ) return ""; + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (info.getPhaseSeq() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(info.getTelegramID()); //Stage Logging 용 + return info.getTelegramID(); + } + + /** + * ignore field count + */ + public int getFieldCount() { + return 0; + } + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 0; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB.java new file mode 100644 index 0000000..bd6120d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB.java @@ -0,0 +1,29 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LGUFB extends DefaultTelegram implements TelegramService +{ + + public RECV_LGUFB() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_030.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_030.java new file mode 100644 index 0000000..4d27023 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_030.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LGUFB_030 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_LGUFB_030() { + //LOGIN 응답 + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_070.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_070.java new file mode 100644 index 0000000..dc47abd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_070.java @@ -0,0 +1,60 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LGUFB_070 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_LGUFB_070() { + //LOGIN 응답 + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_100.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_100.java new file mode 100644 index 0000000..23a80cc --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_100.java @@ -0,0 +1,137 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.lang.String; +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; + +public class RECV_LGUFB_100 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_LGUFB_100() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + String fileName = new String ((byte[]) al_Field.get(5)).substring(0, 5); + String fromId = new String ((byte[]) al_Field.get(7)).trim(); + if ( !fromId.equals("") ){ + fileName = fileName + "_" + fromId; + } + String endGb = new String ((byte[]) al_Field.get(11)); + String bizCode = fileName.substring(0,5); + long fileSize = Long.parseLong(new String ((byte[]) al_Field.get(6))); //화일 size + batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + if ( endGb.equalsIgnoreCase(TelegramKeys.MAGICLINK_END)) { + this.setConditionTxt(TelegramKeys.NOFILE); + } + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + + try { + int recSize = (int)bJobInfo.getFileRecSize(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(fileSize/recSize); + } catch (Exception e) { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + } + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fileName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(new String ((byte[]) al_Field.get(5))); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separator; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + File file = new File(strFullPathName); + if ( file.exists() ){ + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + LogUtil.setLogFileStart(batchDoc); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_110.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_110.java new file mode 100644 index 0000000..58a847e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_110.java @@ -0,0 +1,80 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LGUFB_110 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_LGUFB_110() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_120.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_120.java new file mode 100644 index 0000000..6b0f4c8 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_120.java @@ -0,0 +1,205 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGUFB_120 extends DefaultTelegram implements TelegramService +{ + private String strFullPathName = ""; + private FileOutputStream fout = null; + + private File rcvRealFile = null; + private File rcvArchFile = null; + private File rcvErrorFile = null; + + public RECV_LGUFB_120() { // 다른 전문과 달리 전문 번호가 없어 편의상 120번을 부여함 + } + + public boolean doPreExecute() + { + if (!super.doPreExecute()) return false; + //1. 수신파일 저장 경로 설정 + //저장 디렉토리는 Inbound Server 에서 설정됨 (응답수신 Real 또는 응답송신 Real) + strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPathName.charAt(strFullPathName.length()-1) != File.separatorChar) { + strFullPathName = strFullPathName + File.separator; + } + strFullPathName = strFullPathName + batchDoc.getBatchMsg().getHeader().getFileName(); + + logger.info("{} 응답수신 파일 저장 경로 : [" + this.strFullPathName + "]", logHeader); + rcvRealFile = new File( this.strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPathName) ); + rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPathName) ); + + //2. 응답수신 파일 생성 + logger.info("{} >>>>> 응답수신 파일 생성...... ("+ this.strFullPathName +")", logHeader); + try { +// boolean append = true; +// if ( batchDoc.getBatchMsg().getBody().getCurFileSize() < 1){ +// append = false; +// } + fout = new FileOutputStream(rcvRealFile, true); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI041", new String[] {rcvRealFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 해당 경로에 생성시 오류가 발생하였습니다. [Path : {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + return false; + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + try { + return (int)batchDoc.getBatchMsg().getHeader().getFileSize(); +// return Integer.parseInt(new String ((byte[]) al_Field.get(0))); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + //파일 끝에 append + fout.write(data, 0, length); + + //읽어 들인 파일 사이즈 저장 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch (Exception ex) { + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.error("{} ★★★★★ 수신 파일 데이터 WRITE 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //1. 수신 파일 Close =========================================================== + if (fout != null) fout.close(); + + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() < batchDoc.getBatchMsg().getHeader().getFileSize() ){ + return true; + } + + setConditionTxt(TelegramKeys.EOF); + //2. 수신 파일 End DB로그 ====================================================== + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //사이즈 비교 + long recvSize = rcvRealFile.length(); + if ( recvSize != batchDoc.getBatchMsg().getHeader().getFileSize() ){ + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SEND_BYTE_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute]recvSize-->" + recvSize ); + logger.debug(this.getClass().getName() + "[doPostExecute]batchDoc.getBatchMsg().getHeader().getFileSize()-->" + batchDoc.getBatchMsg().getHeader().getFileSize() ); + return false; + } + super.setFileHeaderAndTrailer(rcvRealFile); + } + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) ) { + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + logger.debug(this.getClass().getName() + "[doPostExecute]super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](1)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPathName) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.MAGIC_RES_CODE_SYSTEM_ERROR); + logger.debug(this.getClass().getName() + "[doPostExecute](2)super.getResolveResponseCode()-->" + super.getResolveResponseCode() ); + return false; + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_130.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_130.java new file mode 100644 index 0000000..ea30cf2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/RECV_LGUFB_130.java @@ -0,0 +1,142 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LGUFB_130 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_LGUFB_130() { + //수신확인 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + + String procYn = new String ((byte[]) al_Field.get(7)); // 처리여부 + + if (getResCode().equalsIgnoreCase(TelegramKeys.MAGIC_RES_CODE_SUCESS) + && procYn.equalsIgnoreCase("Y")) { + LogUtil.setLogFileEnd(batchDoc); + checkMoreFileinDB(); + }else{ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[1]; + msgArgs[0] = getResCode() + ", 처리여부:" + procYn; + String errCode = "BECEAIFRS021"; //'기타오류'(응답코드:{1}) 응답전문이 수신되었습니다. + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + LogUtil.setLogFileEnd(batchDoc); + } + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// SchedulerMessageVO info; +// try{ +// info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); +// if ( info == null ) { +// return; +// } +// String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); +// String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); +// +// //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 +// SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); +// +// //BatchMsgDoc 값 설정 +// batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); +// batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); +// batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); +// batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); +// batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); +// batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); +// BatchJobInfoVO bjInfo = DirInfoManager.getInstance().getFileInfo(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setRecLen((int)bjInfo.getFileRecSize()); +// batchDoc.getBatchMsg().getHeader().setFileSize(0); +// batchDoc.getBatchMsg().getBody().setCurFileSize(0); +// this.setConditionTxt(""); +// +// } catch ( Exception e){ +// +// } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_003.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_003.java new file mode 100644 index 0000000..28d0515 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_003.java @@ -0,0 +1,190 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGUFB_003 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_LGUFB_003() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, "", this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[6]); + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + }else{ + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[7]); + //File Name +// compileField(8, jobInfo.getProperty(TelegramKeys.MLINK_FILENAME), this.al_FieldProps[8]); + compileField(8, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[8]); + //Flag + compileField(9, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[9]); + //시작시간 + compileField(10, "200000000000", this.al_FieldProps[10]); + //끝시간 + compileField(11, TelegramKeys.getYYYYMMDD() + "2400", this.al_FieldProps[11]); + } + + //Password 변경 여부 + compileField(12, "", this.al_FieldProps[12]); + + //New Password + compileField(13, "", this.al_FieldProps[13]); + + //Comm Size + compileField(14, "" +batchDoc.getBatchMsg().getHeader().getPacketSize(), this.al_FieldProps[14]); + + //FILLER + compileField(15, "", this.al_FieldProps[15]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + batchDoc.getBatchMsg().getBody().setErrorMsg(""); +// jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_007.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_007.java new file mode 100644 index 0000000..3aad99f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_007.java @@ -0,0 +1,181 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGUFB_007 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; +// private Properties jobInfo; + + /** + * 생성자 + */ + public SEND_LGUFB_007() { + //LOGOUT 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, "", this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[6]); + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + }else{ + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[7]); + //File Name +// compileField(8, jobInfo.getProperty(TelegramKeys.MLINK_FILENAME), this.al_FieldProps[8]); + compileField(8, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[8]); + //Flag + compileField(9, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + } + + //FILLER + compileField(12, "", this.al_FieldProps[12]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; +// jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_100.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_100.java new file mode 100644 index 0000000..9ca798a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_100.java @@ -0,0 +1,240 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGUFB_100 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + private File file; +// private Properties + /** + * 생성자 + */ + public SEND_LGUFB_100() { + //송신 파일 통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); +// try { +// if ( hdrInfo.substring(58, 61).equals("LEN")){ +// int newLen = Integer.parseInt(hdrInfo.substring(61, 65)); +// batchDoc.getBatchMsg().getHeader().setRecLen(newLen); +// } +// } catch (Exception e) {} + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, "", this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, ""+calculateFileSize(), this.al_FieldProps[6]); + + //송신자 ID + compileField(7, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[7]); + + //수신자 ID + compileField(8, hdrInfo.substring(48, 58), this.al_FieldProps[8]); + + //FILLER 1 + compileField(9, "", this.al_FieldProps[9]); + + //FILLER 2 + compileField(10, "", this.al_FieldProps[10]); + + //마지막 여부 - 체크 안함 + compileField(11, TelegramKeys.MAGICLINK_END, this.al_FieldProps[10]); + + /* + * + if (checkMoreFile()){ + compileField(11, TelegramKeys.MAGICLINK_NEXT, this.al_FieldProps[10]); + }else{ + } + */ + + //전송종류 + compileField(12, TelegramKeys.MAGICLINK_NEW, this.al_FieldProps[12]); + + //FILLER 3 + compileField(13, "", this.al_FieldProps[13]); + + //FILLER 4 + compileField(14, "", this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private long calculateFileSize () { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + + long sendFileSize = file.length() + TelegramKeys.MLINK_HEADER_LEN; + this.batchDoc.getBatchMsg().getHeader().setFileSize(sendFileSize); + return sendFileSize; + + } catch (Exception e) { + return 0; + } + } + + /* + private boolean checkMoreFile(){ + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info != null ) { + return true; + } + } catch ( Exception e){ + return false; + } + return false; + } + */ + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_110.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_110.java new file mode 100644 index 0000000..38f6c66 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_110.java @@ -0,0 +1,174 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGUFB_110 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + /** + * 생성자 + */ + public SEND_LGUFB_110() { + //송신 파일 통보응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, "", this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getRenamedFileName(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, "" + 0, this.al_FieldProps[6]); + + //송신자 ID + compileField(7, recvTelegramBody.substring(30,50), this.al_FieldProps[7]); + + //수신자 ID + compileField(8, recvTelegramBody.substring(50,70), this.al_FieldProps[8]); + + //FILLER 1 + compileField(9, "", this.al_FieldProps[9]); + + //FILLER 2 + compileField(10, "", this.al_FieldProps[10]); + + //마지막 여부 + compileField(11, recvTelegramBody.substring(81,84), this.al_FieldProps[10]); + + //전송종류 + compileField(12, recvTelegramBody.substring(84,87), this.al_FieldProps[12]); + + //FILLER 3 + compileField(13, "", this.al_FieldProps[13]); + + //FILLER 4 + compileField(14, makeZero(""+batchDoc.getBatchMsg().getHeader().getPacketSize(),4), this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_120.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_120.java new file mode 100644 index 0000000..ab84e8f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_120.java @@ -0,0 +1,386 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LGUFB_120 extends DefaultTelegram implements TelegramService +{ +// private Properties jobInfo; + private int REAL_BYTE; // 실 data byte수 + private String filename; + private File file; + private FileInputStream fin ; + private byte[] fileHeader; + private byte[] fileData; + + public SEND_LGUFB_120() { // 다른 전문과 달리 전문 번호가 없어 편의상 120번을 부여함 + } + + public boolean doExecute() { + try { + if (!setBlockAndSeqNO()) return false; + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, "", this.al_FieldProps[0]); + + //<< 전문 완성 + + return true; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPreExecute() { + if (!super.doPreExecute()) return false; + return true; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_BYTE; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + /** + * 여기서는 파일을 닫는다. + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + batchDoc.getBatchMsg().setTelegramHeader(new String((byte[])this.al_Field.get(0))); + batchDoc.getBatchMsg().setTelegramBody(new String(fileData)); + + if ( getConditionTxt().equals(TelegramKeys.EOF)){ + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(file); + + if ( fin != null ) { + fin.close(); + fin = null; + } + logger.info("{} doPostExecute called : file close", logHeader); + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + long totSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + if ( curSize != totSize ){ + logger.debug("[SEND_DAC25_120:doPostExecute]-->" + curSize + "/" + totSize ); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean setBlockAndSeqNO (){ + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } +// boolean isFirstRec = false; + + REAL_BYTE = 0; // data 버퍼에 현재까지 채워진 공간 + int bufferSize = batchDoc.getBatchMsg().getHeader().getPacketSize(); // data 버퍼의 크기 + fileData = new byte[bufferSize]; + // // 각 레코드의 크기 +// int newLineByteLen = 1; +// try { +// Properties jobInfo = getJobInfo(); +// newLineByteLen = Integer.parseInt(jobInfo.getProperty(TelegramKeys.MLINK_NEWLINE_LEN)); +// String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); +// if ( hdrInfo.substring(65, 67).equals("LL")){ +// newLineByteLen = Integer.parseInt(hdrInfo.substring(67, 68)); +// } +// } catch (Exception e) {} +// int recSize = batchDoc.getBatchMsg().getHeader().getRecLen(); +// byte[] recBuffer = new byte[recSize]; +// for (int inx = 0; inx < recBuffer.length; inx++) { +// recBuffer[inx] = ' '; +// } +// logger.debug("[SEND_DAC25_120]newLineByteLen-->" + newLineByteLen ); +// logger.debug("[SEND_DAC25_120]recSize-->" + recSize ); +// logger.debug("[SEND_DAC25_120]recBuffer.length-->" + recBuffer.length ); +// String fileLine = null; + + if (fileHeader != null ){ + int headerLen = fileHeader.length; + System.arraycopy( fileHeader, 0, fileData, 0, headerLen); + REAL_BYTE = headerLen; + + REAL_BYTE += fin.read(fileData, headerLen, fileData.length - headerLen ); +// file +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= REAL_BYTE; + batchDoc.getBatchMsg().setFileHeader(new String(fileHeader)); + fileHeader = null; +// isFirstRec = true; + }else{ + REAL_BYTE = fin.read(fileData); + +// byte[] sendSum = batchDoc.getBatchMsg().getBody().getSendBuffer(); +// if ( sendSum != null ){ +// System.arraycopy( sendSum, 0, fileData, 0, sendSum.length); +// REAL_BYTE = sendSum.length; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= REAL_BYTE; +// batchDoc.getBatchMsg().getBody().setSendBuffer(null); +// } + } +// while ( bufferSize > 0 ){ +// // 일단 한건 읽어 봅시다. +// fileLine = fbr.readLine(); +// if ( fileLine == null ){ // 읽은게 없으면 빠져 나가고 +// fbr.close(); // 다 읽었으면 포인터를 닫고 +// fbr = null; +// setConditionTxt(TelegramKeys.EOF); +// break; +// } +// +// System.arraycopy( fileLine.getBytes(), 0, recBuffer, 0, Math.min(recSize,fileLine.getBytes().length )); +// switch (newLineByteLen) { +// case 1: +// recBuffer[recSize-1] = '\n'; +// break; +// case 2: +// recBuffer[recSize-2] = '\r'; +// recBuffer[recSize-1] = '\n'; +// break; +// default: +// break; +// } +// +// if ( isFirstRec ){ +// String fileHeader = batchDoc.getBatchMsg().getFileHeader() + new String( recBuffer ); +// batchDoc.getBatchMsg().setFileHeader(fileHeader); +// isFirstRec = false; +// } +// // 한레코드 복사 +// +// if ( bufferSize >= recSize ){ // 남음 버퍼 크기가 레코드 한건 보다 크다면 +// System.arraycopy( recBuffer, 0, fileData, fileData.length - bufferSize, recSize); +// REAL_BYTE += recSize; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// bufferSize -= recSize; +// } else { +// System.arraycopy( recBuffer, 0, fileData, fileData.length - bufferSize, bufferSize); +// REAL_BYTE += bufferSize; +// logger.debug("[SEND_DAC25_120],REAL_BYTE-->" + REAL_BYTE); +// byte[] recBit = new byte[recSize-bufferSize]; +// System.arraycopy( recBuffer, bufferSize, recBit, 0, recSize-bufferSize ); +// batchDoc.getBatchMsg().getBody().setSendBuffer(recBit); +// bufferSize = 0; +// } +// } + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + if ( lnCurSize >= batchDoc.getBatchMsg().getHeader().getFileSize()){ + setConditionTxt(TelegramKeys.EOF); + batchDoc.getBatchMsg().setFileTrailer(new String(fileData)); + } + + return true; + + } catch (Exception ex) { + logger.error("{} ★★★★★ 송신 파일 데이터 READ 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + private boolean createFile() + { + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fin != null ) return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + int headerLen = TelegramKeys.MLINK_HEADER_LEN; + fileHeader = new byte[headerLen]; + for (int inx = 0; inx < headerLen - 2; inx++) { + fileHeader[inx] = ' '; + } + + // 헤더 구분 : <> + System.arraycopy( "<>".getBytes(), 0, fileHeader, 0, 10); + + // 업무 구분 : 1 + System.arraycopy( "1".getBytes(), 0, fileHeader, 10, 1); + + // 자료 형태 : 텍스트 파일(N), BINARY 파일(B), 압축데이타(C) + // # 자료형태 알수 없음 따라서 항상 N 으로 표시 + System.arraycopy( "N".getBytes(), 0, fileHeader, 11, 1); + + // 파일 크기 : BODY부분의 크기 + String strFileSize = makeZero( "" + ( batchDoc.getBatchMsg().getHeader().getFileSize() - TelegramKeys.MLINK_HEADER_LEN ), 10); + System.arraycopy( strFileSize.getBytes(), 0, fileHeader, 12, 10); + + // 압축후 파일크기 : 압축후의 BODY부분의 크기 + System.arraycopy( "0000000000".getBytes(), 0, fileHeader, 22, 10); + + String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + // 송신자 ID : 송신자의 ID + System.arraycopy( hdrInfo.getBytes(), 38, fileHeader, 32, 10); + + // 업체 구분: 송신자의 업체구분 코드 + // 정보 구분: BODY의 정보구분 코드 (문서명) + String infoGb = batchDoc.getBatchMsg().getHeader().getBizCode(); + System.arraycopy( infoGb.getBytes(), 0, fileHeader, 42, 5); + + // 예비 1 바이트 + //String reserve = " "; + //System.arraycopy( reserve.getBytes(), 0, fileHeader, 47, 1); + + // 수신자수 : BODY부분을 수신할 ec-Bank HiVAN ID의 수 + System.arraycopy( "001".getBytes(), 0, fileHeader, 48, 3); + + // 수신자 ID : + System.arraycopy( hdrInfo.getBytes(), 48, fileHeader, 51, 10); + // 레코드 구분자 : CR, LF + fileHeader[headerLen-2] = '\r'; + fileHeader[headerLen-1] = '\n'; + + //요구송신 파일 Start DB로그 + try { + LogUtil.setLogFileStart(batchDoc); + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + this.filename = fileDir+ File.separator + fileNm; + this.file = new File(this.filename); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File does not exist!!! ["+this.filename+"]", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID(),filename, fin ); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI021"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_130.java b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_130.java new file mode 100644 index 0000000..63c68f7 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/lgufb/SEND_LGUFB_130.java @@ -0,0 +1,163 @@ +package com.eactive.eai.batch.job.jobItem.lgufb; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class SEND_LGUFB_130 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_LGUFB_130() { + //수신확인 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, "", this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getRenamedFileName(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[6]); + + //처리여부 + if ( this.getResolveResponseCode().equals(TelegramKeys.MAGIC_RES_CODE_SUCESS)) { + compileField(7, "Y", this.al_FieldProps[7]); + } else { + compileField(7, "N", this.al_FieldProps[7]); + } + + //FILLER + compileField(8, "", this.al_FieldProps[8]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC.java b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC.java new file mode 100644 index 0000000..54b45b1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC.java @@ -0,0 +1,63 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.lang.String; + +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_NICEC extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : NICE 전문 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_NICEC() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(5); + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int recCnt = Integer.parseInt( super.getFieldValueString(0) ); + String bizCode = super.getFieldValueString(0).substring(3); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + int recLen = (int)jvo.getFileRecSize(); + return (recCnt * recLen ); + + } catch (Exception ex) { + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return -1; + } + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT01.java b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT01.java new file mode 100644 index 0000000..9fc2fd6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT01.java @@ -0,0 +1,183 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_NICEC_FT01 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 6; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_NICEC_FT01() { + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + +// //업무관리정보 유효성 확인 +// if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_restart)) { +// String bizCode = super.getFieldValueString(0).substring(3); +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); +// if ( jvo != null ){ +// batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); +// batchDoc.getBatchMsg().getHeader().setJobCode(jvo.getMsgDstCode()); +// } +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { +// } +// else if(this.getOpCode().equalsIgnoreCase(this.OpCode_teset)) { +// } +// else { +// logger.info("{} 0800 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); +// this.setResolveResponseCode("94"); +// +// String[] msgArgs = new String[2]; +// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); +// msgArgs[1] = this.getOpCode(); +// String errCode = "BECEAIFJI008"; +// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); +// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// +// } + return true; + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + // 로깅을 위해 + byte[] fieldData = new byte[length]; + System.arraycopy(data, 0, fieldData, 0, length); + this.al_Field.set( idx, fieldData); + + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String strRecCnt = new String((byte[])this.al_Field.get(2)).trim(); + String strRecLen = new String((byte[])this.al_Field.get(3)).trim(); + String strLen = new String((byte[])this.al_Field.get(5)).trim(); + long recCnt = Long.parseLong(strRecCnt); + int recLen = Integer.parseInt(strRecLen); + int fnameLen = Integer.parseInt(strLen); + String fName = new String(bout.toByteArray()).substring(0, fnameLen); +// //파일명으로 부터 거래 구분 코드 추출 +// int bizCodeStartIndex = 0; +// int bizCodeEndIndex = 0; +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); +// for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; +// if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); +// if (bizCodeEndIndex < 0 && 0 < fName.length() + bizCodeEndIndex ) bizCodeEndIndex = fName.length() + bizCodeEndIndex; +// String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); +// logger.debug("bizCodeStartIndex-->" + bizCodeStartIndex); +// logger.debug("bizCodeEndIndex-->" + bizCodeEndIndex); +// logger.debug("fName-->" + fName); +// logger.debug("fName.length()-->" + fName.length()); +// logger.debug("bizCode-->" + bizCode); +// batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + +// BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); +// +// String pattern = null; +// if ( bJobInfo!= null ){ +// pattern = bJobInfo.getSndrcvFileName(); +// } +// String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, true); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRecLen(recLen); + long fileSize = recCnt * recLen; + batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT02.java b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT02.java new file mode 100644 index 0000000..ac2aa2f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT02.java @@ -0,0 +1,273 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_NICEC_FT02 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 6; + private ByteArrayOutputStream bout; + private FileOutputStream fout; + /** + * 생성자 + */ + public RECV_NICEC_FT02() { + //DATA전문 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + + + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(new String((byte[])this.al_Field.get(5))); + + return writeToFile(); + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch (Exception ex) { + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return -1; + } + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean writeToFile(){ + if ( !createFile () ) + return false; + boolean isTrailer = false; + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + + byte[]layout = new byte[recLen]; + try { + int recCnt = Integer.parseInt( super.getFieldValueString(5) ); + long curCnt = batchDoc.getBatchMsg().getBody().getRecCnt(); + for (int jnx = 0; jnx < recCnt; jnx++) { + System.arraycopy( bout.toByteArray(), jnx*layout.length, layout,0,layout.length); + fout.write(layout); + fout.write( '\n' ); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+recLen; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if ( curCnt == 0 && jnx == 0 ){ + batchDoc.getBatchMsg().setFileHeader(new String(layout)); + LogUtil.setLogFileStart(batchDoc); + } + if (curCnt + jnx + 1 >= batchDoc.getBatchMsg().getHeader().getTotRecCnt() ){ + isTrailer = true; + } + } + batchDoc.getBatchMsg().getBody().setRecCnt(batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } catch (Exception e) { + logger.error( e.getMessage(), e); + return false; + }finally{ + try { + fout.close(); + } catch (Exception e2) { + logger.error( e2.getMessage(), e2); + } + } + + try { + if ( isTrailer ){ + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + batchDoc.getBatchMsg().setFileTrailer(new String(layout)); + + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + File file = new File(strFullPath); + File rcvArchFile = new File( StringUtil.realToArchDir(strFullPath) ); + File rcvRootFile = new File( StringUtil.realToRootDir(strFullPath) ); + + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + this.setResolveResponseCode("40"); + } + //수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(업무 서버에 자동 송신하도록 수신 File Event 발생)", logHeader); + if (!rcvRootFile.createNewFile()) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + this.setResolveResponseCode("40"); + } + LogUtil.setLogFileEnd(batchDoc); + } + } catch (Exception e) { + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + private boolean createFile () { + try { + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + fileName; + File file = new File(strFullPath); + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() > 0 ){ + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + }else{ + fout = new FileOutputStream(file, false); + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT03.java b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT03.java new file mode 100644 index 0000000..bbcb750 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT03.java @@ -0,0 +1,72 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_NICEC_FT03 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public RECV_NICEC_FT03() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + +// String strRecCnt = new String((byte[])this.al_Field.get(2)).trim(); +// long recCnt = Long.parseLong(strRecCnt); + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT09.java b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT09.java new file mode 100644 index 0000000..68c51e7 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT09.java @@ -0,0 +1,76 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_NICEC_FT09 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public RECV_NICEC_FT09() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + try { + Properties telegramInfo = getTelegramInfo(); + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME_POST)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(new String((byte[])this.al_Field.get(5))); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT12.java b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT12.java new file mode 100644 index 0000000..7c61a57 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT12.java @@ -0,0 +1,73 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_NICEC_FT12 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public RECV_NICEC_FT12() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + if ( batchDoc.getBatchMsg().getBody().getRecCnt() >= batchDoc.getBatchMsg().getHeader().getTotRecCnt() ){ + this.setConditionTxt(TelegramKeys.EOF); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT13.java b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT13.java new file mode 100644 index 0000000..de142e1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/RECV_NICEC_FT13.java @@ -0,0 +1,72 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_NICEC_FT13 extends DefaultTelegram implements TelegramService +{ + + + /** + * 생성자 + */ + public RECV_NICEC_FT13() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + +// String strRecCnt = new String((byte[])this.al_Field.get(2)).trim(); +// long recCnt = Long.parseLong(strRecCnt); + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT00.java b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT00.java new file mode 100644 index 0000000..d7e6d1b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT00.java @@ -0,0 +1,238 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_NICEC_FT00 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private String fileName; + + /** + * 생성자 + */ + public SEND_NICEC_FT00() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //기관코드 + compileField(1, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[1]); + + //레코드 수 + compileField(2, "", this.al_FieldProps[2]); + //compileField(2, "" + batchDoc.getBatchMsg().getHeader().getTotRecCnt(), this.al_FieldProps[2]); + + //레코드 크기 + compileField(3, "", this.al_FieldProps[3]); + //compileField(3, "" + batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //파일명 길이 + compileField(5, "" + fileName.getBytes().length, this.al_FieldProps[5]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + String getFileName = batchDoc.getBatchMsg().getHeader().getFileName(); + String yymmdd = TelegramKeys.getYYYYMMDD().substring(2); + if ( getFileName != null && getFileName.trim().length() >= 6 ){ + yymmdd = getFileName.trim().substring( getFileName.trim().length() - 6, getFileName.trim().length()); + } + fileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "." + yymmdd; + //batchDoc.getBatchMsg().getHeader().setFileName(fileName); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size() - 1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += fileName.getBytes().length; + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fileName.getBytes().length; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + System.arraycopy(fileName.getBytes(), 0, data, 0, fileName.getBytes().length); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT01.java b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT01.java new file mode 100644 index 0000000..a035ea5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT01.java @@ -0,0 +1,230 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_NICEC_FT01 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private String fileName; + + /** + * 생성자 + */ + public SEND_NICEC_FT01() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //기관코드 + compileField(1, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[1]); + + //레코드 수 + compileField(2, "" + batchDoc.getBatchMsg().getHeader().getTotRecCnt(), this.al_FieldProps[2]); + + //레코드 크기 + compileField(3, "" + batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //파일명 길이 + compileField(5, "" + fileName.getBytes().length, this.al_FieldProps[5]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size() - 1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += fileName.getBytes().length; + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fileName.getBytes().length; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + System.arraycopy(fileName.getBytes(), 0, data, 0, fileName.getBytes().length); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT02.java b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT02.java new file mode 100644 index 0000000..2453509 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT02.java @@ -0,0 +1,350 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_NICEC_FT02 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private File file; + private int REC_CNT; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_NICEC_FT02() { + //DATA전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = makeSendData(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //기관코드 + compileField(1, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[1]); + + //레코드 수 + compileField(2, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[2]); + + //레코드 크기 + compileField(3, "" + batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //파일명 길이 + compileField(5, makeZero( ""+ REC_CNT, ((byte[]) this.al_Field.get(5)).length), this.al_FieldProps[5]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + (REC_CNT*batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + // 로깅을 위해 +// byte[] fieldData = new byte[fldLen]; +// System.arraycopy(data, 0, fieldData, 0, fldLen); +// this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if ( file != null ){ // 처음 전송이면 + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(file); + + //요구송신 파일 Start DB로그 +// batchDoc.getBatchMsg().getHeader().setFileSize(file.length()); + LogUtil.setLogFileStart(batchDoc); + } + + long totalFileSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + long curFileSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + if ( curFileSize >= totalFileSize){ + LogUtil.setLogFileEnd(batchDoc); + } + batchDoc.getBatchMsg().getBody().setRecCnt(batchDoc.getBatchMsg().getBody().getRecCnt() + REC_CNT); + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(new String((byte[])this.al_Field.get(5))); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + + } + + private boolean createFile () + { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null ){ + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + } + return !( fin == null); + } + + private boolean makeSendData() + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + REC_CNT = seqCnt; + if ( remainCnt <= seqCnt ){ + REC_CNT = (int)remainCnt; + isLastSeq = true; + } + + REAL_BYTE = batchDoc.getBatchMsg().getHeader().getRecLen() * seqCnt; + + fileData = new byte[REAL_BYTE]; + for (int inx = 0; inx < fileData.length; inx++) { + fileData[inx] = ' '; + } + for ( int inx = 0 ; inx < REC_CNT ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + if ( isLastSeq ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT03.java b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT03.java new file mode 100644 index 0000000..7744057 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT03.java @@ -0,0 +1,152 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_NICEC_FT03 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_NICEC_FT03() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //기관코드 + compileField(1, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[1]); + + //레코드 수 + compileField(2, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[2]); + + //레코드 크기 + compileField(3, "" + batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT12.java b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT12.java new file mode 100644 index 0000000..b05460f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT12.java @@ -0,0 +1,152 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_NICEC_FT12 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_NICEC_FT12() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //기관코드 + compileField(1, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[1]); + + //레코드 수 + compileField(2, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[2]); + + //레코드 크기 + compileField(3, "" + batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT13.java b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT13.java new file mode 100644 index 0000000..82d0020 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/nice/SEND_NICEC_FT13.java @@ -0,0 +1,157 @@ +package com.eactive.eai.batch.job.jobItem.nice; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_NICEC_FT13 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_NICEC_FT13() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //기관코드 + compileField(1, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[1]); + + //레코드 수 + compileField(2, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[2]); + + //레코드 크기 + compileField(3, "" + batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[3]); + + //전문종별코드 - 전문의 기능을 나타내는 4Bytes 코드로 구성 + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME_POST)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(""); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0600_0001.java b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0600_0001.java new file mode 100644 index 0000000..1450061 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0600_0001.java @@ -0,0 +1,401 @@ +package com.eactive.eai.batch.job.jobItem.pension; + +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; + +public class RECV_T0600_0001 extends DefaultTelegram implements TelegramService +{ +// private final int IDX_FILENAME = 20; + private String strFullPathName = ""; + private FileOutputStream fout = null; + + private File rcvRealFile = null; + private File rcvArchFile = null; + private File rcvErrorFile = null; +// private String rcvEnc =""; + + public RECV_T0600_0001() { + } + + //============================================================================================================================ + // 호출순서 : doPreExecute() -> getCalculatedLength() -> doInformalField() -> doExecute() -> doValidation() -> doPostExecute() + //============================================================================================================================ + + /** + * doPreExecute() 부모클래스의 기본 수행을 호출해 준 후, 0600 전문 수신의 특이 사항을 수행한다. + * 0600 전문의 특이사항은 실질적인 파일 수신시 Write할 파일을 열어주는 것이다. (FileOutputStream) + */ + public boolean doPreExecute() + { + if (!super.doPreExecute()) return false; +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String instituteCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// OutsideVO osd = OutsideManager.getInstance().getOutsideInfo(processCode, instituteCode ); +// rcvEnc = osd.getRecvEnc(); +// if ( rcvEnc == null ) { +// rcvEnc = ""; +// } + + return true; + } + + public boolean doPreExecuteAfterCopy() + { + if (!super.doPreExecuteAfterCopy()) return false; + + //1. 파일명 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '파일명' 전문필드 값 Checking......", logHeader); + String sendInstCode = new String((byte[])al_Field.get( 5)).trim(); //송신기관코드 + String recvInstCode = new String((byte[])al_Field.get( 7)).trim(); //수신기관코드 + String bizCode = new String((byte[])al_Field.get( 9)).trim(); //거래구분코드 + String sendDate = new String((byte[])al_Field.get(13)).trim(); //전문전송일 +// String issueDate = new String((byte[])al_Field.get(17)).trim(); //거래발생일 + String fileName = new String((byte[])al_Field.get(20)).trim(); //파일명 + + batchDoc.getBatchMsg().getHeader().setFileName(fileName); //배치메시지에 파일명 설정 + + String fileSendInstCode = fileName.substring( 0, 4); //송신기관코드 + String fileRecvInstCode = fileName.substring( 4, 8); //수신기관코드 + String fileBizCode = fileName.substring( 8, 15); //거래구분코드 + String fileSendDate = fileName.substring(15, 23); //전문전송일 +// String fileIssueDate = fileName.substring(23, 31); //거래발생일 + String fileSeq = fileName.substring(31); //파일전송회차 + + + if (!fileSendInstCode.equals(sendInstCode)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR009", new String[] {fileName, "송신기관코드", fileSendInstCode, "송신기관코드", sendInstCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 파일명 필드 값 '{1}' 의 {2} 부분 값 '{3}'이 수신전문의 {4} 필드 값 '{5}'과 일치하지 않습니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FILENAME_ERROR); + return false; + } + if (!fileRecvInstCode.equals(recvInstCode)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR009", new String[] {fileName, "수신기관코드", fileRecvInstCode, "수신기관코드", recvInstCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 파일명 필드 값 '{1}' 의 {2} 부분 값 '{3}'이 수신전문의 {4} 필드 값 '{5}'과 일치하지 않습니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FILENAME_ERROR); + return false; + } + if (!fileBizCode.equals(bizCode)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR009", new String[] {fileName, "거래구분코드", fileBizCode, "거래구분코드", bizCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 파일명 필드 값 '{1}' 의 {2} 부분 값 '{3}'이 수신전문의 {4} 필드 값 '{5}'과 일치하지 않습니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FILENAME_ERROR); + return false; + } + if (!fileSendDate.equals(sendDate)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR009", new String[] {fileName, "전문전송일", fileSendDate, "전문전송일", sendDate}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 파일명 필드 값 '{1}' 의 {2} 부분 값 '{3}'이 수신전문의 {4} 필드 값 '{5}'과 일치하지 않습니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FILENAME_ERROR); + return false; + } +// if (!fileIssueDate.equals(issueDate)) { +// String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR009", new String[] {fileName, "거래발생일", fileIssueDate, "거래발생일", issueDate}); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 파일명 필드 값 '{1}' 의 {2} 부분 값 '{3}'이 수신전문의 {4} 필드 값 '{5}'과 일치하지 않습니다. +// super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FILENAME_ERROR); +// return false; +// } + if (!StringUtil.isNumeric(fileSeq) || fileSeq.equals("0000")) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR010", new String[] {fileName, "파일전송회차", fileSeq}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 파일명 필드 값 '{1}' 의 {2} 부분 값 '{3}'이 '0001' 과 같거나 커야 합니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FILENAME_ERROR); + return false; + } + + + + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String organCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + + //2. 수신파일 저장 경로 설정 + //저장 디렉토리는 Inbound Server 에서 설정됨 (응답수신 Real 또는 응답송신 Real) + this.strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath(); + String dirDelimiter = StringUtil.getDirDelimiter(this.strFullPathName); + if (!this.strFullPathName.endsWith(dirDelimiter)) this.strFullPathName += dirDelimiter; + + + //3. 거래구분코드에 대한 작업구분코드 설정 + BatchJobInfoVO jobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + logger.info("{} 거래구분코드 : ["+ bizCode +"]", logHeader); + if (jobInfo == null) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI040", new String[] {fileName, processCode, bizCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일 [{1}] 에 해당하는 JOB_CODE를 찾을수 없습니다. [ProcessCode: {2}] [BizCode: {3}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + logger.info("{} 작업구분코드 : ["+ jobInfo.getMsgDstCode() +"]", logHeader); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + batchDoc.getBatchMsg().getHeader().setJobCode(jobInfo.getMsgDstCode()); + batchDoc.getBatchMsg().getHeader().setRecLen((int)jobInfo.getFileRecSize()); + + + + this.strFullPathName += fileName; + logger.info("{} 응답수신 파일 저장 경로 : [" + this.strFullPathName + "]", logHeader); + rcvRealFile = new File( this.strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리 + try { + rcvArchFile = new File( StringUtil.replaceStr(this.strFullPathName, BatchDirUtil.getResponseRealDir(), BatchDirUtil.getResponseArchDir()) ); + rcvErrorFile = new File( StringUtil.replaceStr(this.strFullPathName, BatchDirUtil.getResponseRealDir(), BatchDirUtil.getResponseErrorDir()) ); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + + + //5. 해당 파일 전송중 여부 체크 + logger.info("{} >>>>> 수신 전문의 '파일명' 전송중 여부 Checking......", logHeader); + if (rcvRealFile.exists()) { +// String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI037", new String[] {rcvRealFile.getAbsolutePath()}); +// batchDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); //해당 파일을 다른 일괄전송 작업에서 수신 중입니다. - 수신파일명[{1}] +// super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_UNCOMPLETED_ERROR); //파일전송미완료 +// return false; + } + + //6. 해당 파일 기수신완료 여부 체크 + logger.info("{} >>>>> 수신 전문의 '파일명' 기수신완료 여부 Checking......", logHeader); + if (rcvArchFile.exists()) { + //파일사이즈 비교 체크는 요건이 있을때 해줌. + //long rcvRealFileSize = rcvRealFile.length(); + //long rcvArchFileSize = rcvArchFile.length(); + //if (rcvRealFileSize == rcvArchFileSize) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI032", new String[] {rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일이 이미 존재합니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_ALREADY_RECEIVED); //기수신완료 + return false; + //} + } + + + //7. 응답수신 파일 생성 + logger.info("{} >>>>> 응답수신 파일 생성...... ("+ this.strFullPathName +")", logHeader); + try { + fout = new FileOutputStream(rcvRealFile); + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 생성 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI041", new String[] {rcvRealFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 해당 경로에 생성시 오류가 발생하였습니다. [Path : {1}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); //기타오류 + return false; + } + + + //8. 응답수신 파일 Start DB로그 + logger.info("{} >>>>> 응답수신 파일 Start DB로그......", logHeader); + try { + LogUtil.setLogFileStart(batchDoc); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 응답수신 파일 Start DB로그 수행시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI021", new String[] {processCode}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); //기타오류 + return false; + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + try { + int nDefiniteLength = 0; + //퇴직연금에서는 마지막에 define 되어 있는 것으로 한다. + for (int i=0; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + nDefiniteLength += aField.length; + } + logger.info("{} INFORMAL 필드 이전에 읽어들인 Byte Length : [" + nDefiniteLength + "]", logHeader); + + String strLength = super.getFieldValueString(batchDoc.getBatchMsg().getPhaseinfo().getLengthFieldIndex()-1); + logger.info("{} HEADER 의 '전문길이' 필드 값 : [" + nDefiniteLength + "]", logHeader); + + int nTotalLength = Integer.parseInt(strLength); + batchDoc.getBatchMsg().getHeader().setFileSize(nTotalLength - nDefiniteLength); //파일사이즈 설정 (전송 진행상태 확인용) + logger.info("{} INFORMAL 필드에서 읽어들일 Byte Length : [" + (nTotalLength - nDefiniteLength) + "]", logHeader); + return (nTotalLength - nDefiniteLength); + + } catch (Exception ex) { + logger.error("{} ★★★★★ 수신 파일 사이즈 계산 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + //파일 끝에 append + fout.write(data, 0, length); + + //읽어 들인 파일 사이즈 저장 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + length; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch (Exception ex) { + logger.error("{} ★★★★★ 수신 파일 데이터 WRITE 시 오류 발생 !! ★★★★★", logHeader, ex); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString()); + return false; + } + } + + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //1. 수신 파일 Close =========================================================== + if (fout != null) fout.close(); +// if ( !rcvEnc.trim().equals("") ) { + // 파일 복호화 +// XecureManager.getInstance().decryptFile( rcvEnc, strFullPathName+".enc", strFullPathName ); + +// } + + //2. 수신 파일 End DB로그 ====================================================== + //수신 파일 (Real 디렉토리) + if (rcvRealFile.exists()) { + //DB로그에 남길 파일 사이즈 설정 + batchDoc.getBatchMsg().getHeader().setFileSize(rcvRealFile.length()); + try { + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(rcvRealFile.length()/recLen); + } catch (Exception e) { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + } + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + } + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + + //File 종료시간 설정 + batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) ) { + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + + //4. 자료구분 필드 값 체크 (Real 일때만 퇴직연금 서버로 파일 전송) + logger.info("{} >>>>> 수신 전문의 '자료구분' 전문필드 값 Checking......", logHeader); + String fileRealTestType = new String((byte[])al_Field.get(3)); //자료구분 + logger.info("{} >>>>> 자료구분 필드 값: ["+ fileRealTestType +"]", logHeader); + +// boolean _SYSTEMTEST = ( EAIServerManager.getInstance().isTEAIServer() || EAIServerManager.getInstance().isDEAIServer() ); +// if (fileRealTestType.equals(TelegramKeys.RPS_HBD_DAT_GBN_PASS) +// || ( _SYSTEMTEST && fileRealTestType.equals(TelegramKeys.RPS_HBD_DAT_GBN_TEST) ) +// || ( !_SYSTEMTEST && fileRealTestType.equals(TelegramKeys.RPS_HBD_DAT_GBN_REAL) ) +// ) { //R (Real): 실데이터 + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(퇴직연금 서버에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPathName) ); + rcvRootFile.createNewFile(); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPathName) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + +// } else { +// logger.info("{} >>>>> 자료구분 필드 값이 'R' (Real) 이 아님. Root 디렉토리에 0 Byte 파일 생성 안함. (퇴직연금 서버에 수신 파일을 송신하지 않음)", logHeader); +// //오류처리 하지 않고 로그 메시지만 남긴다. +// String errMsg = ExceptionUtil.getErrorCode("BICEAIFJI001", new String[] { fileRealTestType }); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //자료구분 필드 값 '{1}' 이 'R' (Real) 이 아님. Root 디렉토리에 0 Byte 파일 생성 안함. (퇴직연금 서버에 수신 파일을 송신하지 않음) +// } + + return true; + + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(8); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(9); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0610_0001.java b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0610_0001.java new file mode 100644 index 0000000..f595cef --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0610_0001.java @@ -0,0 +1,71 @@ +package com.eactive.eai.batch.job.jobItem.pension; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; + + +public class RECV_T0610_0001 extends DefaultTelegram implements TelegramService +{ + public RECV_T0610_0001() { + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //요구전문의 응답전문에 대한 Validation 실패시 요구송신 Process 종료 (return false) + //(전문헤더 Validation은 RECV_T_RTMPS 클래스에서 수행되어 응답코드가 설정됨) + if (!super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) return false; + + return true; + } + + /** + * doPostExecute + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + ///////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////// + logger.info("{} doPostExecute called : 파일전송 성공 ", logHeader); + // File Open LOG + LogUtil.setLogFileEnd(batchDoc); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(8); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(9); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0800_0001.java b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0800_0001.java new file mode 100644 index 0000000..efe140b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0800_0001.java @@ -0,0 +1,135 @@ +package com.eactive.eai.batch.job.jobItem.pension; + +import com.eactive.eai.batch.flowController.DemandTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import java.lang.String; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +/** + * 퇴직연금용 0800 전문 수신용 텔레그램 클래스 + */ +public class RECV_T0800_0001 extends DefaultTelegram implements TelegramService +{ + //>> 거래구분코드 정의 + // 업무개시 + private final String TrClass_start = "0000100"; + private final String TrClass_end = "0000200"; + private final String TrClass_linecheck = "0000300"; + private final String TrClass_errnotify = "0000400"; + private final String TrClass_oknotify = "0000500"; + + /** + * 생성자 + */ + public RECV_T0800_0001() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + //거래구분코드 체크 + String bizCode = this.getTrClass(); + if (bizCode.equalsIgnoreCase(this.TrClass_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + + } else if(bizCode.equalsIgnoreCase(this.TrClass_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + + } else if(bizCode.equalsIgnoreCase(this.TrClass_linecheck)) { + logger.info("{} BATCH JOB : 회선상태 확인 전문 수신 ", logHeader); + + } else if(bizCode.equalsIgnoreCase(this.TrClass_errnotify)) { + logger.info("{} BATCH JOB : 대외기관시스템 장애 통보 수신", logHeader); + + } else if(bizCode.equalsIgnoreCase(this.TrClass_oknotify)) { + logger.info("{} BATCH JOB : 대외기관시스템 장애회복 통보 수신", logHeader); + + } else { + logger.info("{} 0800 telegram : unknown trasaction classification code received >> "+this.getTrClass(), logHeader); + } + + //회선장애통보, 회선장애회복통보 처리 + if ("0000400,0000500".indexOf(this.getTrClass()) >= 0) { + logger.info("{} >>>>> 퇴직연금 "+ (this.getTrClass().equals("0000400")? "회선장애통보" : "회선장애회복통보") +" 전문에 의한 회선 장애 상태 Updating...", logHeader); + try { + //시스템연결정보 테이블 (TSEAIBJ05) 회선 상태를 update 한다. + FlowControllerManager.getInstance().updateSystemConnLineStatus( + batchDoc.getBatchMsg().getHeader().getProcessCode(), + batchDoc.getBatchMsg().getHeader().getInstitutionCode(), + this.getTrClass().equals("0000400")? DemandTargetVO.ORGAN_SOCKET_STATUS_ERROR : DemandTargetVO.ORGAN_SOCKET_STATUS_NORNAL); //0000400:장애, 0000500:회복 + + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI033", new String[] { batchDoc.getBatchMsg().getHeader().getProcessCode() }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + } + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //0800 전문에서 받은 파일명으로는 기수신여부를 체크하지 않는다. + + return true; + } + + /** + * doPostExecute + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + ///////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////// + logger.info("{} doPostExecute called", logHeader); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 수신길이 계산 + */ + public int getCalculatedLength(int idx) { + logger.info("{} getCalculatedLength unexpectedly called : idx = " + idx, logHeader); + return 0; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(8); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(9); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0810_0001.java b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0810_0001.java new file mode 100644 index 0000000..b07b0ca --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T0810_0001.java @@ -0,0 +1,109 @@ +package com.eactive.eai.batch.job.jobItem.pension; + +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_T0810_0001 extends DefaultTelegram implements TelegramService +{ + //>> 거래구분코드 정의 + // 업무개시 + private final String TrClass_start = "0000100"; + private final String TrClass_end = "0000200"; + private final String TrClass_linecheck = "0000300"; + private final String TrClass_errnotify = "0000400"; + private final String TrClass_oknotify = "0000500"; + + /** + * 생성자 + */ + public RECV_T0810_0001() { + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + if (this.getTrClass().equalsIgnoreCase(this.TrClass_start)) { + logger.info("{} BATCH JOB : START request received", logHeader); + } else if (this.getTrClass().equalsIgnoreCase(this.TrClass_end)) { + logger.info("{} BATCH JOB : END request received", logHeader); + } else if (this.getTrClass().equalsIgnoreCase(this.TrClass_linecheck)) { + logger.info("{} BATCH JOB : LINE_CHECK request received", logHeader); + } else if (this.getTrClass().equalsIgnoreCase(this.TrClass_errnotify)) { + logger.info("{} BATCH JOB : ERROR_NOTIFY request received", logHeader); + } else if (this.getTrClass().equalsIgnoreCase(this.TrClass_oknotify)) { + logger.info("{} BATCH JOB : OK_NOTIFY request received", logHeader); + } else { + logger.info("{} 0810 telegram : unknown trasaction classification code received >> "+this.getTrClass(), logHeader); + String errMsg = ExceptionUtil.getErrorCode ("BECEAIFJI015", new String[] { this.batchDoc.getBatchMsg().getHeader().getProcessCode(), this.getTrClass() }); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + + // 응답코드에 대한 처리는 RULE 로 처리됨. + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //요구전문의 응답전문에 대한 Validation 실패시 요구송신 Process 종료 (return false) + //(전문헤더 Validation은 RECV_T_RTMPS 클래스에서 수행되어 응답코드가 설정됨) + if (!super.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) return false; + + return true; + } + + /** + * doPostExecute + */ + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + ///////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////// + logger.info("{} doPostExecute called", logHeader); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 수신길이 계산 + */ + public int getCalculatedLength(int idx) { + logger.info("{} getCalculatedLength unexpectedly called : idx = " + idx, logHeader); + return 0; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(8); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(9); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T_RTMPS.java b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T_RTMPS.java new file mode 100644 index 0000000..ae6b639 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/pension/RECV_T_RTMPS.java @@ -0,0 +1,256 @@ +package com.eactive.eai.batch.job.jobItem.pension; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; + +public class RECV_T_RTMPS extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : 퇴직연금용 길이결정용 텔레그램 클래스 이다. + */ + public RECV_T_RTMPS() { + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //1. 퇴직연금 수신 전문의 전문필드 개수 체크 + logger.info("{} >>>>> 수신 전문의 전문필드 개수 Checking......", logHeader); + if (al_FieldProps == null || al_Field == null || al_FieldProps.length != al_Field.size()) { + String errMsg = "전문필드 값 Validation 체크를 위한 데이터 불량."; + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FORMAT_ERROR); + return false; + } + + //2. 퇴직연금 수신 전문의 전체 전문필드 타입 체크 + logger.info("{} >>>>> 수신 전문의 전체 전문필드 타입 Checking......", logHeader); + for(int i=0; i>>>> 수신 전문의 'SYSTEM_ID' 전문필드 값 Checking......", logHeader); +// currFiledIndex = 1; +// currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); +// if (!currFieldValue.equals(TelegramKeys.RPS_SYSTEM_ID)) { +// String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR006", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, TelegramKeys.RPS_SYSTEM_ID}); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 이 아닙니다. +// super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FORMAT_ERROR); +// return false; +// } + + //3-2. 자료구분 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '자료구분' 전문필드 값 Checking......", logHeader); + currFiledIndex = 3; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + /* + if (!currFieldValue.equals(TelegramKeys.RPS_HBD_DAT_GBN_TEST) && + !currFieldValue.equals(TelegramKeys.RPS_HBD_DAT_GBN_REAL) && + !currFieldValue.equals(TelegramKeys.RPS_HBD_DAT_GBN_PASS)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR007", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, "T,R,B"}); + batchDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 값들 중 하나이어야 합니다. + super.setResolveResponseCode(TelegramKeys.BAN_RET_CODE_DATAGBN_ERROR); + return false; + */ +// boolean _SYSTEMTEST = ( EAIServerManager.getInstance().isTEAIServer() || EAIServerManager.getInstance().isDEAIServer() ); +// if(_SYSTEMTEST){ +// if( (!currFieldValue.equals(TelegramKeys.RPS_HBD_DAT_GBN_PASS) ) && +// (!currFieldValue.equals(TelegramKeys.RPS_HBD_DAT_GBN_TEST) ) ){ +// logger.error("RECV_T_RTMPS ] getSendResponseCode - 자료구분(T:TEST/R:REAL/P:PASS) : ["+currFieldValue+"]"); +// String errMsg = ExceptionUtil.getErrorCode("BICEAIFJI001", new String[] {currFieldValue}); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); +// return false; +// } +// } +// else { +// if( (!currFieldValue.equals(TelegramKeys.RPS_HBD_DAT_GBN_PASS) ) && +// (!currFieldValue.equals(TelegramKeys.RPS_HBD_DAT_GBN_REAL) ) ){ +// logger.error("RECV_T_RTMPS ] getSendResponseCode - 자료구분(T:TEST/R:REAL/P:PASS) : ["+currFieldValue+"]"); +// String errMsg = ExceptionUtil.getErrorCode("BICEAIFJI001", new String[] {currFieldValue}); +// batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); +// super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); +// return false; +// } +// } + + /* + //3-3. 송신기관구분코드 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '송신기관구분코드' 전문필드 값 Checking......", logHeader); + currFiledIndex = 4; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(batchDoc.getEAIBatchMessage().getHeader().getInstituaionType())) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR006", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, batchDoc.getEAIBatchMessage().getHeader().getInstituaionType()}); + batchDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 이 아닙니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_CODE_ERROR); + return false; + } + */ + + //3-4. 송신기관코드 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '송신기관코드' 전문필드 값 Checking......", logHeader); + currFiledIndex = 5; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(batchDoc.getBatchMsg().getHeader().getInstitutionCode())) { + //String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR006", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode()}); + //batchDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 이 아닙니다. + //super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_CODE_ERROR); + //return false; + } + + /* + //3-5. 수신기관구분코드 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '수신기관구분코드' 전문필드 값 Checking......", logHeader); + currFiledIndex = 6; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.RPS_HBD_RSV_CLS_JASAN)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR006", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, TelegramKeys.RPS_HBD_RSV_CLS_JASAN}); + batchDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 이 아닙니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_CODE_ERROR); + return false; + } + */ + + //3-6. 수신기관코드 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '수신기관코드' 전문필드 값 Checking......", logHeader); + currFiledIndex = 7; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); +// if (!currFieldValue.equals(TelegramKeys.RPS_HBD_SND_ID_KB)) { +// //String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR006", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, TelegramKeys.RPS_HBD_SND_ID_KB}); +// //batchDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 이 아닙니다. +// //super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_CODE_ERROR); +// //return false; +// } + + //3-7. 송수신FLAG 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '송수신FLAG' 전문필드 값 Checking......", logHeader); + currFiledIndex = 10; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.RPS_HDB_TRA_FLAG_CLIENT) && + !currFieldValue.equals(TelegramKeys.RPS_HDB_TRA_FLAG_SERVER)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR007", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, "1,2"}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 값들 중 하나이어야 합니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FORMAT_ERROR); + return false; + } + + //3-8. 전문전송일 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '전문전송일' 전문필드 값 Checking......", logHeader); + currFiledIndex = 13; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!DatetimeUtil.isDateValue(currFieldValue)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR008", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 의 형식이 잘못되었습니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FORMAT_ERROR); + return false; + } + + //3-9. 전문전송시간 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '전문전송시간' 전문필드 값 Checking......", logHeader); + currFiledIndex = 14; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!DatetimeUtil.isTimeValue(currFieldValue)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR008", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 의 형식이 잘못되었습니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FORMAT_ERROR); + return false; + } + + //3-10. 거래발생일 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '거래발생일' 전문필드 값 Checking......", logHeader); + currFiledIndex = 17; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!DatetimeUtil.isDateValue(currFieldValue)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR008", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 의 형식이 잘못되었습니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_FORMAT_ERROR); + return false; + } + + //3-11. 응답코드 필드 값 체크 + logger.info("{} >>>>> 수신 전문의 '응답코드' 전문필드 값 Checking......", logHeader); + currFiledIndex = 12; + currFieldValue = new String((byte[])al_Field.get(currFiledIndex)); + if (!currFieldValue.equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR034", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, TelegramKeys.getName_RPS_HDB_RET_CODE(currFieldValue) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 입니다. 거래를 종료합니다. + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(8); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(9); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(12); + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=2; i> 파일헤더 및 내용, 트레일러 만들기 + //<< 최종 길이 셋팅 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + return false; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + int nSumFormalField = 0; + for (int i=0; i hm_job = JobProcessData.getInstance().getBatchStageData(strUUID); + TelegramService prevTelegram = (TelegramService)hm_job.get(JobProcessData.PROCDATA_PRE_TELEGRAM); + if (prevTelegram == null) { + logger.debug("{} not found previous telegram instance : needed in compiling of response telegram", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI035"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // + compileField(0, new String(prevTelegram.getFieldDataByIndex(0)), this.al_FieldProps[0]); + compileField(1, new String(prevTelegram.getFieldDataByIndex(1)), this.al_FieldProps[1]); + long lnLength = this.getSendLength(); + compileField(2, String.valueOf(lnLength), this.al_FieldProps[2]); + // 자료구분 (HDB_DAT_GBN), 실테스트시에는 이 부분을 real로 바꿔야 한다. + compileField(3, new String(prevTelegram.getFieldDataByIndex(3)), this.al_FieldProps[3]); + // 송신기관 구분 (HDB_SND_CLS) : 1:운영, 2:기록, 3:자산, 4:상품, 5:자산운영 + compileField(4, telegramInfo.getProperty(TelegramKeys.HDB_SND_CLS), this.al_FieldProps[4]); + // 송신기관 코드 (HDB_SND_ID) + compileField(5, telegramInfo.getProperty(TelegramKeys.HDB_SND_ID), this.al_FieldProps[5]); + // 수신기관 구분 (HDB_RCV_CLS) + compileField(6, telegramInfo.getProperty(TelegramKeys.HDB_RCV_CLS), this.al_FieldProps[6]); + // 수신기관 코드 (HDB_RSV_ID) + compileField(7, batchDoc.getBatchMsg().getHeader().getInstitutionCode(), this.al_FieldProps[7]); + // 전문종별코드 : 실시간 DB 결정 + compileField(8, this.getFldTelegramType(), this.al_FieldProps[8]); + // 거래구분코드 : 실시간 DB 결정 : 0610 전문의 이전 전문을 복사해서 사용 + compileField(9, new String(prevTelegram.getFieldDataByIndex(9)), this.al_FieldProps[9]); + // 송수신 Flag : 이경우는 수신받는 경우이다. + compileField(10,TelegramKeys.RPS_HDB_TRA_FLAG_SERVER, this.al_FieldProps[10]); + // STATUS : 사용안함 + compileField(11, "000", this.al_FieldProps[11]); + // 응답코드 : --> 정상처리해도 되는지 판단 : + compileField(12, super.getSendResponseCode(), this.al_FieldProps[12]); + // 전문전송일 + compileField(13, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[13]); + // 전문전송시간 + compileField(14, TelegramKeys.getHHMMSS(), this.al_FieldProps[14]); + // 송신기관전문번호, 8자리 : 이전전문에서 복사 + compileField(15, new String(prevTelegram.getFieldDataByIndex(15)), this.al_FieldProps[15]); + // 수신기관전문번호 + // compileField(16, TelegramKeys.getRecvSequence(this.getFldTelegramType()), this.al_FieldProps[16]); + compileField(16, "10000001", this.al_FieldProps[16]); + // 거래발생일, 실 자료의 거래 발생일, 실 파일의 19번째부터 8자리를 읽어야 한다. + compileField(17, new String(prevTelegram.getFieldDataByIndex(17)), this.al_FieldProps[17]); + // 전체파일수 : 사용안함 + compileField(18, new String(prevTelegram.getFieldDataByIndex(18)), this.al_FieldProps[18]); + // 현재파일순번 : 사용안함 + compileField(19, new String(prevTelegram.getFieldDataByIndex(19)), this.al_FieldProps[19]); + // 현재 파일명 + compileField(20, new String(prevTelegram.getFieldDataByIndex(20)), this.al_FieldProps[20]); + // 현재 파일 전체 전문 수 : 사용안함 + compileField(21, new String(prevTelegram.getFieldDataByIndex(21)), this.al_FieldProps[21]); + // 현재 파일 현재 순번 + compileField(22, new String(prevTelegram.getFieldDataByIndex(22)), this.al_FieldProps[22]); + // 전문 CASE 명 + compileField(23, new String(prevTelegram.getFieldDataByIndex(23)), this.al_FieldProps[23]); + // 송신추가정의 + compileField(24, TelegramKeys.RPS_HDB_SND_EXT, this.al_FieldProps[24]); + // 송신추가정의 + compileField(25, TelegramKeys.RPS_HDB_RSV_EXT, this.al_FieldProps[25]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + return false; + } + + /** + * 0610 전문 처리 --> 이전문은 실질 응답 전문이다. 따라서.. 대부분의 값은 복사해서 사용하고 + * 응답 코드만 잘 처리해주면 된다. + */ + public String getSendResponseCode() + { + return TelegramKeys.RPS_HDB_RET_CODE_SUCCESS; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() { + int nSumFormalField = 0; + for (int i=0; i hm_job = JobProcessData.getInstance().getBatchStageData(strUUID); + TelegramService prevTelegram = (TelegramService)hm_job.get(JobProcessData.PROCDATA_PRE_TELEGRAM); + if (prevTelegram == null) { + logger.debug("{} not found previous telegram instance : needed in compiling of response telegram", logHeader); + + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIJI035"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + + // + compileField(0, new String(prevTelegram.getFieldDataByIndex(0)), this.al_FieldProps[0]); + compileField(1, new String(prevTelegram.getFieldDataByIndex(1)), this.al_FieldProps[1]); + long lnLength = this.getSendLength(); + compileField(2, String.valueOf(lnLength), this.al_FieldProps[2]); + // 자료구분 (HDB_DAT_GBN), 실테스트시에는 이 부분을 real로 바꿔야 한다. + compileField(3, new String(prevTelegram.getFieldDataByIndex(3)), this.al_FieldProps[3]); + // 송신기관 구분 (HDB_SND_CLS) : 1:운영, 2:기록, 3:자산, 4:상품, 5:자산운영 + compileField(4, telegramInfo.getProperty(TelegramKeys.HDB_SND_CLS), this.al_FieldProps[4]); + // 송신기관 코드 (HDB_SND_ID) + compileField(5, telegramInfo.getProperty(TelegramKeys.HDB_SND_ID), this.al_FieldProps[5]); + // 수신기관 구분 (HDB_RCV_CLS) + compileField(6, telegramInfo.getProperty(TelegramKeys.HDB_RCV_CLS), this.al_FieldProps[6]); + // 수신기관 코드 (HDB_RSV_ID) + compileField(7, batchDoc.getBatchMsg().getHeader().getInstitutionCode(), this.al_FieldProps[7]); + // 전문종별코드 : 실시간 DB 결정 + compileField(8, this.getFldTelegramType(), this.al_FieldProps[8]); + // 거래구분코드 : 실시간 DB 결정 + compileField(9, this.getFldTrClass(), this.al_FieldProps[9]); + // 송수신 Flag : 이경우는 수신받는 경우이다. + compileField(10,TelegramKeys.RPS_HDB_TRA_FLAG_SERVER, this.al_FieldProps[10]); + // STATUS : 사용안함 + compileField(11, "000", this.al_FieldProps[11]); + // 응답코드 : --> 정상처리해도 되는지 판단 : 20060406 + compileField(12, super.getSendResponseCode(), this.al_FieldProps[12]); + // 전문전송일 + compileField(13, TelegramKeys.getYYYYMMDD(), this.al_FieldProps[13]); + // 전문전송시간 + compileField(14, TelegramKeys.getHHMMSS(), this.al_FieldProps[14]); + // 송신기관전문번호, 8자리 : 이전전문에서 복사 + compileField(15, new String(prevTelegram.getFieldDataByIndex(15)), this.al_FieldProps[15]); + // 수신기관전문번호 + // compileField(16, TelegramKeys.getRecvSequence(this.getFldTelegramType()), this.al_FieldProps[16]); + compileField(16, "10000001", this.al_FieldProps[16]); + // 거래발생일, 실 자료의 거래 발생일, 실 파일의 19번째부터 8자리를 읽어야 한다. + compileField(17, new String(prevTelegram.getFieldDataByIndex(17)), this.al_FieldProps[17]); + // 전체파일수 : 사용안함 + compileField(18, new String(prevTelegram.getFieldDataByIndex(18)), this.al_FieldProps[18]); + // 현재파일순번 : 사용안함 + compileField(19, new String(prevTelegram.getFieldDataByIndex(19)), this.al_FieldProps[19]); + // 현재 파일명 + compileField(20, new String(prevTelegram.getFieldDataByIndex(20)), this.al_FieldProps[20]); + // 현재 파일 전체 전문 수 : 사용안함 + compileField(21, new String(prevTelegram.getFieldDataByIndex(21)), this.al_FieldProps[21]); + // 현재 파일 현재 순번 + compileField(22, new String(prevTelegram.getFieldDataByIndex(22)), this.al_FieldProps[22]); + // 전문 CASE 명 + compileField(23, new String(prevTelegram.getFieldDataByIndex(23)), this.al_FieldProps[23]); + // 송신추가정의 + compileField(24, TelegramKeys.RPS_HDB_SND_EXT, this.al_FieldProps[24]); + // 송신추가정의 + compileField(25, TelegramKeys.RPS_HDB_RSV_EXT, this.al_FieldProps[25]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + //Logging(DEBUG, ExceptionUtil.getErrorCode(e, "doExecute error")); + } + return false; + } + + /** + * 기본 구현은 DefaultTelegram 클래스에서 수행한다. "000"을 리턴하도록... + */ + public String getSendResponseCode() + { + // 정상, 기수신완료, Format 오류, 기관코드 오류, 파일명 오류, 파일전송 미완료, 기타오류 등을 판별하고, + // 응답코드를 결정해 줘야 한다. --> 정영우 과장과 협의하여 현재 처리방식 검토후 결정 : 일단 정상처리 + // + // 퇴직연금 만의 응답코드 계산 로직을 만들 것... + // + return TelegramKeys.RPS_HDB_RET_CODE_SUCCESS; + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() { + int nSumFormalField = 0; + for (int i=0; i organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + long fileSize = Long.parseLong(new String ((byte[]) al_Field.get(6))); //화일 size + String bizFld = new String ((byte[]) al_Field.get(3)); + String basedate = bizFld.substring(6, 14); +// batchDoc.getEAIBatchMessage().getHeader().setFileName(bizCode+"RE"); + batchDoc.getBatchMsg().getHeader().setFileName(fileName); + batchDoc.getBatchMsg().getHeader().setFileSize(fileSize); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + batchDoc.getBatchMsg().getHeader().setBaseDate(basedate); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + BatchJobInfoVO vo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( vo != null ){ + batchDoc.getBatchMsg().getHeader().setJobCode(vo.getBatchCode()); + batchDoc.getBatchMsg().getHeader().setRecLen((int)vo.getFileRecSize()); + //} // 20250910 npe + + try { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(fileSize/(int)vo.getFileRecSize()); + } catch (Exception e) { + batchDoc.getBatchMsg().getHeader().setTotRecCnt(1); + } + } + +// if ( endGb.equalsIgnoreCase(TelegramKeys.MAGICLINK_END)) { +// this.setConditionTxt(TelegramKeys.NOFILE); +// } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_110.java b/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_110.java new file mode 100644 index 0000000..492d634 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_110.java @@ -0,0 +1,82 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_SCBANK_110 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_SCBANK_110() { + //송신 파일 통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + LogUtil.setLogFileStart(batchDoc); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_130.java b/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_130.java new file mode 100644 index 0000000..860fb36 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_130.java @@ -0,0 +1,154 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SCBANK_130 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_SCBANK_130() { + //수신확인 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + + String procYn = new String ((byte[]) al_Field.get(7)); // 처리여부 + + LogUtil.setLogFileEnd(batchDoc); + if (getResCode().equalsIgnoreCase(TelegramKeys.MAGIC_RES_CODE_SUCESS) + && procYn.equalsIgnoreCase("Y")) { + checkMoreFileinDB(); + }else{ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[1]; + msgArgs[0] = getResCode(); + String errCode = "BECEAIFRS021"; //'기타오류'(응답코드:{1}) 응답전문이 수신되었습니다. + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// SchedulerMessageVO info; +// try{ +// info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); +// if ( info == null ) { +// this.setConditionTxt(TelegramKeys.NOFILE); +// return; +// } +// String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); +// String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); +// +// //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 +// SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); +// +// //BatchMsgDoc 값 설정 +// batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); +// batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); +// batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); +// batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); +// batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); +// batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); +// batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); +// batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); +// batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); +// batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); +// batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); +// batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); +// batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); +// BatchJobInfoVO bjInfo = DirInfoManager.getInstance().getFileInfo(info.getJobCode()); +// batchDoc.getBatchMsg().getHeader().setRecLen((int)bjInfo.getFileRecSize()); +// batchDoc.getBatchMsg().getHeader().setFileSize(0); +// batchDoc.getBatchMsg().getBody().setCurFileSize(0); +// String hdrInfoName = info.getHdrInfoName(); +// batchDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); +// batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); +// batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); +// batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt()); +// this.setConditionTxt(""); +// +// } catch ( Exception e){ +// +// } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_SND.java b/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_SND.java new file mode 100644 index 0000000..d4b1d09 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/RECV_SCBANK_SND.java @@ -0,0 +1,236 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SCBANK_SND extends DefaultTelegram implements TelegramService +{ + + private ByteArrayOutputStream bout; + private int REAL_BYTE; + + /** + * 생성자 + */ + public RECV_SCBANK_SND() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String isEOF = new String ((byte[]) al_Field.get(2)); + String bizFld = new String ((byte[]) al_Field.get(3)); + int recv_seq_no = Integer.parseInt(bizFld.substring(0, 10)); + + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (recv_seq_no != seq_no + 1 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = "0" + recv_seq_no; + msgArgs[2] = "0"+ seq_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + if ( isEOF.equals(TelegramKeys.MAGICLINK_END )){ + this.setConditionTxt(TelegramKeys.EOF); + } + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + batchDoc.getBatchMsg().setTelegramBody(new String(bout.toByteArray())); + + FileOutputStream fout = createFile(); + if ( fout == null ){ + return false; + } + fout.write(bout.toByteArray()); + fout.close(); + + // 전송 상태 처리 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + try { + String bizFld = new String ((byte[]) al_Field.get(3)); + REAL_BYTE = Integer.parseInt(bizFld.substring(10)); + return REAL_BYTE; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + bout.write(data, 0, length); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private FileOutputStream createFile () { + FileOutputStream fout = null; + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + if ( seq_no > 1 ){ + fout = new FileOutputStream(file, true); + }else{ + fout = new FileOutputStream(file, false); + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + } + return fout; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_003.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_003.java new file mode 100644 index 0000000..f47b780 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_003.java @@ -0,0 +1,196 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SCBANK_003 extends DefaultTelegram implements TelegramService +{ + + private Properties telegramInfo; + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_SCBANK_003() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + String bizFld = telegramInfo.getProperty(TelegramKeys.BANK_CODE ) + + telegramInfo.getProperty(TelegramKeys.CENTER_CODE ) + + TelegramKeys.getYYYYMMDD(); + compileField(3, bizFld, this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[6]); + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + }else if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE)) { + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_RECV, this.al_FieldProps[7]); + //File Name + //compileField(8, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[8]); + compileField(8, "ALALL", this.al_FieldProps[8]); + //Flag + compileField(9, TelegramKeys.MLINK_RECV_FLAG, this.al_FieldProps[9]); + //시작시간 + compileField(10, TelegramKeys.getYYYYMMDD()+ "0000", this.al_FieldProps[10]); + //끝시간 + compileField(11, TelegramKeys.getYYYYMMDD()+ "2359", this.al_FieldProps[11]); + } + + //Password 변경 여부 + compileField(12, "", this.al_FieldProps[12]); + + //New Password + compileField(13, "", this.al_FieldProps[13]); + + //Comm Size + compileField(14, "" +batchDoc.getBatchMsg().getHeader().getPacketSize(), this.al_FieldProps[14]); + + //FILLER + compileField(15, "", this.al_FieldProps[15]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_007.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_007.java new file mode 100644 index 0000000..d0901dd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_007.java @@ -0,0 +1,169 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SCBANK_007 extends DefaultTelegram implements TelegramService +{ + + private Properties telegramInfo; + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_SCBANK_007() { + //LOGOUT 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + String bizFld = telegramInfo.getProperty(TelegramKeys.BANK_CODE ) + + telegramInfo.getProperty(TelegramKeys.CENTER_CODE ); + compileField(3, bizFld, this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[6]); + + //Job Type + compileField(7, TelegramKeys.MLINK_PROCESS_SEND, this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + //FILLER + compileField(12, "", this.al_FieldProps[12]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_030.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_030.java new file mode 100644 index 0000000..f55c0f9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_030.java @@ -0,0 +1,177 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SCBANK_030 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_SCBANK_030() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + String recvTelegramHeader = new String(batchDoc.getBatchMsg().getTelegramHeader()); + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, recvTelegramHeader.substring(19,39), this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, "", this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, "", this.al_FieldProps[6]); + + //Job Type + compileField(7, recvTelegramBody.substring(28,30), this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + + //Password 변경 여부 + compileField(12, "", this.al_FieldProps[12]); + + //New Password + compileField(13, "", this.al_FieldProps[13]); + + //Comm Size + compileField(14, "" +batchDoc.getBatchMsg().getHeader().getPacketSize(), this.al_FieldProps[14]); + + //FILLER + compileField(15, "", this.al_FieldProps[15]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_070.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_070.java new file mode 100644 index 0000000..aaa74e2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_070.java @@ -0,0 +1,167 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SCBANK_070 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_SCBANK_070() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + String recvTelegramHeader = new String(batchDoc.getBatchMsg().getTelegramHeader()); + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, recvTelegramHeader.substring(19,39), this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //송신자 ID + compileField(5, "", this.al_FieldProps[5]); + + //송신자 암호 + compileField(6, "", this.al_FieldProps[6]); + + //Job Type + compileField(7, recvTelegramBody.substring(28,30), this.al_FieldProps[7]); + //File Name + compileField(8, "", this.al_FieldProps[8]); + //Flag + compileField(9, "", this.al_FieldProps[9]); + //시작시간 + compileField(10, "", this.al_FieldProps[10]); + //끝시간 + compileField(11, "", this.al_FieldProps[11]); + //FILLER + compileField(12, "", this.al_FieldProps[12]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_100.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_100.java new file mode 100644 index 0000000..3578a67 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_100.java @@ -0,0 +1,246 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SCBANK_100 extends DefaultTelegram implements TelegramService +{ + private Properties telegramInfo; + private String isLast; + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + /** + * 생성자 + */ + public SEND_SCBANK_100() { + //송신 파일 통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + if ( !createFile() ){ + return false; + } + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + String bizFld = telegramInfo.getProperty(TelegramKeys.BANK_CODE ) + + telegramInfo.getProperty(TelegramKeys.CENTER_CODE )+ + batchDoc.getBatchMsg().getHeader().getBaseDate(); + compileField(3, bizFld, this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, "" + batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[6]); + + //송신자 ID + compileField(7, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[7]); + + //수신자 ID + compileField(8, "", this.al_FieldProps[8]); + + //FILLER 1 + compileField(9, "", this.al_FieldProps[9]); + + //FILLER 2 + compileField(10, "", this.al_FieldProps[10]); + + //마지막 여부 + compileField(11, isLast, this.al_FieldProps[10]); + + //전송종류 + compileField(12, "", this.al_FieldProps[12]); + + //FILLER 3 + compileField(13, "", this.al_FieldProps[13]); + + //FILLER 4 + compileField(14, "", this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + if ( checkMoreFile() ){ + isLast = TelegramKeys.MAGICLINK_NEXT; + }else{ + isLast = TelegramKeys.MAGICLINK_END; + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkMoreFile(){ + +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// SchedulerMessageVO info; +// try{ +// info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); +// if ( info != null ) { +// return true; +// } +// } catch ( Exception e){ +// return false; +// } + return false; + } + private boolean createFile() + { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(file); + + batchDoc.getBatchMsg().getHeader().setFileSize(file.length()); + logger.info("{} File [" + file.getName() + "] Size =" + file.length(), logHeader); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_110.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_110.java new file mode 100644 index 0000000..6e1a6d3 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_110.java @@ -0,0 +1,183 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SCBANK_110 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_SCBANK_110() { + //송신 파일 통보응답 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + String recvTelegramHeader = new String(batchDoc.getBatchMsg().getTelegramHeader()); + String recvTelegramBody = new String(batchDoc.getBatchMsg().getTelegramBody()); + + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, recvTelegramHeader.substring(19,39), this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[6]); + + //송신자 ID + compileField(7, "", this.al_FieldProps[7]); + + //수신자 ID + compileField(8, "", this.al_FieldProps[8]); + + //FILLER 1 + compileField(9, "", this.al_FieldProps[9]); + + //FILLER 2 + compileField(10, "", this.al_FieldProps[10]); + + //마지막 여부 + String isNofile = recvTelegramBody.substring(81,84); + batchDoc.getBatchMsg().getBody().setSendSummary(isNofile); + compileField(11, isNofile, this.al_FieldProps[11]); + + //전송종류 + compileField(12, "", this.al_FieldProps[12]); + + //FILLER 3 + compileField(13, "", this.al_FieldProps[13]); + + //FILLER 4 + compileField(14, "", this.al_FieldProps[14]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_130.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_130.java new file mode 100644 index 0000000..fc06311 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_130.java @@ -0,0 +1,217 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.lang.String; +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class SEND_SCBANK_130 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; + + /** + * 생성자 + */ + public SEND_SCBANK_130() { + //수신확인 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + if ( !calculateSendLength() ) return false; + + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+SEND_LENGTH, 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + compileField(2, this.getResolveResponseCode(), this.al_FieldProps[2]); + + //업무필드 + compileField(3, "", this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + //FILE NAME + compileField(5, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[5]); + + //FILE SIZE + compileField(6, ""+batchDoc.getBatchMsg().getHeader().getFileSize(), this.al_FieldProps[6]); + + //처리여부 + if ( this.getResolveResponseCode().equals(TelegramKeys.MAGIC_RES_CODE_SUCESS)) { + compileField(7, "Y", this.al_FieldProps[7]); + } else { + compileField(7, "N", this.al_FieldProps[7]); + } + + //FILLER + compileField(8, "", this.al_FieldProps[8]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + private boolean calculateSendLength () { + try { + for (int i=0; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + SEND_LENGTH -= 4; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + long fileSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + if ( fileSize != lnCurSize ){ + this.setResolveResponseCode( TelegramKeys.MAGIC_RES_CODE_ETC_ERROR ); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + } + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + String isNofile = batchDoc.getBatchMsg().getBody().getSendSummary(); + if ( isNofile.equals(TelegramKeys.MAGICLINK_END)){ + setConditionTxt(TelegramKeys.NOFILE); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_SND.java b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_SND.java new file mode 100644 index 0000000..4549c41 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/school/SEND_SCBANK_SND.java @@ -0,0 +1,313 @@ +package com.eactive.eai.batch.job.jobItem.school; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SCBANK_SND extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int REAL_BYTE; // 실 data byte수 + private int HEADER_LEN; + + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_SCBANK_SND() { + //DATA송신 + HEADER_LEN = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setData(); + if (!result) { + return false; + } + //길이 필드 + TR CODE 향후 TCP/IP로 전환 될 것을 대비 하여 길이와 TR CODE를 하나의 필드로 간주 하여 처리 한다. + compileField(0, makeZero(""+(HEADER_LEN+REAL_BYTE), 4), this.al_FieldProps[0]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(1, this.getFldTelegramType().substring(0,3), this.al_FieldProps[1]); + + //응답코드 + if ( getConditionTxt().equals(TelegramKeys.EOF)){ + compileField(2, TelegramKeys.MAGICLINK_END, this.al_FieldProps[2]); + }else{ + compileField(2, TelegramKeys.MAGICLINK_NEXT, this.al_FieldProps[2]); + } + + //업무필드 + String bizFld = makeZero( ""+batchDoc.getBatchMsg().getBody().getSeqNum(), 10) + + makeZero( ""+REAL_BYTE, 10 ); + compileField(3, bizFld, this.al_FieldProps[3]); + + //예비 + compileField(4, "", this.al_FieldProps[4]); + + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return HEADER_LEN + 4 + REAL_BYTE; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( fin == null) { + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + logger.info("{} File [" + file.getName() + "] Size =" + file.length(), logHeader); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setData () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + for (int i=0; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + HEADER_LEN += aField.length; + } + HEADER_LEN -= 4; + + int data_size = this.batchDoc.getBatchMsg().getHeader().getPacketSize() - HEADER_LEN; + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + this.batchDoc.getBatchMsg().getBody().setSeqNum(seq_no + 1); + + if (batchDoc.getBatchMsg().getBody().getCurFileSize() + data_size >= batchDoc.getBatchMsg().getHeader().getFileSize()) { + this.setConditionTxt(TelegramKeys.EOF); + } + + fileData = new byte[data_size]; + REAL_BYTE = fin.read(fileData); + + // 전송 상태 처리 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(1); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(2); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB.java new file mode 100644 index 0000000..b70a63e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB.java @@ -0,0 +1,140 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_SHCDB extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 : CMS쪽 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_SHCDB() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + String propKey = ""; + switch (idx) { + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + return Integer.parseInt( getTelegramInfo().getProperty(propKey) ); + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + idx = vo.getLengthField(); + if (idx == 0) return -1; + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=2; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + return; + } + LogUtil.setLogFileEnd(batchDoc); + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){} + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0310.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0310.java new file mode 100644 index 0000000..59469f0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0310.java @@ -0,0 +1,243 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SHCDB_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_SHCDB_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0320.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0320.java new file mode 100644 index 0000000..37cd685 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0320.java @@ -0,0 +1,230 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SHCDB_0320 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_SHCDB_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + return Integer.parseInt(byte_size); + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0600.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0600.java new file mode 100644 index 0000000..7a9d530 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0600.java @@ -0,0 +1,118 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SHCDB_0600 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_SHCDB_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0610.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0610.java new file mode 100644 index 0000000..8304b6a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0610.java @@ -0,0 +1,143 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SHCDB_0610 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_SHCDB_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + // File Open LOG + File ff = new File(fileName); + + //응답송신이 아니고 0610/0004를 수신하면 (응답송신의 경우 recv0300일경우에 파일을 이동시키므로 이단계에서는 파일이 존재하지 않음 + if (!CommonKeys.PROCESS_RESPONSE_SEND.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + if (ff.exists() && OpCode_noexsist.equals(this.getOpCode())) { + logger.info("{} FILE SIZE ("+ ff.length() + "]", logHeader); + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(ff); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + if (OpCode_noexsist.equals(this.getOpCode()) && fileNm != null && !fileNm.trim().equals("")) { + //응답수신 파일 Start DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0620.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0620.java new file mode 100644 index 0000000..e8b47a4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0620.java @@ -0,0 +1,123 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SHCDB_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_SHCDB_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0630.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0630.java new file mode 100644 index 0000000..1350fcc --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0630.java @@ -0,0 +1,170 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SHCDB_0630 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_SHCDB_0630() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try{ + + String fileInfo = new String ((byte[]) al_Field.get(9)); + String fName = fileInfo.substring(0, 8).trim(); + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_CDCMS_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + } + + String pattern = null; + long recLen = 0; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getHeader().setFileSize(fSize); + long recCnt = 0; + if ( recLen > 0 ){ + recCnt = fSize / recLen; + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0640.java b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0640.java new file mode 100644 index 0000000..1e2f495 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/RECV_SHCDB_0640.java @@ -0,0 +1,167 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SHCDB_0640 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_SHCDB_0640() { + //화일정보수신통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String fileInfo = new String ((byte[]) al_Field.get(9)); // 화일정보내역 + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + if (getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_ALREADY_RECEIVED) + ||getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_NOT_REGISTERED)) { //기송신 파일이면 + checkMoreFileinDB(); + } else { + if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면 + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; + + /* + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + logger.error( e.getMessage(), e); + } + */ + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0300.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0300.java new file mode 100644 index 0000000..9ee73f0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0300.java @@ -0,0 +1,452 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_SHCDB_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //결번갯수 + compileField(11, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + String jobCode = this.batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + case 12: + return MISSING_FIELD.length(); + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + case 12: + //mod by khs data = MISSING_FIELD.getBytes(); + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0310.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0310.java new file mode 100644 index 0000000..20c8de1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0310.java @@ -0,0 +1,378 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_SHCDB_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 (실제 기관 코드 사용 길이-1) 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0320.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0320.java new file mode 100644 index 0000000..5346b10 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0320.java @@ -0,0 +1,464 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0320 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_SHCDB_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + case 12: + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + case 12: + return REAL_BYTE; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID()); + if( fin != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + if ( isLastSeq ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0600.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0600.java new file mode 100644 index 0000000..6e5e72e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0600.java @@ -0,0 +1,337 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.encrypt.EncryptManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_SHCDB_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE); + if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) { + String orgCd = telegramInfo.getProperty(TelegramKeys.BANK_CODE); + String orgCd2 = orgCd.substring(1); + if ( orgCd.length() == 8 ) + orgCd2 = orgCd.substring(0,1)+orgCd.substring(7,8); + String passwd = EncryptManager.getInstance().getEncrypt(batchDoc.getBatchMsg().getHeader().getUserID(), + (batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6), + //telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1), + orgCd2, + TelegramKeys.getYYYYMMddHHmmss().substring(2,8)); + compileField(12, passwd, this.al_FieldProps[12]); + }else{ + compileField(12, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[12]); + } + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0610.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0610.java new file mode 100644 index 0000000..455f7f9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0610.java @@ -0,0 +1,377 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_SHCDB_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + logger.info("{} Process Type : ["+this.batchDoc.getBatchMsg().getHeader().getProcessType()+"]", logHeader); + logger.info("{} FldOpCode : ["+this.getFldOpCode()+"]", logHeader); + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode())> -1 ){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 (CMS시스템의 책임자 ID + compileField(11, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[11]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(12, "", this.al_FieldProps[12]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (this.getFldOpCode().equals("001")) return true; + + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0620.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0620.java new file mode 100644 index 0000000..9421fce --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0620.java @@ -0,0 +1,301 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_SHCDB_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0630.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0630.java new file mode 100644 index 0000000..3685561 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0630.java @@ -0,0 +1,315 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0630 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_SHCDB_0630() { + //화일정보수신요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + int seqSize = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ) * batchDoc.getBatchMsg().getHeader().getRecLen(); + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + + //응답코드 + compileField(8, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(fileName, 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12)); + // 0630 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + fileInfo.append(makeZero(""+(SEND_LENGTH + seqSize - 13), 4)); + + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0640.java b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0640.java new file mode 100644 index 0000000..7d169c4 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/shcd/SEND_SHCDB_0640.java @@ -0,0 +1,363 @@ +package com.eactive.eai.batch.job.jobItem.shcd; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SHCDB_0640 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_SHCDB_0640() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + //전송길이 + compileField(2, "" + SEND_LENGTH, this.al_FieldProps[2]); + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + //거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무 + //compileField(5, this.getFldTrClass(), this.al_FieldProps[5]); + //기관별로 송수신시 사용되는 거래구분코드가 상이하여 기관별 속성값에서 참조하도록 함. + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + //송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시 + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_SEND), this.al_FieldProps[6]); + }else{ + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_RECV), this.al_FieldProps[6]); + } + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName() , this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(batchDoc.getBatchMsg().getHeader().getFileName(), 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getBody().getCurFileSize(),12)); + fileInfo.append(makeZero(""+calculateTelegramSize(), 4)); + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + //해당 거래구분에 대한 Job_Code 값 설정 + //거래구분코드 조회 BizCode 조회 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + if (info != null) { + batchDoc.getBatchMsg().getHeader().setJobCode(info.getMsgDstCode());; + } else { + logger.debug("{} " + batchDoc.getBatchMsg().getHeader().getUUID()+ "'s Job Code is null", logHeader); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + batchDoc.getBatchMsg().getHeader().setJobCode((processCode+"00000")); //dummy code + // TEST 용 return false; + } + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + // XX인 경우 길이를 1로 계산하므로 i=3 인 경우 실제 기관 코드 사용 길이-1 만큼을 더 해 준다. + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += ( getCalculatedLength(3) - 1 ); + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fieldLen = -1; + String propKey = ""; + switch (idx) { + + case 0: + propKey = TelegramKeys.TRCD_LEN; + break; + + case 3: + propKey = TelegramKeys.ORGN_CD_LEN; + break; + + default: + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + try { + fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) ); + + } catch (Exception e) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = propKey; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return fieldLen; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + switch (idx) { + case 3: + // 기관코드 + System.arraycopy((telegramInfo.getProperty(TelegramKeys.BANK_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + break; + default: + break; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private int calculateTelegramSize(){ + int recSize = 200; + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo != null && bJobInfo.getFileRecSize() > 0 ){ + recSize = (int)Math.min(bJobInfo.getFileRecSize(), 4000); + } + + // 0630/0640 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630/0640 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + return (batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize) * recSize + SEND_LENGTH - 13; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01.java b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01.java new file mode 100644 index 0000000..3383a8b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01.java @@ -0,0 +1,71 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_SKT01 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : SKT 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_SKT01() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( this.getTelegramType().equals("0800") || this.getTelegramType().equals("0810") ){ + return super.getFieldValueString(11); + }else{ + return ""; + } + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int nDocLen = Integer.parseInt(new String((byte[])this.al_Field.get(0))); + int nReceivedLen = 0; + for (int i=1; i> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_line = "301"; //회선테스트 + + + /** + * 생성자 + */ + public RECV_SKT01_0800() { + //개시/종료 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try{ + + String fName = new String ((byte[]) al_Field.get(4)); + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo != null ){ + batchDoc.getBatchMsg().getHeader().setJobCode(bJobInfo.getMsgDstCode()); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bJobInfo.getFileRecSize()); + }else{ + batchDoc.getBatchMsg().getHeader().setRecLen(100); + } + + + batchDoc.getBatchMsg().getHeader().setFileName(fName); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_line)) { + logger.info("{} BATCH JOB : line check request received", logHeader); + } + else { + logger.info("{} 0800 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode("99"); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } + + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_0810.java b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_0810.java new file mode 100644 index 0000000..1d99968 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_0810.java @@ -0,0 +1,118 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SKT01_0810 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_line = "301"; //회선테스트 + + + /** + * 생성자 + */ + public RECV_SKT01_0810() { + //개시/종료 전문 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_line)) { + logger.info("{} BATCH JOB : line check request received", logHeader); + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode("99"); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } + + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2100.java b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2100.java new file mode 100644 index 0000000..c45e291 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2100.java @@ -0,0 +1,162 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.util.HashMap; +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_SKT01_2100 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_SKT01_2100() { + //DATA수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(11)); + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_seq_no = Integer.parseInt(_seq_no); + + // 강제 결번 테스트용 +// if ( Math.random() > 0.3 ){ +// block_data.put( new Integer(recv_seq_no-1) , (byte[]) al_Field.get(13)); +// } + block_data.put( new Integer(recv_seq_no-1) , (byte[]) al_Field.get(13)); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + baout.write((byte[])this.al_Field.get(al_Field.size()-1), 0, 12); + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2200.java b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2200.java new file mode 100644 index 0000000..fc8cb73 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2200.java @@ -0,0 +1,127 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.lang.String; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_SKT01_2200 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_SKT01_2200() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(11)); + + int recv_block_no = Integer.parseInt(_block_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + if (recv_block_no != block_no ){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2210.java b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2210.java new file mode 100644 index 0000000..29df901 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/RECV_SKT01_2210.java @@ -0,0 +1,119 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SKT01_2210 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_SKT01_2210() { + //결번확인통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String missing_field = new String ((byte[]) al_Field.get(12)); + + int lastSeq = batchDoc.getBatchMsg().getBody().getSeqNum(); + int recv_migging_count = 0; + for (int inx = 0; inx < lastSeq; inx++) { + if ( (missing_field.getBytes())[inx] == '0' ) + recv_migging_count++; + } + + + if (recv_migging_count == 0 ) { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + + long fileSize = batchDoc.getBatchMsg().getHeader().getFileSize(); + long curSize = batchDoc.getBatchMsg().getBody().getCurFileSize(); + if ( curSize >= fileSize){ + this.setConditionTxt(TelegramKeys.EOF); + } + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + +} diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_0800.java b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_0800.java new file mode 100644 index 0000000..12932d2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_0800.java @@ -0,0 +1,265 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SKT01_0800 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + public SEND_SKT01_0800() { + //개시/종료 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE ), this.al_FieldProps[1]); + + //송신기관코드 - 송신기관코드 참조 "7170" + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE ), this.al_FieldProps[2]); + + //전문코드(개시/데이터/결번) + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //자료구분코드(파일명) - 기본(19) - 파일명(Full Name): 기관코드(4)+파일ID(6)+구분자(1)+YYYYMMDD(8) + compileField(4, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[4]); + + //전문고유번호(순번) 각각의 전문은 고유한 6자리의 번호를 갖는다.(각각의 전문을 sequence하게 할당한다.) + compileField(5, ""+batchDoc.getBatchMsg().getBody().getNodeCount(), this.al_FieldProps[5]); + + //전송일자(YYMMDD) + compileField(6, TelegramKeys.getYYYYMMDD().substring(2), this.al_FieldProps[6]); + + //전송시각(HH24MISS) + compileField(7, TelegramKeys.getHHMMSS(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //암호 - UNUSED + compileField(9, "", this.al_FieldProps[9]); + + //RESERVED - UNUSED + compileField(10, "", this.al_FieldProps[10]); + + //통신망관리정보(001/002/301) + compileField(11, this.getFldOpCode(), this.al_FieldProps[11]); + + //DATA HEADER - UNUSED + compileField(12, "", this.al_FieldProps[12]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (this.getFldOpCode().equals("001")){ + LogUtil.setLogFileStart(batchDoc); + }else if (this.getFldOpCode().equals("002")){ + LogUtil.setLogFileEnd(batchDoc); + } + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return -1; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } + + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_0810.java b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_0810.java new file mode 100644 index 0000000..d6f34d5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_0810.java @@ -0,0 +1,354 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SKT01_0810 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + public SEND_SKT01_0810() { + //개시/종료 전문 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE ), this.al_FieldProps[1]); + + //송신기관코드 - 송신기관코드 참조 "7170" + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE ), this.al_FieldProps[2]); + + //전문코드(개시/데이터/결번) + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //자료구분코드(파일명) - 기본(19) - 파일명(Full Name): 기관코드(4)+파일ID(6)+구분자(1)+YYYYMMDD(8) + compileField(4, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[4]); + + //전문고유번호(순번) 각각의 전문은 고유한 6자리의 번호를 갖는다.(각각의 전문을 sequence하게 할당한다.) + compileField(5, ""+batchDoc.getBatchMsg().getBody().getNodeCount(), this.al_FieldProps[5]); + + //전송일자(YYMMDD) + compileField(6, TelegramKeys.getYYYYMMDD().substring(2), this.al_FieldProps[6]); + + //전송시각(HH24MISS) + compileField(7, TelegramKeys.getHHMMSS(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //암호 - UNUSED + compileField(9, "", this.al_FieldProps[9]); + + //RESERVED - UNUSED + compileField(10, "", this.al_FieldProps[10]); + + //통신망관리정보(001/002/301) + compileField(11, this.getFldOpCode(), this.al_FieldProps[11]); + + //DATA HEADER - UNUSED + compileField(12, "", this.al_FieldProps[12]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if (this.getFldOpCode().equals("001")){ + LogUtil.setLogFileStart(batchDoc); + }else if (this.getFldOpCode().equals("002")){ + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if ( block_data != null ){ + //FileOutputStream fout = new FileOutputStream(rcvRealFile, true); + try (FileOutputStream fout = new FileOutputStream(rcvRealFile, true)) {// 20250910 obl + for (int i = 0; i Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode("99"); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + } + + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return -1; + + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(11); + } + + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2100.java b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2100.java new file mode 100644 index 0000000..4312688 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2100.java @@ -0,0 +1,501 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SKT01_2100 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; // 실 data byte수 + private int DATA_LEN; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_SKT01_2100() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE ), this.al_FieldProps[1]); + + + //송신기관코드 - 송신기관코드 참조 "7170" + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE ), this.al_FieldProps[2]); + + //전문코드(개시/데이터/결번) + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //자료구분코드(파일명) - 기본(19) - 파일명(Full Name): 기관코드(4)+파일ID(6)+구분자(1)+YYYYMMDD(8) + compileField(4, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[4]); + + //전문고유번호(순번) 각각의 전문은 고유한 6자리의 번호를 갖는다.(각각의 전문을 sequence하게 할당한다.) + compileField(5, ""+batchDoc.getBatchMsg().getBody().getNodeCount(), this.al_FieldProps[5]); + + //전송일자(YYMMDD) + compileField(6, TelegramKeys.getYYYYMMDD().substring(2), this.al_FieldProps[6]); + + //전송시각(HH24MISS) + compileField(7, TelegramKeys.getHHMMSS(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + //암호 - UNUSED + + compileField(9, "", this.al_FieldProps[9]); + + //RESERVED - UNUSED + compileField(10, "", this.al_FieldProps[10]); + + //BLOCK-NO + compileField(11, ""+BLOCK_NO, this.al_FieldProps[11]); + + //RECORD 일련번호 + compileField(12, ""+SEQUENCE_NO, this.al_FieldProps[12]); + + //DATA ( 총 길이 + DATA건수 + 1개 DATA 길이 + DATA + SPACE + compileField(13, new String(fileData), this.al_FieldProps[13]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size()-1; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + baout.write((byte[])this.al_Field.get(al_Field.size()-1), 0, 12); + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID()); + if( fin != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + if ( missing_count > 0 ){ + return setBlockAndSeqNO_from_memory(); + }else{ + return setBlockAndSeqNO_from_disk(); + } + + } + private boolean setBlockAndSeqNO_from_disk () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + logger.debug("[SEND_0320]remainCnt-->" + remainCnt); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + DATA_LEN = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + DATA_LEN = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = DATA_LEN / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[4004]; + for (int inx1 = 0; inx1 < fileData.length; inx1++) { + fileData[inx1] = ' '; + } + String strDataTotLen = makeZero("" + ( DATA_LEN + 19),4); + String strRecCount = makeZero( "" + readCnt, 4); + String strRecLen = makeZero( "" + batchDoc.getBatchMsg().getHeader().getRecLen(), 4); + System.arraycopy( strDataTotLen.getBytes(), 0, fileData, 0, 4); + System.arraycopy( strRecCount.getBytes(), 0, fileData, 4, 4); + System.arraycopy( strRecLen.getBytes(), 0, fileData, 8, 4); + + byte[] fileLine = null; + for ( int inx = 0 ; inx < readCnt ; inx++){ + fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, 12 + inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + if ( BLOCK_NO == 1 && SEQUENCE_NO == 1 && inx == 0 ){ + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + } + + if ( isLastSeq ){ + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + DATA_LEN; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean setBlockAndSeqNO_from_memory () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2200.java b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2200.java new file mode 100644 index 0000000..f8bb0b0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2200.java @@ -0,0 +1,258 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SKT01_2200 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_SKT01_2200() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE ), this.al_FieldProps[1]); + + //송신기관코드 - 송신기관코드 참조 "7170" + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE ), this.al_FieldProps[2]); + + //전문코드(개시/데이터/결번) + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //자료구분코드(파일명) - 기본(19) - 파일명(Full Name): 기관코드(4)+파일ID(6)+구분자(1)+YYYYMMDD(8) + compileField(4, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[4]); + + //전문고유번호(순번) 각각의 전문은 고유한 6자리의 번호를 갖는다.(각각의 전문을 sequence하게 할당한다.) + compileField(5, ""+batchDoc.getBatchMsg().getBody().getNodeCount(), this.al_FieldProps[5]); + + //전송일자(YYMMDD) + compileField(6, TelegramKeys.getYYYYMMDD().substring(2), this.al_FieldProps[6]); + + //전송시각(HH24MISS) + compileField(7, TelegramKeys.getHHMMSS(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + //암호 - UNUSED + + compileField(9, "", this.al_FieldProps[9]); + + //RESERVED - UNUSED + compileField(10, "", this.al_FieldProps[10]); + + //BLOCK-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return -1; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2210.java b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2210.java new file mode 100644 index 0000000..643d453 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/skt/SEND_SKT01_2210.java @@ -0,0 +1,384 @@ +package com.eactive.eai.batch.job.jobItem.skt; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SKT01_2210 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_SKT01_2210() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE ), this.al_FieldProps[1]); + + //송신기관코드 - 송신기관코드 참조 "7170" + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE ), this.al_FieldProps[2]); + + //전문코드(개시/데이터/결번) + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //자료구분코드(파일명) - 기본(19) - 파일명(Full Name): 기관코드(4)+파일ID(6)+구분자(1)+YYYYMMDD(8) + compileField(4, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[4]); + + //전문고유번호(순번) 각각의 전문은 고유한 6자리의 번호를 갖는다.(각각의 전문을 sequence하게 할당한다.) + compileField(5, ""+batchDoc.getBatchMsg().getBody().getNodeCount(), this.al_FieldProps[5]); + + //전송일자(YYMMDD) + compileField(6, TelegramKeys.getYYYYMMDD().substring(2), this.al_FieldProps[6]); + + //전송시각(HH24MISS) + compileField(7, TelegramKeys.getHHMMSS(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + //암호 - UNUSED + + compileField(9, "", this.al_FieldProps[9]); + + //RESERVED - UNUSED + compileField(10, "", this.al_FieldProps[10]); + + //BLOCK-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[11]); + + //MISSING_FIELD + compileField(12, MISSING_FIELD, this.al_FieldProps[12]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<11; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=11; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + return -1; + + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 +// public String getTrClass() +// { +// return super.getFieldValueString(5); +// } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } + + +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT.java new file mode 100644 index 0000000..8b51bbc --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT.java @@ -0,0 +1,125 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_SSNBT extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 : CMS쪽 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_SSNBT() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + try { + int telegramSize = Integer.parseInt(new String ((byte[]) al_Field.get(0))); + int preFldTotSize = 0; + for (int i=1; i< idx; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + preFldTotSize += aField.length; + } + return telegramSize - preFldTotSize; + + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0310.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0310.java new file mode 100644 index 0000000..c3f9ed5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0310.java @@ -0,0 +1,220 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SSNBT_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 6; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_SSNBT_0310() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(7)); + int recv_seq_no = Integer.parseInt(_seq_no); + + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + int dataSize = Integer.parseInt(new String ((byte[]) al_Field.get(5))); + byte[] recvData = new byte[dataSize]; + System.arraycopy(bout.toByteArray(), 0, recvData, 0, dataSize); + + block_data.put( new Integer(recv_seq_no - 1), recvData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + if ( recv_seq_no == 1 ){ // 첫 레코드이면 + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(bizCode, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + batchDoc.getBatchMsg().setFileHeader(new String(recvData)); + LogUtil.setLogFileStart(batchDoc); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + if ( i != 6 ){ + baout.write((byte[])this.al_Field.get(i)); + }else{ + baout.write(bout.toByteArray()); + } + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < this.al_Field.size(); inx++) { + if ( inx != idx ){ + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0320.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0320.java new file mode 100644 index 0000000..d802b80 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0320.java @@ -0,0 +1,226 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SSNBT_0320 extends DefaultTelegram implements TelegramService +{ + + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_SSNBT_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(7)); + int recv_seq_no = Integer.parseInt(_seq_no); + + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + int dataSize = Integer.parseInt(new String ((byte[]) al_Field.get(5))); + byte[] recvData = new byte[dataSize]; + System.arraycopy(bout.toByteArray(), 0, recvData, 0, dataSize); + + block_data.put( new Integer(recv_seq_no - 1), recvData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + if ( recv_seq_no == 1 ){ // 첫 레코드이면 + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(bizCode, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + batchDoc.getBatchMsg().setFileHeader(new String(recvData)); + LogUtil.setLogFileStart(batchDoc); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + if ( i != 6 ){ + baout.write((byte[])this.al_Field.get(i)); + }else{ + baout.write(bout.toByteArray()); + } + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + if ( idx == 6 ){ + return batchDoc.getBatchMsg().getHeader().getSequenceSize(); + } + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + if ( inx != 6 ){ + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + }else{ + preLen += batchDoc.getBatchMsg().getHeader().getSequenceSize(); + } + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == 6) { + bout.write(data, 0, length); + } else if (idx == 9) { + return true; + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0600.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0600.java new file mode 100644 index 0000000..5b996eb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0600.java @@ -0,0 +1,216 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SSNBT_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "002"; //개별업무 종료 + private final String OpCode_end = "003"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_SSNBT_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + batchDoc.getBatchMsg().getBody().setRecvFld01(new String((byte[])this.al_Field.get(1))); + batchDoc.getBatchMsg().getBody().setRecvFld05(new String((byte[])this.al_Field.get(5))); + batchDoc.getBatchMsg().getBody().setRecvFld06(new String((byte[])this.al_Field.get(6))); + batchDoc.getBatchMsg().getBody().setRecvFld07(new String((byte[])this.al_Field.get(7))); + batchDoc.getBatchMsg().getBody().setRecvFld08(new String((byte[])this.al_Field.get(8))); + batchDoc.getBatchMsg().getBody().setRecvFld09(new String((byte[])this.al_Field.get(9))); + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + } + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0610.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0610.java new file mode 100644 index 0000000..aa9b71b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0610.java @@ -0,0 +1,161 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SSNBT_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_unit_end = "002"; //개별업무 종료 + private final String OpCode_end = "003"; //전체업무 종료 + + /** + * 생성자 + */ + public RECV_SSNBT_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.BOKGG_RES_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0620.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0620.java new file mode 100644 index 0000000..55492bd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/RECV_SSNBT_0620.java @@ -0,0 +1,196 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_SSNBT_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_SSNBT_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _seq_no = new String ((byte[]) al_Field.get(5)); + int recv_seq_no = Integer.parseInt(_seq_no); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if ( recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _seq_no; + msgArgs[2] = ""+seq_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + if ( batchDoc.getBatchMsg().getHeader().getFileSize() <= batchDoc.getBatchMsg().getBody().getCurFileSize()){ + this.setConditionTxt(TelegramKeys.EOF); + LogUtil.setLogFileEnd(batchDoc); + } + return true; + } + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + JobProcessData job = JobProcessData.getInstance(); + // 기 처리 완료된 시퀀스를 저장하여야 하는데 삼성네트웍스 프로토콜에서는 block 넘버가 의미 없으므로 이를 사용하도록 한다. + int lastSeq = batchDoc.getBatchMsg().getBody().getBlockNum(); + + HashMap hm = job.getBatchStageData(uuid); + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + this.setConditionTxt(TelegramKeys.LOSS); + batchDoc.getBatchMsg().getBody().setSeqNum(lastSeq+1); + } + + for (int inx = lastSeq + 1; inx <= recv_seq_no; inx++) { + if ( block_data.get( inx - 1 ) == null ){ + this.setConditionTxt(TelegramKeys.LOSS); + batchDoc.getBatchMsg().getBody().setSeqNum(inx); + break; + } + } + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = 0; + for (int inx = 1; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + return true; + } + + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + batchDoc.getBatchMsg().getBody().setRecvFld05(new String ((byte[])this.al_Field.get(5))); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0300.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0300.java new file mode 100644 index 0000000..f283cdb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0300.java @@ -0,0 +1,240 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SSNBT_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + /** + * 생성자 + */ + public SEND_SSNBT_0300() { + //결번요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 - 아데나 장비와 TCP통신을 위한 전문길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + //- 신/구 고객을 구분하기 위한 코드 + //- 기존고객코드 : EG01, EG05(구버젼 IBM tr id) + //- EG01,EG05를 제외하고는 모두 신규고객(Space처리) + //compileField(1, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[1]); + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문기능을 나타내는 코드 + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 : 전문의 처리결과를 나타내는 코드로 REQUEST전문에는 '0' 을 SET 하며 + //RESPONSE 전문에는 해당내용을 SET 한다. + //'000' = 정상 '310' = 송신자 계정오류 '001' = 송신집계오류 + //'320' = 송신자 ID 오류 '330' = 송신자 PSWD오류 '010' = NUMERIC오류 + //'340' = 수신자계정오류 '350' = 수산자 ID오류 '999' = 기타오류 + compileField(3, TelegramKeys.SSNET_MISS_RES_CODE, this.al_FieldProps[3]); + + //고객코드 - 현재 space 처리 + compileField(4, "", this.al_FieldProps[4]); + + //최종일련번호 - 결번전문 확인요구 및 완료시 SET 함 + compileField(5, "" + batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[5]); + + compileField(6, "", this.al_FieldProps[6]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 84; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0310.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0310.java new file mode 100644 index 0000000..4eb57d2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0310.java @@ -0,0 +1,295 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SSNBT_0310 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_SSNBT_0310() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 - 아데나 장비와 TCP통신을 위한 전문길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + //- 신/구 고객을 구분하기 위한 코드 + //- 기존고객코드 : EG01, EG05(구버젼 IBM tr id) + //- EG01,EG05를 제외하고는 모두 신규고객(Space처리) + //compileField(1, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[1]); + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문기능을 나타내는 코드 ('0600'/'0610') + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 : 전문의 처리결과를 나타내는 코드로 REQUEST전문에는 '0' 을 SET 하며 + //RESPONSE 전문에는 해당내용을 SET 한다. + //'000' = 정상 '310' = 송신자 계정오류 '001' = 송신집계오류 + //'320' = 송신자 ID 오류 '330' = 송신자 PSWD오류 '010' = NUMERIC오류 + //'340' = 수신자계정오류 '350' = 수산자 ID오류 '999' = 기타오류 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //고객코드 - 현재 space 처리 + compileField(4, "", this.al_FieldProps[4]); + + //전문길이 - 순수 DATA의 길이 + compileField(5, ""+REAL_BYTE, this.al_FieldProps[5]); + + //전문일련번호 - DATA RECORD : '00000001'부터 1씩 증가 + compileField(7, "" + SEQUENCE_NO, this.al_FieldProps[7]); + + //송수신 업무구분 - 'S' : 송신, 'R' : 수신 + compileField(8, TelegramKeys.SSNET_SEND, this.al_FieldProps[8]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + for (int inx = REAL_BYTE; inx < fldLen; inx++) { + data[inx] = ' '; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return batchDoc.getBatchMsg().getHeader().getSequenceSize(); + } + + private boolean setBlockAndSeqNO () + { + try { + SEQUENCE_NO = Integer.parseInt(batchDoc.getBatchMsg().getBody().getRecvFld05()); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + fileData = block_data.get( new Integer(SEQUENCE_NO - 1)); + REAL_BYTE = fileData.length; + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH -= 2; // 전문레이아웃상 가변필드가 두개임 + SEND_LENGTH += getCalculatedLength(6); + SEND_LENGTH += getCalculatedLength(9); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0320.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0320.java new file mode 100644 index 0000000..416e60b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0320.java @@ -0,0 +1,390 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SSNBT_0320 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_SSNBT_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 - 아데나 장비와 TCP통신을 위한 전문길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + //- 신/구 고객을 구분하기 위한 코드 + //- 기존고객코드 : EG01, EG05(구버젼 IBM tr id) + //- EG01,EG05를 제외하고는 모두 신규고객(Space처리) + //compileField(1, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[1]); + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문기능을 나타내는 코드 ('0600'/'0610') + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 : 전문의 처리결과를 나타내는 코드로 REQUEST전문에는 '0' 을 SET 하며 + //RESPONSE 전문에는 해당내용을 SET 한다. + //'000' = 정상 '310' = 송신자 계정오류 '001' = 송신집계오류 + //'320' = 송신자 ID 오류 '330' = 송신자 PSWD오류 '010' = NUMERIC오류 + //'340' = 수신자계정오류 '350' = 수산자 ID오류 '999' = 기타오류 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //고객코드 - 현재 space 처리 + compileField(4, "", this.al_FieldProps[4]); + + //전문길이 - 순수 DATA의 길이 + compileField(5, ""+REAL_BYTE, this.al_FieldProps[5]); + + //전문일련번호 - DATA RECORD : '00000001'부터 1씩 증가 + compileField(7, "" + SEQUENCE_NO, this.al_FieldProps[7]); + + //송수신 업무구분 - 'S' : 송신, 'R' : 수신 + compileField(8, TelegramKeys.SSNET_SEND, this.al_FieldProps[8]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + if ( fldLen == 0 ){ + return 0; + } + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + for (int inx = REAL_BYTE; inx < fldLen; inx++) { + data[inx] = ' '; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + if ( lnCurSize == REAL_BYTE ){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( idx == 6 ){ + return batchDoc.getBatchMsg().getHeader().getSequenceSize(); + }else{ + return 0; + } + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID()); + if( fin != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum() + 1; + + if (SEQUENCE_NO % block_size == 0) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + + // 한번에 보내는 길이 + int sequenceSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + + boolean isLastSeq = false; + if ( sequenceSize < remainSize ){ + REAL_BYTE = sequenceSize; + }else{ + REAL_BYTE = (int)remainSize; + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + + fileData = new byte[REAL_BYTE]; + fin.read(fileData); + + if ( isLastSeq ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO - 1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH -= 2; // 전문레이아웃상 가변필드가 두개임 + SEND_LENGTH += getCalculatedLength(6); + SEND_LENGTH += getCalculatedLength(9); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0320_JB.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0320_JB.java new file mode 100644 index 0000000..32cb427 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0320_JB.java @@ -0,0 +1,439 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SSNBT_0320_JB extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_SSNBT_0320_JB() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 - 아데나 장비와 TCP통신을 위한 전문길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + //- 신/구 고객을 구분하기 위한 코드 + //- 기존고객코드 : EG01, EG05(구버젼 IBM tr id) + //- EG01,EG05를 제외하고는 모두 신규고객(Space처리) + //compileField(1, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[1]); + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문기능을 나타내는 코드 ('0600'/'0610') + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 : 전문의 처리결과를 나타내는 코드로 REQUEST전문에는 '0' 을 SET 하며 + //RESPONSE 전문에는 해당내용을 SET 한다. + //'000' = 정상 '310' = 송신자 계정오류 '001' = 송신집계오류 + //'320' = 송신자 ID 오류 '330' = 송신자 PSWD오류 '010' = NUMERIC오류 + //'340' = 수신자계정오류 '350' = 수산자 ID오류 '999' = 기타오류 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //고객코드 - 현재 space 처리 + compileField(4, "", this.al_FieldProps[4]); + + //전문길이 - 순수 DATA의 길이 + compileField(5, ""+REAL_BYTE, this.al_FieldProps[5]); + + //전문일련번호 - DATA RECORD : '00000001'부터 1씩 증가 + compileField(7, "" + SEQUENCE_NO, this.al_FieldProps[7]); + + //송수신 업무구분 - 'S' : 송신, 'R' : 수신 + compileField(8, TelegramKeys.SSNET_SEND, this.al_FieldProps[8]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + if ( fldLen == 0 ){ + return 0; + } + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + for (int inx = REAL_BYTE; inx < fldLen; inx++) { + data[inx] = ' '; + } + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + if ( lnCurSize == REAL_BYTE ){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( idx == 6 ){ + return batchDoc.getBatchMsg().getHeader().getSequenceSize(); + }else{ + return 0; + } + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID()); + if( fin != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum() + 1; + + if (SEQUENCE_NO % block_size == 0) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + int appendLen = 0; + try { + appendLen = Integer.parseInt(getJobInfo().getProperty(TelegramKeys.APPEND_LL_LEN)); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + + fileData = new byte[REAL_BYTE]; + byte[] fileLine = null; + for ( int inx = 0 ; inx < readCnt ; inx++){ + fileLine = FileUtil.readLine(fin); + if ( fileLine == null ){ + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + Exception e = new Exception("체크파일에 명시된 건수와 DATA 파일의 건수가 맞지 않습니다. \n"+ + "확인 바랍니다."); + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + if ( fileLine.length + appendLen < batchDoc.getBatchMsg().getHeader().getRecLen() ){ + Exception e = new Exception("정의된 레코드 길이 보다 읽은 파일 레코드 길이가 작습니다. \n"+ + "확인 바랍니다.\n" + + "정의된 길이 [" + batchDoc.getBatchMsg().getHeader().getRecLen() + "], " + + "파일에서 읽은 길이[" + fileLine.length + "]"); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.getMessage()); + logger.error( e.getMessage(), e); + return false; + } + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), + Math.min(batchDoc.getBatchMsg().getHeader().getRecLen(), fileLine.length)); + if ( appendLen > 0 ){ + fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-1] = '\n'; + } + if ( appendLen > 1 ){ + fileData[((inx+1) * batchDoc.getBatchMsg().getHeader().getRecLen())-2] = '\r'; + } + if ( SEQUENCE_NO == 1 && inx == 0 ){ + byte[] header = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + System.arraycopy(fileLine, 0, header, 0, batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().setFileHeader(new String(header)); + } + } + + if ( isLastSeq ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + byte[] trailer = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + System.arraycopy(fileLine, 0, trailer, 0, batchDoc.getBatchMsg().getHeader().getRecLen()); + batchDoc.getBatchMsg().setFileTrailer(new String(trailer)); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO - 1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH -= 2; // 전문레이아웃상 가변필드가 두개임 + SEND_LENGTH += getCalculatedLength(6); + SEND_LENGTH += getCalculatedLength(9); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0600.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0600.java new file mode 100644 index 0000000..551da86 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0600.java @@ -0,0 +1,335 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SSNBT_0600 extends DefaultTelegram implements TelegramService +{ + private Properties telegramInfo; + private Properties jobInfo; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + /** + * 생성자 + */ + public SEND_SSNBT_0600() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 - 아데나 장비와 TCP통신을 위한 전문길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + //- 신/구 고객을 구분하기 위한 코드 + //- 기존고객코드 : EG01, EG05(구버젼 IBM tr id) + //- EG01,EG05를 제외하고는 모두 신규고객(Space처리) + //compileField(1, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[1]); + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문기능을 나타내는 코드 ('0600'/'0610') + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 : 전문의 처리결과를 나타내는 코드로 REQUEST전문에는 '0' 을 SET 하며 + //RESPONSE 전문에는 해당내용을 SET 한다. + //'000' = 정상 '310' = 송신자 계정오류 '001' = 송신집계오류 + //'320' = 송신자 ID 오류 '330' = 송신자 PSWD오류 '010' = NUMERIC오류 + //'340' = 수신자계정오류 '350' = 수산자 ID오류 '999' = 기타오류 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //고객코드 - 현재 space 처리 + compileField(4, "", this.al_FieldProps[4]); + + //SOURCE ACCOUNT - 본인의 그룹 ID + compileField(5, telegramInfo.getProperty(TelegramKeys.SSNET_GROUP_ID), this.al_FieldProps[5]); + + //SOURCE USER-ID - 본인의 ID + compileField(6, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[6]); + + //SOURCE PASSOWRD - 본인의 PASSWORD + compileField(7, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[7]); + + //DEST ACCOUNT - 상대방 그룹 ID + compileField(8, jobInfo.getProperty(TelegramKeys.SSNET_GROUP_ID), this.al_FieldProps[8]); + + //DEST USER-ID - 상대방 ID + compileField(9, jobInfo.getProperty(TelegramKeys.SSNET_USER_ID), this.al_FieldProps[9]); + + //DEST TYPE - 수신자 TYPE(무조건 'D'를 입력) + compileField(10, TelegramKeys.SSNET_DEST_TYPE, this.al_FieldProps[10]); + + //USER MSG CLASS + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)) { + compileField(11, jobInfo.getProperty(TelegramKeys.SSNET_SEND_MSG_ID), this.al_FieldProps[11]); + }else{ + compileField(11, jobInfo.getProperty(TelegramKeys.SSNET_RECV_MSG_ID), this.al_FieldProps[11]); + } + + //업무관리정보 - '001' = 업무개시 '002' = 파일 수신요구 '003' = 업무종료 '310' = 업무장애 회복확인 + compileField(12, this.getFldOpCode(), this.al_FieldProps[12]); + + //송신집계내역 - 송신한 마지막 0320전문의 일련번호, + compileField(13, "" + batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[13]); + + //# ARCHIVE REF-ID 수신요구 SETTING(사용않함 → Space) + compileField(14, "", this.al_FieldProps[14]); + + //# ARCHIVE 요구표시 ARCHIVE 수신요구시 'Y'로 SETTING(사용않함→Space) + compileField(15, "", this.al_FieldProps[15]); + + //# MSG QUE 조회요구 MSG QUE 조회요구시 'Y'로 SETTING(사용않함→Space) + compileField(16, "", this.al_FieldProps[16]); + + //# MSG CANCEL 요구 MSG CANCEL 조회요구시 'Y'로 SETTING(사용않함→Space) + compileField(17, "", this.al_FieldProps[17]); + + //# GROUP 등록요구 GROUP 등록요구시 'Y'로 SETTING(사용않함→Space) + compileField(18, "", this.al_FieldProps[18]); + + //Code 변환 여부 표시 - 코드변환시 'A', 미변환 송수신시 'E'로 SETTING + String codeConv = TelegramKeys.SSNET_CODE_CONV_DEFAULT; + if ( jobInfo.getProperty(TelegramKeys.SSNET_CODE_CONV_OPT)!= null && + !jobInfo.getProperty(TelegramKeys.SSNET_CODE_CONV_OPT).equals("") ){ + codeConv = jobInfo.getProperty(TelegramKeys.SSNET_CODE_CONV_OPT); + } + compileField(19, codeConv, this.al_FieldProps[19]); + + //결번 Check 간격 - 전문 몇건마다 결번 체크할 것인지 결정 (예:100건마다 -> '100'), + //최대 999,100건 이하는 반드시 앞자리에 0을 표시(예: 050, 020) + //※ 70 이하의 값을 권장함 + compileField(20, "" + batchDoc.getBatchMsg().getHeader().getBlockSize(), this.al_FieldProps[20]); + + //고객 시스템 TRAN-ID - 고객시스템의 TRANS-ID를 SETTING + compileField(21, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[21]); + + //결번 CHK요구표시 - 'Y'(고정값) + compileField(22, TelegramKeys.SSNET_MISS_CHK_REQ, this.al_FieldProps[22]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + createFile(); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fldLen = getCalculatedLength(idx); + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 7; + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean createFile() + { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(file); + + batchDoc.getBatchMsg().getHeader().setFileSize(file.length()); + logger.info("{} File [" + file.getName() + "] Size =" + file.length(), logHeader); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} + diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0610.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0610.java new file mode 100644 index 0000000..55f333b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0610.java @@ -0,0 +1,295 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SSNBT_0610 extends DefaultTelegram implements TelegramService +{ + + private Properties jobInfo; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + /** + * 생성자 + */ + public SEND_SSNBT_0610() { + //LOGIN 요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 - 아데나 장비와 TCP통신을 위한 전문길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + //- 신/구 고객을 구분하기 위한 코드 + //- 기존고객코드 : EG01, EG05(구버젼 IBM tr id) + //- EG01,EG05를 제외하고는 모두 신규고객(Space처리) + //compileField(1, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[1]); + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문기능을 나타내는 코드 ('0600'/'0610') + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 : 전문의 처리결과를 나타내는 코드로 REQUEST전문에는 '0' 을 SET 하며 + //RESPONSE 전문에는 해당내용을 SET 한다. + //'000' = 정상 '310' = 송신자 계정오류 '001' = 송신집계오류 + //'320' = 송신자 ID 오류 '330' = 송신자 PSWD오류 '010' = NUMERIC오류 + //'340' = 수신자계정오류 '350' = 수산자 ID오류 '999' = 기타오류 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //고객코드 - 현재 space 처리 + compileField(4, "", this.al_FieldProps[4]); + + //SOURCE ACCOUNT - 본인의 그룹 ID + compileField(5, batchDoc.getBatchMsg().getBody().getRecvFld05(), this.al_FieldProps[5]); + + //SOURCE USER-ID - 본인의 ID + compileField(6, batchDoc.getBatchMsg().getBody().getRecvFld06(), this.al_FieldProps[6]); + + //SOURCE PASSOWRD - 본인의 PASSWORD + compileField(7, batchDoc.getBatchMsg().getBody().getRecvFld07(), this.al_FieldProps[7]); + + //DEST ACCOUNT - 상대방 그룹 ID + compileField(8, batchDoc.getBatchMsg().getBody().getRecvFld08(), this.al_FieldProps[8]); + + //DEST USER-ID - 상대방 ID + compileField(9, batchDoc.getBatchMsg().getBody().getRecvFld09(), this.al_FieldProps[9]); + + //DEST TYPE - 수신자 TYPE(무조건 'D'를 입력) + compileField(10, TelegramKeys.SSNET_DEST_TYPE, this.al_FieldProps[10]); + + //USER MSG CLASS + //compileField(11, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[11]); + compileField(11, "", this.al_FieldProps[11]); + + //업무관리정보 - '001' = 업무개시 '002' = 파일 수신요구 '003' = 업무종료 '310' = 업무장애 회복확인 + compileField(12, this.getFldOpCode(), this.al_FieldProps[12]); + + //송신집계내역 - 송신한 마지막 0320전문의 일련번호, + compileField(13, "" + batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[13]); + + //# ARCHIVE REF-ID 수신요구 SETTING(사용않함 → Space) + compileField(14, "", this.al_FieldProps[14]); + + //# ARCHIVE 요구표시 ARCHIVE 수신요구시 'Y'로 SETTING(사용않함→Space) + compileField(15, "", this.al_FieldProps[15]); + + //# MSG QUE 조회요구 MSG QUE 조회요구시 'Y'로 SETTING(사용않함→Space) + compileField(16, "", this.al_FieldProps[16]); + + //# MSG CANCEL 요구 MSG CANCEL 조회요구시 'Y'로 SETTING(사용않함→Space) + compileField(17, "", this.al_FieldProps[17]); + + //# GROUP 등록요구 GROUP 등록요구시 'Y'로 SETTING(사용않함→Space) + compileField(18, "", this.al_FieldProps[18]); + + //Code 변환 여부 표시 - 코드변환시 'A', 미변환 송수신시 'E'로 SETTING + String codeConv = TelegramKeys.SSNET_CODE_CONV_DEFAULT; + if ( jobInfo.getProperty(TelegramKeys.SSNET_CODE_CONV_OPT)!= null && + !jobInfo.getProperty(TelegramKeys.SSNET_CODE_CONV_OPT).equals("") ){ + codeConv = jobInfo.getProperty(TelegramKeys.SSNET_CODE_CONV_OPT); + } + compileField(19, codeConv, this.al_FieldProps[19]); + + //결번 Check 간격 - 전문 몇건마다 결번 체크할 것인지 결정 (예:100건마다 -> '100'), + //최대 999,100건 이하는 반드시 앞자리에 0을 표시(예: 050, 020) + //※ 70 이하의 값을 권장함 + compileField(20, "" + batchDoc.getBatchMsg().getHeader().getBlockSize(), this.al_FieldProps[20]); + + //고객 시스템 TRAN-ID - 고객시스템의 TRANS-ID를 SETTING + compileField(21, "", this.al_FieldProps[21]); + + //결번 CHK요구표시 - 'Y'(고정값) + compileField(22, TelegramKeys.SSNET_MISS_CHK_REQ, this.al_FieldProps[22]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + return REAL_SEND_LENGTH; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + jobInfo = getJobInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < 8) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fldLen = getCalculatedLength(idx); + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 7; + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0620.java b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0620.java new file mode 100644 index 0000000..4d63b78 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/ssnet/SEND_SSNBT_0620.java @@ -0,0 +1,352 @@ +package com.eactive.eai.batch.job.jobItem.ssnet; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_SSNBT_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + /** + * 생성자 + */ + public SEND_SSNBT_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE) ) { + result = saveToFile(); + } + if (!result) return false; + + //전송길이 - 아데나 장비와 TCP통신을 위한 전문길이 필드 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //TRANSACTION CODE + //- 신/구 고객을 구분하기 위한 코드 + //- 기존고객코드 : EG01, EG05(구버젼 IBM tr id) + //- EG01,EG05를 제외하고는 모두 신규고객(Space처리) + //compileField(1, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[1]); + compileField(1, "", this.al_FieldProps[1]); + + //전문종별코드. 전문기능을 나타내는 코드 ('0600'/'0610') + compileField(2, this.getFldTelegramType(), this.al_FieldProps[2]); + + //응답코드 : 전문의 처리결과를 나타내는 코드로 REQUEST전문에는 '0' 을 SET 하며 + //RESPONSE 전문에는 해당내용을 SET 한다. + //'000' = 정상 '310' = 송신자 계정오류 '001' = 송신집계오류 + //'320' = 송신자 ID 오류 '330' = 송신자 PSWD오류 '010' = NUMERIC오류 + //'340' = 수신자계정오류 '350' = 수산자 ID오류 '999' = 기타오류 + compileField(3, this.getResolveResponseCode(), this.al_FieldProps[3]); + + //고객코드 - 현재 space 처리 + compileField(4, "", this.al_FieldProps[4]); + + //최종일련번호 - 결번전문 확인요구 및 완료시 SET 함 + compileField(5, "" + batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[5]); + + //전문내용구분코드 - 'C' : 결번전문확인 요구 전문 + // 'E' : 결번 확인 완료(결번이 없을때) + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) ) { + compileField(6, TelegramKeys.SSNET_MISS_REQ, this.al_FieldProps[6]); + }else{ + compileField(6, TelegramKeys.SSNET_MISS_RES, this.al_FieldProps[6]); + } + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<5; i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=5; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(this.al_Field.size()-1); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean saveToFile() { + + // 기 처리 완료된 시퀀스를 저장하여야 하는데 삼성네트웍스 프로토콜에서는 block 넘버가 의미 없으므로 이를 사용하도록 한다. + int lastSeq = batchDoc.getBatchMsg().getBody().getBlockNum(); + FileOutputStream fout = null; + + if ( lastSeq == 0) + fout = createFile(false); + else + fout = createFile(true); + + if ( fout == null) { + return false; + } + + try { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = Integer.parseInt(batchDoc.getBatchMsg().getBody().getRecvFld05()); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + try { + String strRecvLen = getJobInfo().getProperty(TelegramKeys.RECV_REC_LEN); + recLen = Integer.parseInt(strRecvLen); + } catch (Exception e) {} + + for (int i = lastSeq + 1; i <= seq_no; i++) { //받은 seq_no만큼만 데이터 확인하여 기록 + byte[] data = (byte[]) block_data.get(new Integer(i-1)); + + if ( recLen < 1 ){ + recLen = data.length; + } + byte[]layout = new byte[recLen]; + for (int inx = 0; inx < layout.length; inx++) { + layout[inx] = ' '; + } + + int dataCnt = data.length / recLen ; + for (int jnx = 0; jnx < dataCnt; jnx++) { + System.arraycopy( data,jnx*layout.length,layout,0,layout.length); + fout.write(layout); + fout.write( '\n' ); + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+recLen; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + batchDoc.getBatchMsg().getHeader().setFileSize(lnCurSize); + long totRecCnt = batchDoc.getBatchMsg().getHeader().getTotRecCnt(); + if ( totRecCnt == -1 ) + totRecCnt = 0; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(++totRecCnt); + } + + } + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); //데이터 기록후 Vector 초기화 + batchDoc.getBatchMsg().getBody().setBlockNum(seq_no); + + return true; + + } catch (Exception e) { + logger.error( e.getMessage(), e); + return false; + }finally{ + try { + fout.close(); + } catch (Exception e2) { + logger.error( e2.getMessage(), e2); + } + } + + } + + private FileOutputStream createFile (boolean append) { + try { + String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + return new FileOutputStream(file, append); + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return null; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return 84; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + for (int inx = 0; inx < fldLen; inx++) { + data[inx] = ' '; + } + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(2); + } + + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(3); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD.java new file mode 100644 index 0000000..89f1b6d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD.java @@ -0,0 +1,77 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_WELCD extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 : 복지카드 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_WELCD() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + idx = vo.getLengthField(); + if (idx == 0) return -1; + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=idx; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(2)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=0; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// SchedulerMessageVO info; +// try{ +// info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); +// if ( info == null ) { +// return; +// } +// LogUtil.setLogFileEnd(batchDoc); +// String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); +// String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); +// +// //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 +// SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); +// +// //BatchMsgDoc 값 설정 +// batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); +// batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); +// batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); +// batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); +// batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); +// batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); +// // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. +// //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); +// batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); +// batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); +// batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); +// batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); +// batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); +// batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); +// batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); +// batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); +// batchDoc.getBatchMsg().getHeader().setFileSize(0); +// batchDoc.getBatchMsg().getBody().setCurFileSize(0); +// this.setConditionTxt(TelegramKeys.EOF); +// +// } catch ( Exception e){} + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0310.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0310.java new file mode 100644 index 0000000..a49279e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0310.java @@ -0,0 +1,244 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_WELCD_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_WELCD_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(2)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=0; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0320.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0320.java new file mode 100644 index 0000000..07112c5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0320.java @@ -0,0 +1,231 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_WELCD_0320 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 12; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_WELCD_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_seq_no = Integer.parseInt(_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(2)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=0; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0600.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0600.java new file mode 100644 index 0000000..c249c69 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0600.java @@ -0,0 +1,195 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_WELCD_0600 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + private Properties telegramInfo; + + /** + * 생성자 + */ + public RECV_WELCD_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + // 거래구분코드(송수신 구분 코드) 체크 + String recvTrGbCd = getFieldValueString(5); + if ( telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND).equals(recvTrGbCd)){ + logger.info("{} BATCH JOB : send request received", logHeader); + batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND); + checkFileinDB(getFieldValueString(7)); + }else if ( telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV).equals(recvTrGbCd)){ + logger.info("{} BATCH JOB : recv request received", logHeader); + setConditionTxt(TelegramKeys.RECV); + batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE); + }else{ + logger.info("{} BATCH JOB : send/recv request error", logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_FORMAT_ERROR); + setConditionTxt(TelegramKeys.ERROR); + } + + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + batchDoc.getBatchMsg().getHeader().setTRXID(new String(this.al_Field.get(0))); + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + private void checkFileinDB(String fileName){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode, fileName ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + return; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + String hdrInfoName = info.getHdrInfoName(); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt()); + this.setConditionTxt(TelegramKeys.SEND); + LogUtil.updateLogMaster(batchDoc); + } catch ( Exception e){} + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0610.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0610.java new file mode 100644 index 0000000..b12e554 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0610.java @@ -0,0 +1,127 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_WELCD_0610 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_WELCD_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + if (OpCode_noexsist.equals(this.getOpCode()) && fileNm != null && !fileNm.trim().equals("")) { + //응답수신 파일 Start DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0620.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0620.java new file mode 100644 index 0000000..9686ed2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0620.java @@ -0,0 +1,120 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_WELCD_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_WELCD_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(9)); + String _seq_no = new String ((byte[]) al_Field.get(10)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0630.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0630.java new file mode 100644 index 0000000..8ef95a9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0630.java @@ -0,0 +1,174 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_WELCD_0630 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_WELCD_0630() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try{ + String fileInfo = new String ((byte[]) al_Field.get(9)); + String fName = fileInfo.substring(0, 8).trim(); + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + int fByte = Integer.parseInt(fileInfo.substring(20, 24)); //전문 바이트 수 + + //TelegramKeys.DATA_BYTE_SIZE는 한번에 파일에서 읽어와 전송할 데이터의 크기 + if (fByte < batchDoc.getBatchMsg().getHeader().getSequenceSize()) { + //630전문과 640전문의 byte수를 비교하여 작은 값을 설정. + batchDoc.getBatchMsg().getHeader().setSequenceSize(fByte); + } + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_CDCMS_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + } + + String pattern = null; + long recLen = 0; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + } + + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getHeader().setFileSize(fSize); + long recCnt = 0; + if ( recLen > 0 ){ + recCnt = fSize / recLen; + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0640.java b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0640.java new file mode 100644 index 0000000..cea5d28 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/RECV_WELCD_0640.java @@ -0,0 +1,176 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_WELCD_0640 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_WELCD_0640() { + //화일정보수신통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String fileInfo = new String ((byte[]) al_Field.get(9)); // 화일정보내역 + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + int fByte = Integer.parseInt(fileInfo.substring(20, 24)); //전문 바이트 수 + + //TelegramKeys.DATA_BYTE_SIZE는 한번에 파일에서 읽어와 전송할 데이터의 크기 + if (fByte > 0 && fByte < batchDoc.getBatchMsg().getHeader().getSequenceSize()) { + //630전문과 640전문의 byte수를 비교하여 작은 값을 설정. + batchDoc.getBatchMsg().getHeader().setSequenceSize(fByte); + } + + if (getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_ALREADY_RECEIVED) + ||getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_NOT_REGISTERED)) { //기송신 파일이면 + checkMoreFileinDB(); + } else { + + if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면 + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkMoreFileinDB(){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + String hdrInfoName = info.getHdrInfoName(); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt()); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + logger.error( e.getMessage(), e); + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0300.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0300.java new file mode 100644 index 0000000..6adab6d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0300.java @@ -0,0 +1,395 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_WELCD_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //TRANSACTION CODE + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + //최종 SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //결번갯수 + compileField(11, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + String jobCode = this.batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return MISSING_FIELD.length(); + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0310.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0310.java new file mode 100644 index 0000000..311b7bd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0310.java @@ -0,0 +1,266 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_WELCD_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //TRANSACTION CODE + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug( logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0320.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0320.java new file mode 100644 index 0000000..2b43b2a --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0320.java @@ -0,0 +1,421 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0320 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_WELCD_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //TRANSACTION CODE + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //BLOCK-NO + compileField(9, ""+BLOCK_NO, this.al_FieldProps[9]); + //SEQUENCE-NO + compileField(10, ""+SEQUENCE_NO, this.al_FieldProps[10]); + //실 DATA BYTE 수 + compileField(11, ""+REAL_BYTE, this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID()); + if( fin != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + if ( isLastSeq ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0600.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0600.java new file mode 100644 index 0000000..ba5bf51 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0600.java @@ -0,0 +1,212 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_WELCD_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + + //TRANSACTION CODE + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE) ){ + batchDoc.getBatchMsg().getHeader().setTRXID(telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE)); + } + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode()) > -1){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 + compileField(11, "", this.al_FieldProps[11]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0610.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0610.java new file mode 100644 index 0000000..b724ee9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0610.java @@ -0,0 +1,260 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_WELCD_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //TRANSACTION CODE + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode()) > -1){ + compileField(7, "", this.al_FieldProps[7]); + } else { + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + } + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //전문 전송 일시 (MMddhhmmss) + compileField(9, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[9]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(10, this.getFldOpCode(), this.al_FieldProps[10]); + + //송신자명 + compileField(11, "", this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if ("001|004".indexOf(this.getFldOpCode()) > -1) return true; + + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(10); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0620.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0620.java new file mode 100644 index 0000000..50cb78d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0620.java @@ -0,0 +1,201 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_WELCD_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //TRANSACTION CODE + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //BLOCK-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[9]); + + //최종 SEQUENCE-NO + compileField(10, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0630.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0630.java new file mode 100644 index 0000000..2794722 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0630.java @@ -0,0 +1,224 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0630 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_WELCD_0630() { + //화일정보수신요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + int seqSize = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ) * batchDoc.getBatchMsg().getHeader().getRecLen(); + + //TRANSACTION CODE + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( fileName.indexOf("_") > -1 ){ + fileName = fileName.substring(0, fileName.indexOf("_")); + } + compileField(7, fileName , this.al_FieldProps[7]); + + //응답코드 + compileField(8, this.getResolveResponseCode(), this.al_FieldProps[8]); + + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(fileName, 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12)); + // 0630 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + fileInfo.append(makeZero(""+(SEND_LENGTH + seqSize - 13), 4)); + + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + String jobCode = batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setBizCode(bjvo.getJobTranDstcd()); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + String hdrInfoName = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt()); + } catch (Exception e) {} + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0640.java b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0640.java new file mode 100644 index 0000000..b431746 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/welcd/SEND_WELCD_0640.java @@ -0,0 +1,250 @@ +package com.eactive.eai.batch.job.jobItem.welcd; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_WELCD_0640 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_WELCD_0640() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //TRANSACTION CODE + compileField(0, batchDoc.getBatchMsg().getHeader().getTRXID(), this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //전송길이 + compileField(2, "" + REAL_SEND_LENGTH, this.al_FieldProps[2]); + + //기관코드 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드CARD송신업무"S", CARD수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[5]); + }else{ + compileField(5, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[5]); + } + + //송수신 FLAG 전문발생기관 (B:e-제너두, C:Card) + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[6]); + + //화일명 + compileField(7, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[7]); + //응답코드 + compileField(8, this.getSendResponseCode(), this.al_FieldProps[8]); + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(makeSpace(batchDoc.getBatchMsg().getHeader().getFileName(), 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getBody().getCurFileSize(),12)); + fileInfo.append(makeZero(""+calculateTelegramSize(), 4)); + compileField(9, fileInfo.toString(), this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + //해당 거래구분에 대한 Job_Code 값 설정 + //거래구분코드 조회 BizCode 조회 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + if (info != null) { + batchDoc.getBatchMsg().getHeader().setJobCode(info.getMsgDstCode());; + } else { + logger.debug("{} " + batchDoc.getBatchMsg().getHeader().getUUID()+ "'s Job Code is null", logHeader); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + batchDoc.getBatchMsg().getHeader().setJobCode((processCode+"00000")); //dummy code + // TEST 용 return false; + } + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) {} + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<9; i++) { //CMS전문의 헤더는 응답코드까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=9; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=3; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + for (int i=0; i< 3; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + REAL_SEND_LENGTH += aField.length; + } + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private int calculateTelegramSize(){ + int recSize = 200; + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo != null && bJobInfo.getFileRecSize() > 0 ){ + recSize = (int)Math.min(bJobInfo.getFileRecSize(), 4000); + } + + // 0630/0640 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630/0640 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + return (batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize) * recSize + SEND_LENGTH - 13; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(5); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(8); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01.java b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01.java new file mode 100644 index 0000000..1b65136 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01.java @@ -0,0 +1,146 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_LDB01 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 : 우리투자증권 지역개발공채 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_LDB01() { + } + + public boolean doExecute() { + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + if ( super.getFieldValueString(4).equalsIgnoreCase("0600") ||super.getFieldValueString(4).equalsIgnoreCase("0610") ){ + return super.getFieldValueString(12); + } + else { + return super.getOpCode(); + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + + idx = vo.getLengthField(); + if (idx == 0) return -1; + + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=1; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // HashMap 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( idx == 1 ){ + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = getCalculatedLength(1); + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //우리투자증권 지역개발공채 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkFileEOF() { + if ( batchDoc.getBatchMsg().getBody().getCurFileSize() + + batchDoc.getBatchMsg().getHeader().getRecLen() + >= batchDoc.getBatchMsg().getHeader().getFileSize() ){ + this.setConditionTxt(TelegramKeys.EOF); + } + return; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0310.java b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0310.java new file mode 100644 index 0000000..ebf22e0 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0310.java @@ -0,0 +1,250 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LDB01_0310 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 14; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_LDB01_0310() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(11)); + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (((recv_block_no - block_no) > 1 ) || ((recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + + return false; + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + batchDoc.getBatchMsg().getHeader().setRecLen(Integer.parseInt(super.getFieldValueString(9))); + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //우리투자증권 지역개발공채 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + if ( idx == 1 ){ + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = getCalculatedLength(1); + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0320.java b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0320.java new file mode 100644 index 0000000..7f1b5b2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0320.java @@ -0,0 +1,384 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LDB01_0320 extends DefaultTelegram implements TelegramService { + private int INFORMALFIELD_INDEX = 14; + private ByteArrayOutputStream bout; + private File file; + private FileOutputStream fout; + private String strFullPath = ""; + + /** + * 생성자 + */ + public RECV_LDB01_0320() { + //DATA 수신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + String fName = new String ((byte[]) al_Field.get(5)); + String baseDate = new String ((byte[]) al_Field.get(8)); + batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate); + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + String pattern = null; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc); + batchDoc.getBatchMsg().getHeader().setFileName(recvFileName); + + String _block_no = new String ((byte[]) al_Field.get(11)); + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if (( recv_block_no != 9999 ) && ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 )) { + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + + } + + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + batchDoc.getBatchMsg().getHeader().setRecLen(Integer.parseInt(super.getFieldValueString(9))); + if ( recv_block_no == 0 || recv_block_no == 9999) { + if (!createFile(recv_block_no == 0)) { + return false; + } + if (recv_block_no == 9999) { + this.setConditionTxt(TelegramKeys.EOF); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + + String _block_no = new String ((byte[]) al_Field.get(11)); + String _seq_no = new String ((byte[]) al_Field.get(12)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] newLine = new byte[1]; + newLine[0] = '\n'; + + if ( recv_block_no == 0 ){ // 받은 데이터가 헤더 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileHeader(new String(bout.toByteArray())); + } else if ( recv_block_no == 9999 ) { // 받은 데이터가 트레일러 이면 + fout.write( bout.toByteArray() ); + fout.write(newLine); + fout.close(); + batchDoc.getBatchMsg().setFileTrailer(new String(bout.toByteArray())); + + if ( !moveFile()) + return false; + + } else if (recv_block_no > 0){ +// } else if ( ( recv_block_no > 0) && (recv_seq_no > 1) ){ // 강제 결번 테스트용 + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //우리투자증권 지역개발공채 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + if ( idx == 1 ){ + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = getCalculatedLength(1); + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + private boolean createFile ( boolean init) { + try { + strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath(); + if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) { + strFullPath = strFullPath + File.separator; + } + strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName(); + logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, !init); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private boolean moveFile() throws Exception{ + + //DB로그에 남길 파일 사이즈 설정 + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getBody().getCurFileSize()); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recLen > 0 ){ + int recCnt = (int)batchDoc.getBatchMsg().getBody().getCurFileSize()/recLen; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + } + + File rcvArchFile = new File( StringUtil.realToArchDir(this.strFullPath) ); + File rcvErrorFile = new File( StringUtil.realToErrorDir(this.strFullPath) ); + + //응답코드가 000 (성공) 이 아니면 Error 디렉토리로 옮기고 리턴 + if ( !super.getResolveResponseCode().equals(TelegramKeys.KFB_RET_CODE_SUCCESS) ) { + // 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvErrorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) { + errMsg += "\n caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg(); + } + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}] + } + return false; + } + + //3. 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = file.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {file.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + return false; + } + + //4-1. 수신 Root 디렉토리에 동일 파일명의 0 byte 의 Dummy 파일 생성 + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(호스트에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + File rcvRootFile = new File( StringUtil.realToRootDir(this.strFullPath) ); + rcvRootFile.createNewFile(); + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(this.strFullPath) }); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + return false; + } + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0330.java b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0330.java new file mode 100644 index 0000000..ba4c43d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0330.java @@ -0,0 +1,222 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + + +public class RECV_LDB01_0330 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_LDB01_0330() { + //HEADER/TRAILER 수신 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + //업무관리정보 유효성 확인 + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //우리투자증권 지역개발공채 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if( super.getFieldValueString(11).equals( "0000") ) { + LogUtil.setLogFileStart(batchDoc); + if ( batchDoc.getBatchMsg().getHeader().getTotRecCnt() <= 2 ){ + this.setConditionTxt(TelegramKeys.NOBODY); + } + } else if (super.getFieldValueString(11).equals( "9999")) { + LogUtil.setLogFileEnd(batchDoc); + this.setConditionTxt(TelegramKeys.NOFILE); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + if ( idx == 1 ){ + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = getCalculatedLength(1); + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + /* + private boolean checkMoreFile(){ + return false; + String processCode = batchDoc.getEAIBatchMessage().getHeader().getProcessCode(); + String institutionCode = batchDoc.getEAIBatchMessage().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return false; + } + String strUUID = batchDoc.getEAIBatchMessage().getHeader().getUUID(); + String strSubUUID = batchDoc.getEAIBatchMessage().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + logger.debug("UUID추적:[ScheduleHandlerProcess]:uuid["+info.getUUID() +"]"); + logger.debug("UUID추적:[ScheduleHandlerProcess]:subuuid["+info.getSubUUID() +"]"); + + //BatchMsgDoc 값 설정 + batchDoc.getEAIBatchMessage().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getEAIBatchMessage().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getEAIBatchMessage().getHeader().setFilePath(info.getFilePath()); + batchDoc.getEAIBatchMessage().getHeader().setFileName(info.getFileName()); + batchDoc.getEAIBatchMessage().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getEAIBatchMessage().getHeader().setJobCode(info.getJobCode()); + batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getEAIBatchMessage().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getEAIBatchMessage().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getEAIBatchMessage().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getEAIBatchMessage().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getEAIBatchMessage().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getEAIBatchMessage().getHeader().setUserPassword(info.getRemoteUserPW()); + + + + } catch ( Exception e){ + return false; + + } + return true; + } + */ + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0600.java b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0600.java new file mode 100644 index 0000000..8e55d8b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0600.java @@ -0,0 +1,197 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LDB01_0600 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_snd_req = "008"; //송신시작요구 + private final String OpCode_chk_down = "301"; //업무 장애 회복 확인 + + /** + * 생성자 + */ + public RECV_LDB01_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_snd_req)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_chk_down)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.KFB_RET_CODE_TGRAM_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //우리투자증권 지역개발공채 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + if ( idx == 1 ){ + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = getCalculatedLength(1); + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0610.java b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0610.java new file mode 100644 index 0000000..5e1c554 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0610.java @@ -0,0 +1,196 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LDB01_0610 extends DefaultTelegram implements TelegramService { + + //>> 업무관리정보 + private final String OpCode_start = "001"; //개별 업무 개시 + private final String OpCode_resume = "002"; //파일 송수신 계속 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private final String OpCode_snd_req = "008"; //송신시작요구 + private final String OpCode_chk_down = "301"; //업무 장애 회복 확인 + + /** + * 생성자 + */ + public RECV_LDB01_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_resume)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_unit_end)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_snd_req)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_chk_down)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.KFB_RET_CODE_TGRAM_CODE_ERROR); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + //응답 전문을 수신한 경우에만 return false + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //우리투자증권 지역개발공채 전문의 헤더는 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + if ( idx == 1 ){ + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = getCalculatedLength(1); + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0620.java b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0620.java new file mode 100644 index 0000000..0cc814f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/RECV_LDB01_0620.java @@ -0,0 +1,194 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.common.exception.ExceptionUtil; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +public class RECV_LDB01_0620 extends DefaultTelegram implements TelegramService { + + /** + * 생성자 + */ + public RECV_LDB01_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + + try { + + String _block_no = new String ((byte[]) al_Field.get(11)); // 0 base 인덱스 + String _seq_no = new String ((byte[]) al_Field.get(12)); // 0 base 인덱스 + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return false; + } + // 두번째 결번확인 전문을 받은 경우에는 SeqNum 을 다시 세팅해줘야 한다. + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //우리투자증권 지역개발공채 전문의 헤더는 업무별 레코드 길이까지 임. + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + if ( idx == 1 ){ + try { + return Integer.parseInt( getTelegramInfo().getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + String byte_size = new String ((byte[]) al_Field.get(0)); //실 DATA Byte수 + logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader); + int preLen = getCalculatedLength(1); + for (int inx = 2; inx < idx; inx++) { + byte[] aField = (byte[]) this.al_Field.get(inx); + preLen += aField.length; + } + return Integer.parseInt(byte_size) - preLen; + } + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + + } else { + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0300.java b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0300.java new file mode 100644 index 0000000..845532f --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0300.java @@ -0,0 +1,429 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LDB01_0300 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private File file; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_LDB01_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. +// compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + // --받은 내용을 그대로 돌려 보내기 + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[12]); + + //결번갯수 + compileField(13, ""+MISSING_COUNT, this.al_FieldProps[11]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( idx == 1 ){ + try { + return Integer.parseInt( telegramInfo.getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + return MISSING_FIELD.length(); + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * return value : 0 no left data to be sent + * -1 error + * >0 data copied to the data field + * + * 비정형 필드인 결번확인의 데이터를 얻어낸다. + * 결번확인 데이터를 실어주고 결번확인 필드의 길이를 반환한다. + */ + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < MISSING_FIELD.length()) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( idx == 1 ){ + int fldLen = getCalculatedLength(idx); + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(1); + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = seq_no; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0310.java b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0310.java new file mode 100644 index 0000000..4e59ef6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0310.java @@ -0,0 +1,365 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LDB01_0310 extends DefaultTelegram implements TelegramService { + + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_LDB01_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. +// compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+SEQUENCE_NO , this.al_FieldProps[12]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(13, "" + recCnt, this.al_FieldProps[13]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( idx == 1 ){ + int fldLen = getCalculatedLength(idx); + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( idx == 1 ){ + try { + return Integer.parseInt( telegramInfo.getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + return REAL_BYTE; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + + try { + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug( logHeader + " : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + byte[] data = block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = data.length; + fileData = new byte[REAL_BYTE]; + System.arraycopy( data, 0, fileData, 0, data.length); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(1); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0320.java b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0320.java new file mode 100644 index 0000000..111a794 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0320.java @@ -0,0 +1,494 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + + +public class SEND_LDB01_0320 extends DefaultTelegram implements TelegramService { + + private FileInputStream fin; + private File file; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_LDB01_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. +// compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[12]); + + //Record 수 + int recCnt = this.REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + compileField(13, "" + recCnt, this.al_FieldProps[13]); + + int block_num = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + if ( block_num > 0 && block_num < 9999) { + batchDoc.getBatchMsg().getBody().setRecCnt( batchDoc.getBatchMsg().getBody().getRecCnt() + recCnt ); + } + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( idx == 1 ){ + int fldLen = getCalculatedLength(idx); + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + if (this.getFldOpCode().equals("999") ){ + if (fin != null ) { + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( idx == 1 ){ + try { + return Integer.parseInt( telegramInfo.getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + return REAL_BYTE; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + private boolean createFile () + { + + try { + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + + if ( fin == null) { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + } + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int sequence_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize(); + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + this.setConditionTxt(""); + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = (HashMap)job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + fileData = new byte[sequence_size + 1]; // 파일의 한 라인당 길이 + 개행문자 1바이트 + + if (this.getFldOpCode().equals("000")) { + fileData = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileHeader(new String(fileLine)); + } + else if (this.getFldOpCode().equals("999")) { + BLOCK_NO = 9999; + SEQUENCE_NO = 999; + + fileData = new byte[batchDoc.getBatchMsg().getHeader().getRecLen()]; + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy(fileLine, 0, fileData, 0, Math.min(fileLine.length, fileData.length)); + batchDoc.getBatchMsg().setFileTrailer(new String(fileLine)); + + } else { + if (block_no == 0 && seq_no == 0){ + block_no = 1; + seq_no = 1; + BLOCK_NO = 1; + SEQUENCE_NO = 1; + this.setConditionTxt(""); + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + } + + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + if ( seqCnt < remainCnt - 1){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)(remainCnt - 1) * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + block_data.put( new Integer(SEQUENCE_NO-1) , fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + REAL_BYTE = fileData.length; + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(1); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0330.java b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0330.java new file mode 100644 index 0000000..ad3b1e1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0330.java @@ -0,0 +1,332 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LDB01_0330 extends DefaultTelegram implements TelegramService { + + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private String recvTelegramBody; + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_LDB01_0330() { + // HEADER/TRAILER 수신 보고 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + recvTelegramBody = batchDoc.getBatchMsg().getTelegramBody(); + + REAL_BYTE = recvTelegramBody.length() - 11; + + boolean result = calculateSendLength(); + if (!result) return false; + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. +// compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + // --받은 내용을 그대로 돌려 보내기 + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[12]); + + //Record 수 --받은 내용을 그대로 돌려 보내기 + compileField(13, recvTelegramBody.substring(8,11), this.al_FieldProps[13]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + String _block_no = new String ((byte[]) al_Field.get(11)); + int recv_block_no = Integer.parseInt(_block_no); + + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+ REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + if( recv_block_no == 0 ) { + LogUtil.setLogFileStart(batchDoc); + } else if ( recv_block_no == 9999 ) { + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getBody().getCurFileSize()); + int recLen = batchDoc.getBatchMsg().getHeader().getRecLen(); + if ( recLen > 0 ){ + int recCnt = (int)batchDoc.getBatchMsg().getBody().getCurFileSize()/recLen; + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + } + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + if ( idx == 1 ){ + try { + return Integer.parseInt( telegramInfo.getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + }else{ + return REAL_BYTE; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(1); + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < REAL_BYTE) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if ( idx == 1 ){ + int fldLen = getCalculatedLength(idx); + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + return fldLen; + } + + System.arraycopy(recvTelegramBody.getBytes(), 11, data, 0, REAL_BYTE ); + + return REAL_BYTE; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0600.java b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0600.java new file mode 100644 index 0000000..b5557cd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0600.java @@ -0,0 +1,306 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LDB01_0600 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + //>> 업무관리정보 + private final String OpCode_unit_end = "003"; //개별업무 종료 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_LDB01_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. +// compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(11, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[11]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송수신 계속 + // “003”: 개별 업무 종료 “008”: 송신 시작 요구 + // “301”: 업무 장애 회복 확인 + compileField(12, this.getFldOpCode(), this.al_FieldProps[12]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(13, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[13]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(14, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[14]); + + //송신 집계 내역 - 개별업무 종료(0600/003)시만 사용하는 Field로 전송된 Record Count를 Set한다. + if ( this.getFldOpCode().equalsIgnoreCase(OpCode_unit_end) ) + compileField(15, "" + batchDoc.getBatchMsg().getBody().getRecCnt(), this.al_FieldProps[15]); + else + compileField(15, "" ,this.al_FieldProps[15]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + + if (CommonKeys.PROCESS_REQUEST_RECEIVE.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){ + String filename = batchDoc.getBatchMsg().getHeader().getFileName(); + if ( filename.length() == 14){ + batchDoc.getBatchMsg().getHeader().setBaseDate( filename.substring(6)); + } else { + batchDoc.getBatchMsg().getHeader().setBaseDate( TelegramKeys.getYYYYMMDD( -1 ) ); + } + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + return Integer.parseInt( telegramInfo.getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(1); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fldLen = getCalculatedLength(idx); + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0610.java b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0610.java new file mode 100644 index 0000000..1ef709c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0610.java @@ -0,0 +1,291 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LDB01_0610 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_LDB01_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. +// compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+SEND_LENGTH, this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //전문 전송 일시 - 전문을 발신하는 기관에서 전문을 전송하는 일자와 시간을 Set한다. + compileField(11, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[11]); + + //업무 관리 정보 - 파일전송업무 관리를 위한 정보로 아래의 값 중 하나를 Set 한다. + // “001”: 개별 업무 개시 “002”: 파일 송?수신 계속 + // “003”: 개별 업무 종료 “008”: 송신 시작 요구 + // “301”: 업무 장애 회복 확인 + compileField(12, this.getFldOpCode(), this.al_FieldProps[12]); + + //송신자명 파일전송업무의 책임이 있는 사람의 나타내는 ID를 Set한다. + compileField(13, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[13]); + + //송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호 + compileField(14, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[14]); + + //송신 집계 내역 - 개별업무 종료(0600/003)시만 사용하는 Field로 전송된 Record Count를 Set한다. + compileField(15, "", this.al_FieldProps[15]); + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + return Integer.parseInt( telegramInfo.getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(1); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fldLen = getCalculatedLength(idx); + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(12); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0620.java b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0620.java new file mode 100644 index 0000000..ba3769c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/wis/SEND_LDB01_0620.java @@ -0,0 +1,281 @@ +package com.eactive.eai.batch.job.jobItem.wis; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_LDB01_0620 extends DefaultTelegram implements TelegramService { + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_LDB01_0620() { + // 결번 전문 확인 요청 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + compileField(0, ""+SEND_LENGTH, this.al_FieldProps[0]); + + // 해당 Transaction을 기동하는 코드로 본 파일전송 업무는 “KFBFTP”문자를 사용한다. +// compileField(1, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[1]); + + //업무구분코드 -업무구분을 위하여 Set하는 문자로 본 파일전송 업무에서는 “FTP”문자를 사용키로 한다. + compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]); + + //대표기관코드 - 전문관련 금융기관을 나타내는 코드로서 금융기관 공동코드 (7자리)중 상위 3자리 금융기관 대표코드를 사용한다. + // Ex) 국민: 004, 부산: 032, 농협: 011 등 + compileField(3, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[3]); + + //전문종별코드. 전문의 기능을 나타내는 구분코드로 전문종류별로 해당 전문코드를 Set하며 세부사항은 표준화 사항의 전문종별 코드를 참조한다. + compileField(4, this.getFldTelegramType(), this.al_FieldProps[4]); + + //거래구분코드 + compileField(5, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[5]); + + //송수신 FLAG 전문을 발생시킨 기관을 나타내는 코드로 아래의 값중 해당코드를 Set한다. + //“C”: 은행연합회에서 전문을 발생할 시 + //“B”: 은행에서 전문을 발생할 시 + compileField(6, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[6]); + + //응답코드 + compileField(7, TelegramKeys.KFB_RET_CODE_SUCCESS, this.al_FieldProps[7]); + + //전송기준일자 + compileField(8, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[8]); + + //업무별 Record Length -송수신을 하고자 하는 자료의 Record Length를 Set 한다. + compileField(9, ""+batchDoc.getBatchMsg().getHeader().getRecLen(), this.al_FieldProps[9]); + + //송수신 업무 구분코드. 은행연합회를 기준으로 하여 해당전문이 송수신업무 중 어느 업무에 관련된 것인지를 구분하기 위한 코드로 아래 값 중 해당코드를 Set한다. + //“S”: 파일 송신업무 관련 전문 (은행연합회 → 은행) + //“R”: 파일 수신업무 관련 전문 (은행 → 은행연합회) + compileField(10, getFldTrClass() , this.al_FieldProps[10]); + + //Block-NO + compileField(11, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum() , this.al_FieldProps[11]); + + //Sequence-NO + compileField(12, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum() , this.al_FieldProps[12]); + + //<< 전문 완성 + + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<10; i++) { //은행연합회 전문의 헤더는 레코드 길이까지 임. + byte[] barr = (byte[])this.al_Field.get(i); + if ( barr[0] != '\0') { + baout.write((byte[])this.al_Field.get(i)); + } + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=10; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다. + * + * 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다 + * + * 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요. + */ + public int getCalculatedLength(int idx) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + return Integer.parseInt( telegramInfo.getProperty(TelegramKeys.TRCD_LEN) ); + } catch (Exception e) { + logger.info(e.getMessage(), e); + return 0; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader); + return -1; + } + }catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=2; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += getCalculatedLength(1); + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + public int getInformalFieldSendData(int idx, byte[] data) { + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + int fldLen = getCalculatedLength(idx); + System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen ); + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(4); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(10); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL.java new file mode 100644 index 0000000..ae4a94d --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL.java @@ -0,0 +1,77 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager; +import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO; + +/** + * TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다. + * RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다. + */ +public class RECV_ZENEL extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 : 제니엘 길이 결정용 텔레그램 클래스 이다. + */ + public RECV_ZENEL() { + } + + public boolean doExecute() { + + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } + + /** + * 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다. + * + * return value : <0 계산 할 수 없거나 장애이다. + * >0 해당 데이터를 소켓에서 더 읽어들인다. + */ + public int getRemainDataLength() + { + try { + int idx; + String strLength; + + String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode(); + NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode); + idx = vo.getLengthField(); + if (idx == 0) return -1; + strLength = new String((byte[])this.al_Field.get(idx-1)); + int nDocLen = Integer.parseInt(strLength); + int nReceivedLen = 0; + for (int i=idx; i hm = job.getBatchStageData(uuid); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화 + } else if (recv_migging_count > 0) { + this.setConditionTxt(TelegramKeys.LOSS); + } + this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count); + this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + ByteArrayInputStream bin = new ByteArrayInputStream (data, 0, length); + byte[] xxField = new byte[length]; + bin.read(xxField, 0, length); + al_Field.set(idx, xxField); + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean checkFileEOF() { + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File realFile = new File(fileName); + if (!realFile.exists()) // 파일이 없으면 리턴 False + { + logger.debug("{} the File["+ realFile.getName() + "] does not exist!!!", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = realFile.getName(); + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + if ( batchDoc.getBatchMsg().getHeader().getFileSize() + <= batchDoc.getBatchMsg().getBody().getCurFileSize()) { + checkMoreFileinDB(); + } + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI023"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + + } + + private void checkMoreFileinDB(){ + this.setConditionTxt(TelegramKeys.NOFILE); + return; +// String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); +// String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); +// SchedulerMessageVO info; +// try{ +// info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); +// if ( info == null ) { +// this.setConditionTxt(TelegramKeys.NOFILE); +// return; +// } +// LogUtil.setLogFileEnd(batchDoc); +// String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); +// String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); +// +// //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 +// SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); +// +// //BatchMsgDoc 값 설정 +// batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); +// batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); +// batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); +// batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); +// batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); +// batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); +// batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); +// // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. +// //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); +// batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); +// batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); +// batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); +// batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); +// batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); +// batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); +// batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); +// batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); +// batchDoc.getBatchMsg().getHeader().setFileSize(0); +// batchDoc.getBatchMsg().getBody().setCurFileSize(0); +// this.setConditionTxt(TelegramKeys.EOF); +// +// } catch ( Exception e){} + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0310.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0310.java new file mode 100644 index 0000000..e2b4e86 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0310.java @@ -0,0 +1,244 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_ZENEL_0310 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_ZENEL_0310() { + //결번 DATA 송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + String missing_field = batchDoc.getBatchMsg().getBody().getMissingNmField(); +// int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + this.setConditionTxt(TelegramKeys.ERROR); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + byte[] _missing_field = missing_field.getBytes(); + if (_missing_field[recv_seq_no-1] == '0') { + _missing_field[recv_seq_no-1] = '1'; +// missingCount -= 1; + batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field)); + logger.info("{} doExecute> RECV missing telegram [" + recv_seq_no + "] missing field" + new String(_missing_field), logHeader); + } else { + logger.info("{} doExecute> recived recv_seq_no is not missing field", logHeader); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null ){ + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_seq_no = Integer.parseInt(_seq_no); + + logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader); + if (block_data.get(new Integer(recv_seq_no-1)) == null) { + block_data.put(new Integer(recv_seq_no-1), bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0320.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0320.java new file mode 100644 index 0000000..3fb2694 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0320.java @@ -0,0 +1,231 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_ZENEL_0320 extends DefaultTelegram implements TelegramService +{ + + private int INFORMALFIELD_INDEX = 11; + private ByteArrayOutputStream bout; + + /** + * 생성자 + */ + public RECV_ZENEL_0320() { + //DATA송신 + bout = new ByteArrayOutputStream(); + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + + //중간 블럭 데이터 손실되었거나, 지금까지 수신한 블럭의 크기가 현재 받은 블럭의 크기보다 크면 Error + if ((recv_block_no - block_no) > 1 || (recv_block_no - block_no) < 0 ){ + logger.debug("{} doExecute >> recived block_no is bigger than current block_no", logHeader); + this.setConditionTxt(TelegramKeys.ERROR); + + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + batchDoc.getBatchMsg().getBody().setBlockNum(recv_block_no); + batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no); + return true; + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_seq_no = Integer.parseInt(_seq_no); + + block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray()); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * SEND : 송신 길이 계산 + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + try { + String byte_size = new String ((byte[]) al_Field.get(0)); + int tot_byte_size = Integer.parseInt(byte_size); + int read_byte_size = 0; + for (int i=1; i < idx; i++){ + read_byte_size += al_Field.get(i).length; + } + return tot_byte_size - read_byte_size; + } catch(Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI005"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } else { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + } + + public boolean doInformalField(int idx, byte[] data, int length) + { + try { + if (idx == INFORMALFIELD_INDEX) { + bout.write(data, 0, length); + } else { + logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI004"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0600.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0600.java new file mode 100644 index 0000000..14aefc6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0600.java @@ -0,0 +1,189 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_ZENEL_0600 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + private Properties telegramInfo; + + /** + * 생성자 + */ + public RECV_ZENEL_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + // 거래구분코드(송수신 구분 코드) 체크 + String recvTrGbCd = getFieldValueString(4); + if ( telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND).equals(recvTrGbCd)){ + logger.info("{} BATCH JOB : send request received", logHeader); + batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND); + checkMoreFileinDB(); + }else if ( telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV).equals(recvTrGbCd)){ + logger.info("{} BATCH JOB : recv request received", logHeader); + setConditionTxt(TelegramKeys.RECV); + batchDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE); + }else{ + logger.info("{} BATCH JOB : send/recv request error", logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_FORMAT_ERROR); + setConditionTxt(TelegramKeys.ERROR); + } + + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0600 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + private void checkMoreFileinDB(){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + try{ + info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + this.setConditionTxt(TelegramKeys.NOFILE); + return; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + this.setConditionTxt(TelegramKeys.SEND); + LogUtil.updateLogMaster(batchDoc); + } catch ( Exception e){} + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0610.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0610.java new file mode 100644 index 0000000..cab65e6 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0610.java @@ -0,0 +1,127 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.io.File; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_ZENEL_0610 extends DefaultTelegram implements TelegramService +{ + //>> 업무관리정보 + private final String OpCode_start = "001"; //업무개시 + private final String OpCode_end = "002"; //업무종료 + private final String OpCode_exsist = "003"; //추가송신파일 있음 + private final String OpCode_noexsist = "004"; //추가송신파일 없음 + + /** + * 생성자 + */ + public RECV_ZENEL_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + //업무관리정보 유효성 확인 + if (this.getOpCode().equalsIgnoreCase(this.OpCode_start)) { + logger.info("{} BATCH JOB : start request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_end)) { + logger.info("{} BATCH JOB : end request received", logHeader); + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_exsist)) { + } + else if(this.getOpCode().equalsIgnoreCase(this.OpCode_noexsist)) { + } + else { + logger.info("{} 0610 telegram : unknown Operation code received >> "+this.getOpCode(), logHeader); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = this.getOpCode(); + String errCode = "BECEAIFJI008"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + } + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + if (OpCode_noexsist.equals(this.getOpCode()) && fileNm != null && !fileNm.trim().equals("")) { + //응답수신 파일 Start DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0620.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0620.java new file mode 100644 index 0000000..6b2cb17 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0620.java @@ -0,0 +1,120 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_ZENEL_0620 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_ZENEL_0620() { + //결번확인요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String _block_no = new String ((byte[]) al_Field.get(8)); + String _seq_no = new String ((byte[]) al_Field.get(9)); + int recv_block_no = Integer.parseInt(_block_no); + int recv_seq_no = Integer.parseInt(_seq_no); + int block_no = batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (recv_block_no > block_no || recv_seq_no < seq_no){ + // 0620으로 받은 BLOCK_NO가 EAIBatchMessage의 BLOCK_NO 보다 크거나 + // 0620으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함. + this.setConditionTxt(TelegramKeys.ERROR); + logger.debug("{} received block_no is bigger than current block_no", logHeader); + String[] msgArgs = new String[3]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = _block_no; + msgArgs[2] = ""+block_no; + String errCode = "BECEAIFJI024"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + return true; + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0630.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0630.java new file mode 100644 index 0000000..e3db396 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0630.java @@ -0,0 +1,172 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.ArrayList; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_ZENEL_0630 extends DefaultTelegram implements TelegramService +{ + /** + * 생성자 + */ + public RECV_ZENEL_0630() { + //화일정보수신요구 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try{ + String fileInfo = new String ((byte[]) al_Field.get(8)); + String fName = new String ((byte[]) al_Field.get(6)).trim(); + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + int fByte = Integer.parseInt(fileInfo.substring(20, 24)); //전문 바이트 수 + + //TelegramKeys.DATA_BYTE_SIZE는 한번에 파일에서 읽어와 전송할 데이터의 크기 + if (fByte < batchDoc.getBatchMsg().getHeader().getSequenceSize()) { + //630전문과 640전문의 byte수를 비교하여 작은 값을 설정. + batchDoc.getBatchMsg().getHeader().setSequenceSize(fByte); + } + + //파일명으로 부터 거래 구분 코드 추출 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length(); + String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex); + batchDoc.getBatchMsg().getHeader().setBizCode(bizCode); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){ + logger.debug("[RECV_CDCMS_0630][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")"); + this.setResolveResponseCode(TelegramKeys.RES_CODE_NOT_REGISTERED); + } + + String pattern = null; + long recLen = 0; + if ( bJobInfo!= null ){ + pattern = bJobInfo.getSndrcvFileName(); + recLen = bJobInfo.getFileRecSize(); + } + String recvFileName = FileUtil.getRecvFileName(fName, pattern, batchDoc, false); + batchDoc.getBatchMsg().getHeader().setFileName(fName); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(recvFileName); + + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + logger.debug("{} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+recvFileName+">>", logHeader); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileFullName = fileDir + recvFileName; + + File file = new File(fileFullName); + if (file.exists() && file.length() > 0) { + //파일 수신시에 미완료된 파일은 처음부터 받는다. 따라서 기존 파일 삭제 + file.delete(); + } + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + batchDoc.getBatchMsg().getHeader().setFileSize(fSize); + long recCnt = 0; + if ( recLen > 0 ){ + recCnt = fSize / recLen; + } + batchDoc.getBatchMsg().getHeader().setTotRecCnt(recCnt); + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0640.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0640.java new file mode 100644 index 0000000..7e4af39 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/RECV_ZENEL_0640.java @@ -0,0 +1,222 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RECV_ZENEL_0640 extends DefaultTelegram implements TelegramService +{ + + /** + * 생성자 + */ + public RECV_ZENEL_0640() { + //화일정보수신통보 + } + + /** + * 전문 해체하기 + */ + public boolean doExecute() { + if (!super.doExecute()) return false; + try { + String fileInfo = new String ((byte[]) al_Field.get(8)); // 화일정보내역 + long fSize = Long.parseLong(fileInfo.substring(8, 20)); //화일 size + int fByte = Integer.parseInt(fileInfo.substring(20, 24)); //전문 바이트 수 + + //TelegramKeys.DATA_BYTE_SIZE는 한번에 파일에서 읽어와 전송할 데이터의 크기 + if (fByte < batchDoc.getBatchMsg().getHeader().getSequenceSize()) { + //630전문과 640전문의 byte수를 비교하여 작은 값을 설정. + batchDoc.getBatchMsg().getHeader().setSequenceSize(fByte); + } + + if (getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_ALREADY_RECEIVED) + ||getResCode().equalsIgnoreCase(TelegramKeys.RES_CODE_NOT_REGISTERED)) { //기송신 파일이면 + checkMoreFileinDB(); + } else { +// int seqSize = batchDoc.getBatchMsg().getHeader().getSequenceSize(); +// int blockSize = batchDoc.getBatchMsg().getHeader().getBlockSize(); +// int totSeqSizeOffSize = 0; +// int seqSizeOffSize = 0; +// int blockSizeOffSize = 0; + + if (fSize > 0) { //기 송신된 파일이면서 미완료 파일이면 +// totSeqSizeOffSize = (int)fSize / seqSize; +// if (totSeqSizeOffSize > 0 ) { // +// blockSizeOffSize = totSeqSizeOffSize / blockSize; +// batchDoc.getBatchMsg().getBody().setCurFileSize(fSize); +// +// FileInputStream fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); +// if ( blockSizeOffSize > 0) { +// long iLoopCnt = blockSizeOffSize * blockSize; +// for( int inx = 0; inx < iLoopCnt; inx++){ +// FileUtil.readLine(fin); +// } +// batchDoc.getBatchMsg().getBody().setBlockNum(blockSizeOffSize+1); //기 송신된 블럭 다음부터 송신 +// } else { +// batchDoc.getBatchMsg().getBody().setBlockNum(1); +// } +// seqSizeOffSize = totSeqSizeOffSize % blockSize; +// +// String header = this.batchDoc.getBatchMsg().getFileHeader(); +// // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 +// JobProcessData job = JobProcessData.getInstance(); +// String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); +// HashMap hm = job.getBatchStageData(uuid); +// +// @SuppressWarnings("unchecked") +// HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); +// if (block_data == null) { +// block_data = new HashMap(); +// } +// +// if (seqSizeOffSize > 0){ +// for ( int jnx = 0; jnx < seqSizeOffSize; jnx++){ +// byte[] fileLine = FileUtil.readLine(fin); +// int REAL_BYTE = Integer.parseInt(header.substring(23, 27)); +// byte[] fileData = new byte[REAL_BYTE]; +// System.arraycopy( fileLine, 7, fileData, 0, REAL_BYTE); +// block_data.put( new Integer(jnx), fileData); +// } +// hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); +// batchDoc.getBatchMsg().getBody().setSeqNum(seqSizeOffSize); +// } else { +// batchDoc.getBatchMsg().getBody().setSeqNum(0); +// } +// } +// else {//기전송된 파일의 사이즈가 seqSize보다 작으면 처음부터 다시 송신 +// batchDoc.getBatchMsg().getBody().setBlockNum(0); +// batchDoc.getBatchMsg().getBody().setSeqNum(0); +// } + setConditionTxt(TelegramKeys.ERROR); + throw new Exception("상대 기관에 수신 자료 초기화 요청 바랍니다."); + } else { //최초 송신이면 + batchDoc.getBatchMsg().getBody().setBlockNum(0); + batchDoc.getBatchMsg().getBody().setSeqNum(0); + } + } + + } catch ( Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + /** + * 전문 Validation + */ + public boolean doValidation() + { + if (!super.doValidation()) return false; + return true; + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + LogUtil.setLogFileStart(batchDoc); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private void checkMoreFileinDB(){ + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + SchedulerMessageVO info; + + try{ + info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode ); + if ( info == null ) { + return; + } + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID(); + + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID); + + //BatchMsgDoc 값 설정 + batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + // 0600 전문을 보내어 현재 파일을 마무리 하여야 하므로 여기서 BizCode를 세팅하면 안된다. + //batchDoc.getEAIBatchMessage().getHeader().setBizCode(info.getBizCode()); + batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchDoc.getBatchMsg().getHeader().setFileSize(0); + batchDoc.getBatchMsg().getBody().setCurFileSize(0); + this.setConditionTxt(TelegramKeys.EOF); + + } catch ( Exception e){ + logger.error( e.getMessage(), e); + } + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0300.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0300.java new file mode 100644 index 0000000..b13d52c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0300.java @@ -0,0 +1,393 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0300 extends DefaultTelegram implements TelegramService +{ + + private int SEQUENCE_NO; + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + private int MISSING_COUNT; //결번갯수 + private String MISSING_FIELD; + + private Properties telegramInfo; + private FileOutputStream fout; + + /** + * 생성자 + */ + public SEND_ZENEL_0300() { + //결번확인통보 + MISSING_COUNT = 0; + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + boolean result = calculateMissingCount(); + if (!result) return false; + + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //BLOCK-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[8]); + //최종 SEQUENCE-NO + compileField(9, ""+SEQUENCE_NO, this.al_FieldProps[9]); + //결번갯수 + compileField(10, ""+MISSING_COUNT, this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + // 20060413 add by khs + if (MISSING_COUNT==0) { + fout.close(); + } + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + String jobCode = this.batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + * RECV : 수신 길이 계산 + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return MISSING_FIELD.length(); + } + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + + ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes()); + bin.read(data, 0, MISSING_FIELD.length()); + return MISSING_FIELD.length(); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { //마지막 결번확인은 가변길이 + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함. + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + return true; + } + + private boolean calculateMissingCount () { + try { + + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + JobProcessData job = JobProcessData.getInstance(); + HashMap hm = job.getBatchStageData(uuid); + + byte[] _missingNm = new byte[seq_no]; + for (int i=0; i block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + MISSING_COUNT = SEQUENCE_NO; + for (int i = 0; i> missing telegram : [" + i + "]", logHeader); + } + } + } + + if (MISSING_COUNT == 0) { + if (!createFile()) { + return false; + } + + for (int i = 0; i> File full-path [" + strFullPath + "]", logHeader); + File file = new File(strFullPath); + fout = new FileOutputStream(file, true); //bytes will be written to the end of the file rather than the beginning + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0310.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0310.java new file mode 100644 index 0000000..8cab18c --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0310.java @@ -0,0 +1,265 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0310 extends DefaultTelegram implements TelegramService +{ + + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_ZENEL_0310() { + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //BLOCK-NO + compileField(8, ""+BLOCK_NO, this.al_FieldProps[8]); + + //SEQUENCE-NO + compileField(9, ""+SEQUENCE_NO, this.al_FieldProps[9]); + + //실 DATA BYTE 수 + compileField(10, ""+REAL_BYTE, this.al_FieldProps[10]); + + if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료 + this.setConditionTxt(TelegramKeys.LOSSEND); + } + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean setBlockAndSeqNO () + { + try { + + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + + int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount(); + String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField(); + int missing_fld_len = missing_field.getBytes().length; + byte[] _missing = missing_field.getBytes(); + + this.BLOCK_NO = block_no; + + for (int i=0; i hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap)hm.get(JobProcessData.PROCDATA_BLOCKDATA); + + if (block_data == null ){ + logger.debug(logHeader +" : " + ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")); + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI026-1"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return false; + } + fileData = (byte[]) block_data.get( new Integer(SEQUENCE_NO -1) ); + this.REAL_BYTE = fileData.length; + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0320.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0320.java new file mode 100644 index 0000000..dcb7aa5 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0320.java @@ -0,0 +1,423 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Properties; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0320 extends DefaultTelegram implements TelegramService +{ + + private FileInputStream fin ; + private int BLOCK_NO; + private int SEQUENCE_NO; + private int REAL_BYTE; //실 data byte수 + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + private byte[] fileData; + + /** + * 생성자 + */ + public SEND_ZENEL_0320() { + //DATA송신 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = setBlockAndSeqNO(); + if (!result) { + return false; + } + result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //BLOCK-NO + compileField(8, ""+BLOCK_NO, this.al_FieldProps[8]); + //SEQUENCE-NO + compileField(9, ""+SEQUENCE_NO, this.al_FieldProps[9]); + //실 DATA BYTE 수 + compileField(10, ""+REAL_BYTE, this.al_FieldProps[10]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public int getInformalFieldSendData(int idx, byte[] data) { + int fldLen = getCalculatedLength(idx); + try { + if (idx >= this.getFieldCount() ) { + logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (data.length < fldLen) { + logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI014"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + ByteArrayInputStream bin = new ByteArrayInputStream(fileData); + bin.read(data, 0, REAL_BYTE); + // 20060419 add by khs for 전송상태 확인 + long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE; + batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize); + + // 로깅을 위해 + byte[] fieldData = new byte[fldLen]; + System.arraycopy(data, 0, fieldData, 0, fldLen); + this.al_Field.set( idx, fieldData); + + return fldLen; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI006"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return -1; + } + } + + public boolean doPostExecute() { + try { + if (!super.doPostExecute()) return false; + + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외 + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + /** + * int getCalculatedLength(int idx) + * -------------------------------------------------------------------------------------- + * 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다. + * 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다. + */ + public int getCalculatedLength(int idx) { + + if (idx >= this.getFieldCount()) { + logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader); + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI011"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + if (!this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = ""+idx; + String errCode = "BECEAIFJI012"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + return -1; + } + return REAL_BYTE; + } + + private boolean createFile () + { + + fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID()); + if( fin != null ) return true; + try { + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + String[] msgArgs = new String[2]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + msgArgs[1] = fileName; + String errCode = "BECEAIFJI022"; + String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + throw new Exception(" the File["+fileName+"] does not exist!!!"); + } + fin = new FileInputStream(file); + BatchOpenFileManager.getInstance().addFile(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fin); + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI028"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + private boolean setBlockAndSeqNO () + { + try { + if (!createFile()) { + logger.error("{} file open failed", logHeader); + return false; + } + + int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize(); + int block_no = this.batchDoc.getBatchMsg().getBody().getBlockNum(); + int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum(); + + if (block_no == 0 && seq_no == 0) { //첫 0320 전송이면 + this.BLOCK_NO = 1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else { + if (seq_no == block_size) { //한 블럭 송신 후 결번확인(0300) 이후 데이터 전송 + this.BLOCK_NO = block_no+1; + this.SEQUENCE_NO = 1; + this.setConditionTxt(""); + + } else if (seq_no >= block_size-1) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 0620전문으로 넘어가게 함 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(TelegramKeys.BLOCKEND); + } else { //한 블럭내에 데이터 전송 반복이면 + this.BLOCK_NO = block_no; + this.SEQUENCE_NO = seq_no+1; + this.setConditionTxt(""); + } + + } + // 한번에 블러킹 할 건수 + int seqCnt = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ); + // 남은 바이트 수 + long remainSize = batchDoc.getBatchMsg().getHeader().getFileSize() - batchDoc.getBatchMsg().getBody().getCurFileSize(); + // 남은 건수 + long remainCnt = remainSize / batchDoc.getBatchMsg().getHeader().getRecLen(); + + boolean isLastSeq = false; + if ( seqCnt < remainCnt ){ + REAL_BYTE = seqCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + }else{ + REAL_BYTE = (int)remainCnt * batchDoc.getBatchMsg().getHeader().getRecLen(); + this.setConditionTxt(TelegramKeys.BLOCKEND); + isLastSeq = true; + } + int readCnt = REAL_BYTE / batchDoc.getBatchMsg().getHeader().getRecLen(); + + fileData = new byte[REAL_BYTE]; + for ( int inx = 0 ; inx < readCnt ; inx++){ + byte[] fileLine = FileUtil.readLine(fin); + System.arraycopy( fileLine, 0, fileData, inx * batchDoc.getBatchMsg().getHeader().getRecLen(), batchDoc.getBatchMsg().getHeader().getRecLen()); + } + + if ( isLastSeq ){ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } + + // 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다. 2008.06.19 - 정동한 + JobProcessData job = JobProcessData.getInstance(); + String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap hm = job.getBatchStageData(uuid); + + @SuppressWarnings("unchecked") + HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); + if (block_data == null) { + block_data = new HashMap(); + } + block_data.put( new Integer(SEQUENCE_NO-1), fileData); + hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data); + // 2008.06.19 - 정동한 + + this.batchDoc.getBatchMsg().getBody().setBlockNum(BLOCK_NO); + this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO); + + return true; + } catch (Exception e ) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI029"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size()-1; i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + SEND_LENGTH += REAL_BYTE; + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0600.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0600.java new file mode 100644 index 0000000..5f4cf8e --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0600.java @@ -0,0 +1,206 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0600 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_ZENEL_0600() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode()) > -1){ + compileField(6, "", this.al_FieldProps[6]); + } else { + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + } + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //전문 전송 일시 (MMddhhmmss) + compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //송신자명 + compileField(10, "", this.al_FieldProps[10]); + + //송신자 암호 + compileField(11, "", this.al_FieldProps[11]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0610.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0610.java new file mode 100644 index 0000000..094a4af --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0610.java @@ -0,0 +1,259 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0610 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_ZENEL_0610() { + //업무개시요구 및 업무개시통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + if ( "001|004".indexOf(this.getFldOpCode()) > -1){ + compileField(6, "", this.al_FieldProps[6]); + } else { + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + } + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //전문 전송 일시 (MMddhhmmss) + compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]); + + //업무관리정보. CMS 업무 관리를 위한 코드. + //001-업무개시, 002-화일 송수신 완료(송신할 화일 존재), 003-화일 송수신 완료(송신할 화일 없음), 004-업무종료 + compileField(9, this.getFldOpCode(), this.al_FieldProps[9]); + + //송신자명 + compileField(10, "", this.al_FieldProps[10]); + + //송신자 암호 + compileField(11, "", this.al_FieldProps[11]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + if ("001|004".indexOf(this.getFldOpCode()) > -1) return true; + + //이하 응답코드가 '업무개시'가 아닌 경우에만 처리 + //수신 파일 관련 처리 + String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath(); + String fileNm = batchDoc.getBatchMsg().getHeader().getFileName(); + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + String fileName = fileDir + fileNm; + + File rcvRealFile = new File( fileName ); + File rcvArchFile = new File( StringUtil.realToArchDir(fileName) ); + File rcvRootFile = new File( StringUtil.realToRootDir(fileName) ); + + if ((fileNm != null) && (!fileNm.trim().equals(""))&& (rcvRealFile.exists())) { + + //DB로그에 남길 파일 헤더,트레일러 내용 설정 + super.setFileHeaderAndTrailer(rcvRealFile); + + //DB로그에 남길 변경 파일명 설정 (파일명 변경 안함) + batchDoc.getBatchMsg().getHeader().setRenamedFileName(fileName); + //수신 Real 디렉토리 -> Arch 디렉토리로 파일 이동 (파일명 변경 안한고 동일 파일명 존재시 Overwrite) + logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader); + boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}] + super.setResolveResponseCode(TelegramKeys.RPS_HDB_RET_CODE_OTHER_ERROR); + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + return true; //다음단계 수행시 응답코드를 기준으로 에러전문을 송신하기위해 true 설정함 + } + + logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(HOST에 자동 송신하도록 수신 File Event 발생)", logHeader); + try { + isSuccessMoveFile = rcvRootFile.createNewFile(); + } catch (Exception e) { } // 실패인 경우 무시하고 로깅만 하도록.... + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()}); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}] + } + + //수신 파일 End DB로그 + LogUtil.setLogFileEnd(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getFieldValueString(9); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0620.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0620.java new file mode 100644 index 0000000..8ed5432 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0620.java @@ -0,0 +1,197 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0620 extends DefaultTelegram implements TelegramService +{ + + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_ZENEL_0620() { + //결번확인요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //BLOCK-NO + compileField(8, ""+this.batchDoc.getBatchMsg().getBody().getBlockNum(), this.al_FieldProps[8]); + + //최종 SEQUENCE-NO + compileField(9, ""+this.batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[9]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0630.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0630.java new file mode 100644 index 0000000..2896928 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0630.java @@ -0,0 +1,216 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0630 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + + /** + * 생성자 + */ + public SEND_ZENEL_0630() { + //화일정보수신요구 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + int seqSize = ( batchDoc.getBatchMsg().getHeader().getSequenceSize() / batchDoc.getBatchMsg().getHeader().getRecLen() ) * batchDoc.getBatchMsg().getHeader().getRecLen(); + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(batchDoc.getBatchMsg().getHeader().getFileName().substring(0, 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getHeader().getFileSize(), 12)); + // 0630 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + fileInfo.append(makeZero(""+(SEND_LENGTH + seqSize - 13), 4)); + + compileField(8, fileInfo.toString(), this.al_FieldProps[8]); + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + try { + String jobCode = batchDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchDoc.getBatchMsg().getHeader().setBizCode(bjvo.getJobTranDstcd()); + batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + String hdrInfoName = batchDoc.getBatchMsg().getHeader().getHdrInfoName(); + batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt()); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0640.java b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0640.java new file mode 100644 index 0000000..3decb0b --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobItem/zeniel/SEND_ZENEL_0640.java @@ -0,0 +1,248 @@ +package com.eactive.eai.batch.job.jobItem.zeniel; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobItem.DefaultTelegram; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class SEND_ZENEL_0640 extends DefaultTelegram implements TelegramService +{ + private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이 + private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이 + + private Properties telegramInfo; + /** + * 생성자 + */ + public SEND_ZENEL_0640() { + //화일정보수신통보 + } + + /** + * 전문조립 + */ + public boolean doExecute() { + try { + + boolean result = calculateSendLength(); + if (!result) return false; + + //전송길이 + compileField(0, "" + SEND_LENGTH, this.al_FieldProps[0]); + + //업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET + compileField(1, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[1]); + + //기관코드 + compileField(2, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[2]); + + //전문종별코드. 전문의 기능을 나타냄. + compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]); + + //거래구분코드 센터 송신업무"S", 센터 수신업무 "R" + String procType = batchDoc.getBatchMsg().getHeader().getProcessType(); + if ( procType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) || + procType.equalsIgnoreCase(CommonKeys.PROCESS_RESPONSE_SEND)) { + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_SEND), this.al_FieldProps[4]); + }else{ + compileField(4, telegramInfo.getProperty(TelegramKeys.TRAN_GBN_RECV), this.al_FieldProps[4]); + } + + //송수신 FLAG 전문발생기관 + compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER), this.al_FieldProps[5]); + + //화일명 + compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]); + + //응답코드 + compileField(7, this.getResolveResponseCode(), this.al_FieldProps[7]); + + //화일 정보내역. 화일명+화일size+전문바이트수 + //RECV 0630/0640에서는 서로 교환한 값중 작은 값으로 결정한다. + StringBuffer fileInfo = new StringBuffer(); + fileInfo.append(batchDoc.getBatchMsg().getHeader().getFileName().substring(0, 8)); + fileInfo.append(makeZero(""+batchDoc.getBatchMsg().getBody().getCurFileSize(),12)); + fileInfo.append(makeZero(""+calculateTelegramSize(), 4)); + compileField(8, fileInfo.toString(), this.al_FieldProps[8]); + + //<< 전문 완성 + return true; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI001"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + } + + /** + * 실제 송신할 전문의 총길이를 리턴해준다. + */ + public int getSendLength() + { + try { + return REAL_SEND_LENGTH; //실 DATA BYTE수 + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI013"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return -1; + } + } + + public boolean doPreExecute() { + try { + if (!super.doPreExecute()) return false; + telegramInfo = getTelegramInfo(); + //해당 거래구분에 대한 Job_Code 값 설정 + //거래구분코드 조회 BizCode 조회 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + String fileName = batchDoc.getBatchMsg().getHeader().getFileName(); + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(batchDoc.getBatchMsg().getHeader().getProcessCode(), bizCode); + if (info != null) { + batchDoc.getBatchMsg().getHeader().setJobCode(info.getMsgDstCode());; + } else { + logger.debug("{} " + batchDoc.getBatchMsg().getHeader().getUUID()+ "'s Job Code is null", logHeader); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + batchDoc.getBatchMsg().getHeader().setJobCode((processCode+"00000")); //dummy code + // TEST 용 return false; + } + try { + int sleepTime = Integer.parseInt(telegramInfo.getProperty(TelegramKeys.SLEEP_TIME)); + Thread.sleep(sleepTime); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + return true; + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI003"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + public boolean doPostExecute() { + if (!super.doPostExecute()) return false; + try { + //DB로그에 남길 전문 헤더 설정 + ByteArrayOutputStream baout = new ByteArrayOutputStream(); + for (int i=0; i<8; i++) { //제니엘 CMS전문의 헤더는 응답코드까지 임(TRANSACTION CODE 삭제) + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray())); + + //DB로그에 남길 전문 바디 설정 + baout = new ByteArrayOutputStream(); + for (int i=8; i< al_Field.size(); i++) { + baout.write((byte[])this.al_Field.get(i)); + } + batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray())); + + //성공 시 응답수신 파일 Start DB로그 + if (this.getSendResponseCode().equals(TelegramKeys.RES_CODE_SUCESS)){ + LogUtil.setLogFileStart(batchDoc); + } + + return true; + + } catch(Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + return false; + } + } + + private boolean calculateSendLength () { + try { + for (int i=1; i< this.al_Field.size(); i++) { + byte[] aField = (byte[]) this.al_Field.get(i); + SEND_LENGTH += aField.length; + } + REAL_SEND_LENGTH = SEND_LENGTH; + REAL_SEND_LENGTH += ((byte[]) this.al_Field.get(0)).length; + } catch (Exception e) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI025"; + String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( e.getMessage(), e); + return false; + } + return true; + } + + private int calculateTelegramSize(){ + int recSize = 200; + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + if ( bJobInfo != null && bJobInfo.getFileRecSize() > 0 ){ + recSize = (int)Math.min(bJobInfo.getFileRecSize(), 4000); + } + + // 0630/0640 전문 길이 ( 공통 + 24 = SEND_LENGTH ) 0320 전문 길이 ( 공통 + 11 + 파일내역 ) + // 그러므로 0320 전문의 길이는 0630/0640 전문 길이에서 파일 내역을 더하고 13을 빼 준다 ) + return (batchDoc.getBatchMsg().getHeader().getSequenceSize() / recSize) * recSize + SEND_LENGTH - 13; + } + //---------------- 특정 필드값을 구하는 부분 + // 전문종별코드 필드값 리턴 + public String getTelegramType() + { + return super.getFieldValueString(3); + } + // 거래구분코드 필드값 리턴 + public String getTrClass() + { + return super.getFieldValueString(4); + } + //응답코드 필드값 리턴 + public String getResCode() + { + return super.getFieldValueString(7); + } + //업무관리코드 필드값 리턴 + public String getOpCode() + { + return super.getOpCode(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/EEND.java b/src/com/eactive/eai/batch/job/jobModule/Component/EEND.java new file mode 100644 index 0000000..3f0cc86 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/EEND.java @@ -0,0 +1,83 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.net.Socket; + +import com.eactive.eai.batch.job.jobModule.ReSendReqSend; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; +import com.eactive.eai.common.util.UCMsgSenderUtil; + +public class EEND extends JobComponent implements JobComponentService +{ + + // 소켓을 구한다. + BatchRunningJobManager bs_man = BatchRunningJobManager.getInstance(); + Socket socket ; + + public BatchDoc execute() throws Exception { + FileInputStream fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fin != null){ + try{ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + } + + BufferedReader fbr = BatchOpenFileManager.getInstance().getFbr(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fbr != null){ + try{ + fbr.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + } + + BufferedInputStream bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if (bis != null){ + try { + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + } + + IniSafeManager.getInstance().removeManager(batchDoc); + + logger.info("{} EEND.execute>> Batch job end with error.. ", logHeader); + logger.debug("{} 1. Node Count = " + batchDoc.getBatchMsg().getBody().getNodeCount(), logHeader); + if (batchDoc.getBatchMsg().getHeader().getProcessType().equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND) + && batchDoc.getBatchMsg().getHeader().getReqSendRetryFlag()==true){ //요구송신이면서 재처리 설정되어 있으면.. + batchDoc = ReSendReqSend.insertJobToQueue(batchDoc); + }else{ + UCMsgSenderUtil.sendUCMsg(batchDoc); + } + return batchDoc; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/END.java b/src/com/eactive/eai/batch/job/jobModule/Component/END.java new file mode 100644 index 0000000..4aa4ccd --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/END.java @@ -0,0 +1,135 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.BufferedReader; +import java.net.Socket; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityManager; +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityVO; +import com.eactive.eai.batch.running.BatchOpenFileManager; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.secure.inisafe.IniSafeManager; + +public class END extends JobComponent implements JobComponentService +{ + + // 소켓을 구한다. + BatchRunningJobManager bs_man = BatchRunningJobManager.getInstance(); + Socket socket ; + + public BatchDoc execute() throws Exception { + + FileInputStream fin = BatchOpenFileManager.getInstance().getFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fin != null){ + try{ + fin.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + } + + BufferedReader fbr = BatchOpenFileManager.getInstance().getFbr(batchDoc.getBatchMsg().getHeader().getUUID() ); + if ( fbr != null){ + try{ + fbr.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID() ); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + } + + BufferedInputStream bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID()); + if (bis != null){ + try { + bis.close(); + BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID()); + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs); + this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error( ex.getMessage(), ex); + } + } + //우선순위 처리를 위해 전송된 파일 수 증가와 실행여부 업데이트 + //2009.8.19 by kscheon - start + if (batchDoc.getBatchMsg().getHeader().getProcessType().equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_SEND)){ //요구송신이면서 재처리 설정되어 있으면.. + + + try{ + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + String propName = TelegramKeys.PROP_GROUP_NAME_PREFIX + "{" + batchDoc.getBatchMsg().getHeader().getProcessCode() + "_" + bizCode + "}"; + + PropManager pmanager = PropManager.getInstance(); + Properties telegramInfo = pmanager.getProperties(propName); + String isPriority =""; + String[] priorityList = null; + + if (telegramInfo != null ){ + isPriority = telegramInfo.getProperty("priority"); + } + BatchJobPriorityManager jobpmanager = BatchJobPriorityManager.getInstance(); + + + //우선순위가 설정된 업무인 경우에는 같은 우선순위의 작업만 한번에 socket을 할당 할 수 있도록 한다. + if (isPriority != null && "Y".equals(isPriority)){ + String plist = telegramInfo.getProperty("priority.list"); + if (plist != null && plist.length() >0){//등록된 우선순위 목록이 있으면.. + + priorityList = plist.split(","); + } + + if (priorityList != null && priorityList.length >0){ + BatchJobPriorityVO datavo = jobpmanager.getPriorityDatabyBizCode(priorityList[0], batchDoc.getBatchMsg().getHeader().getBizCode()); + + if (datavo != null){ + int dataCount = datavo.getDataCount(); + datavo.setDataCount(dataCount+1); + } + + if (!bizCode.equals(priorityList[0]) + && bizCode.equals(priorityList[priorityList.length-1])){ //마지막 우선순위 작업을 실행했으면.. 우선순위 목록의 마지막 작업은 우선순위가 가장 낮아야 한다. + jobpmanager.delPriorityData(priorityList[0]); //등록된 우선순위 목록을 삭제한다. + }else { + jobpmanager.updateExecuteJobList(priorityList[0],bizCode, this.batchDoc.getBatchMsg().getHeader().getUUID(), this.batchDoc.getBatchMsg().getHeader().getFileName()); + } + } + } + }catch (Exception e){ + //무시.. + } + } + + IniSafeManager.getInstance().removeManager(batchDoc); + + //우선순위 처리를 위해 전송된 파일 수 증가와 실행여부 업데이트 + //2009.8.19 by kscheon - end + + logger.info("{} END.execute>> Batch job end ", logHeader); + + logger.debug("{} 1. Node Count = " + batchDoc.getBatchMsg().getBody().getNodeCount(), logHeader); + + return batchDoc; + } + +} diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/JobComponent.java b/src/com/eactive/eai/batch/job/jobModule/Component/JobComponent.java new file mode 100644 index 0000000..bd3d5f9 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/JobComponent.java @@ -0,0 +1,176 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.net.Socket; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.FlowController; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class JobComponent implements JobComponentService +{ + + public BatchDoc batchDoc; + + // FileLoger + protected Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public String logHeader; + public String logNodeCount; + + // 소켓을 구한다. + public BatchRunningJobManager bs_man = BatchRunningJobManager.getInstance(); + public Socket socket ; + public String strUUID = ""; + public String strRuleCode = ""; + public String strPhaseCode = ""; + + public PhaseInfoVO nextPhaseInfoVO = null; + + public JobComponent() { + } + + public BatchDoc getEAIBatchMessage() + { + return batchDoc; + } + + public void setEAIBatchMessage(BatchDoc batchDoc) throws Exception + { + this.batchDoc = batchDoc; + this.strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + this.strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode(); + this.strPhaseCode = batchDoc.getBatchMsg().getPhaseinfo().getPhaseCode(); + + logger = batchDoc.getLogger(); + // 노드카운트를 1 증가시킨다. + int nNodeCount = batchDoc.getBatchMsg().getBody().getNodeCount(); + batchDoc.getBatchMsg().getBody().setNodeCount(nNodeCount+1); + + logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+ + batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+ + batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+ + batchDoc.getBatchMsg().getHeader().getFileName() +" / "+ + batchDoc.getBatchMsg().getHeader().getRuleCode() +" / "+ + batchDoc.getBatchMsg().getPhaseinfo().getPhaseCode() +" / "+ + batchDoc.getBatchMsg().getPhaseinfo().getPhaseType() +"] "; + logNodeCount = "[NodeCnt-"+ batchDoc.getBatchMsg().getBody().getNodeCount() +" / "+ + this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1) +"] "; + } + + public BatchDoc execute() throws Exception { + return batchDoc; + } + + protected void setPreviousTelegramComponent(TelegramService telegramComp) { + HashMap map = JobProcessData.getInstance().getBatchStageData(strUUID); + map.remove(JobProcessData.PROCDATA_PRE_TELEGRAM); + map.put(JobProcessData.PROCDATA_PRE_TELEGRAM, telegramComp); + } + + public void doErrorAction(TelegramService telegramComp, String errCode) throws Exception + { + doErrorAction(null, telegramComp, errCode, null); + } + + public void doErrorAction(Exception cause, TelegramService telegramComp, String errCode) throws Exception + { + doErrorAction(cause, telegramComp, errCode, null); + } + + public void doErrorAction(TelegramService telegramComp, String errCode, String[] args) throws Exception + { + doErrorAction(null, telegramComp, errCode, args); + } + + public void doErrorAction(Exception cause, TelegramService telegramComp, String errCode, String[] args) throws Exception + { + //telegramComp 가 null 이 아니면 다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록 + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. + if (telegramComp != null) { + this.setPreviousTelegramComponent(telegramComp); + } + + //1. 에러메시지 설정 + String errMsg = ExceptionUtil.getErrorCode(cause, batchDoc, errCode, args); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + logger.error(logHeader+" [" + errMsg+"]"); + + String phaseType = batchDoc.getBatchMsg().getPhaseinfo().getPhaseType(); + //================================================================================================= + // 송신 시 오류가 발생한 경우 + if (phaseType.equals("SEND")) { + //다음단계를 에러종료 단계로 설정 + batchDoc.getBatchMsg().getBody().setNextPhaseCode(FlowController.PHASECODE_ERROR_END); + return; + } + + //================================================================================================= + //수신 시 오류가 발생한 경우 + + //정상수신인데 기대했던 전문종별코드가 아닌경우 + if (errCode.equals(ErrorKeys.ERROR_UNEXPECTED_TELEGRAM_IGNORE)) { + //다음단계를 바꾸지 않고 그대로 둔다. (정상수신된 부적합한 전문종별코드의 전문을 무시한다.) + return; + } + + //다음 단계정보 조회 + String strUUID = batchDoc.getBatchMsg().getHeader().getUUID(); + HashMap currdata_hm = JobProcessData.getInstance().getBatchStageData(strUUID); + if (currdata_hm == null) { + logger.error("{} ★★★★★ NO NEXT STAGE INFO ★★★★★", logHeader); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(FlowController.PHASECODE_ERROR_END); + return; + } + @SuppressWarnings("unchecked") + ArrayList al_curr_poss_next_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (al_curr_poss_next_stage == null || al_curr_poss_next_stage.size() == 0) { + logger.error("{} ★★★★★ NO NEXT STAGE ★★★★★", logHeader); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(FlowController.PHASECODE_ERROR_END); + return; + } + + //####################################################################### + //TIMEOUT 오류인 경우 + //####################################################################### + if (errMsg.indexOf(ErrorKeys.ERROR_TIMEOUT_OVER) > 0) { + //다음단계 목록에서 TIMEOUT 단계를 찾아 설정한다. + for (int i=0; i [" + vo.getNextPhaseCode() + "]", logHeader); + logger.info("{} ===============================================================", logHeader); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(vo.getNextPhaseCode()); + return; + } + } + logger.info("{} [TIMEOUT] NOT Assigned [TIMEOUT] Condition Next Stage ... ", logHeader); + logger.info("{} ===============================================================", logHeader); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(FlowController.PHASECODE_ERROR_END); + + //####################################################################### + //응답송신, 응답수신 시 오류이고 Socket 이 연결된 경우 + //(오류전문을 송신한다. 응답코드는 오류가 발생한 지점에서 설정된다.) +// } else if ((batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND) || +// batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_RECEIVE)) && +// BatchRunningJobManager.getInstance().isSocketClosed(strUUID) == false) { +// //다음단계 목록에서 가장 첫번째 단계를 설정한다. (SEND 단계) +// PhaseInfoVO vo = (PhaseInfoVO) al_curr_poss_next_stage.get(0); +// batchDoc.getBatchMsg().getBody().setNextPhaseCode(vo.getNextPhaseCode()); +// logger.info("{} [응답송수신 수신전문 오류] => 에러전문 송신 Next Phase : ["+vo.getNextPhaseCode()+"]", logHeader); +// + } else { + batchDoc.getBatchMsg().getBody().setNextPhaseCode(FlowController.PHASECODE_ERROR_END); + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/JobComponentService.java b/src/com/eactive/eai/batch/job/jobModule/Component/JobComponentService.java new file mode 100644 index 0000000..a7cb241 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/JobComponentService.java @@ -0,0 +1,10 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import com.eactive.eai.batch.doc.BatchDoc; + +public interface JobComponentService +{ + public BatchDoc getEAIBatchMessage() ; + public void setEAIBatchMessage(BatchDoc pBatchDoc) throws Exception; + public BatchDoc execute() throws Exception ; +} diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/RECV1.java b/src/com/eactive/eai/batch/job/jobModule/Component/RECV1.java new file mode 100644 index 0000000..21d27d2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/RECV1.java @@ -0,0 +1,493 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LoggingUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramItemVO; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * Rule에 정의되지 않은 {전문종별코드} 수신 시 작업을 중지하는 RECV Flow Component + */ +public class RECV1 extends JobComponent implements JobComponentService +{ + + private TelegramService ll_telegram = null; + private TelegramService rv_telegram = null; + + ByteArrayOutputStream boutHeader = new ByteArrayOutputStream(); + ByteArrayOutputStream boutBody = new ByteArrayOutputStream(); + + /** + * JobComponentService functions + */ + public BatchDoc execute() throws Exception + { + + // UUID, 흐름규칙 코드 구하기 + logger.debug("{} ■ Node Count = " + batchDoc.getBatchMsg().getBody().getNodeCount(), logHeader); + + //============================================================================================== + // 소켓을 찾는다. + logger.debug("{} ▶ SOCKET 검색......", logHeader); + socket = bs_man.getRunningSocket(strUUID); + if (socket == null ) { + doErrorAction(null, ErrorKeys.ERROR_NO_SOCKET, new String[] {strUUID}); + return batchDoc; + } + DataInputStream din = new DataInputStream(socket.getInputStream()); + + //============================================================================================== + // RECV 단계의 타임아웃과 반복시도 횟수값을 알아내기위한 공용저장공간 뒤지기 + logger.debug("{} ▶ JobProcessData 검색......", logHeader); + HashMap currdata_hm = JobProcessData.getInstance().getBatchStageData(strUUID); + if (currdata_hm == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_PROCDATA, new String[] {strUUID}); + return batchDoc; + } + @SuppressWarnings("unchecked") + ArrayList curr_poss_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (curr_poss_stage == null || curr_poss_stage.size() == 0) { + doErrorAction(null, ErrorKeys.ERROR_NO_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + + //============================================================================================== + // PhaseInfo 정보에서 RECV 용 TIMEOUT과 반복 횟수를 읽어들인다. + logger.debug("{} ▶ SOCKET Timeout 설정......", logHeader); + PhaseInfoVO pvo = curr_poss_stage.get(0); + int nTimeout = pvo.getTOVal() * 1000; // 타임아웃 시간 (msec) + int nRepeatCount = pvo.getRepeat(); + socket.setSoTimeout(nTimeout); + logger.debug("{} ☞ [Timeout = " + pvo.getTOVal() + "초], [Retry count = " + nRepeatCount +"]", logHeader); + + //############################################################################################## + // 이하 HEADER 처리 부분 # + //############################################################################################## + + //============================================================================================== + // EAIBatchMessage의 노드정보에서 전문결정용 텔레그램 클래스를 찾아낸다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram 정보 검색......", logHeader); + String strTelegramID = batchDoc.getBatchMsg().getPhaseinfo().getLengthTelegramID(); + int nLengthFieldIdx = batchDoc.getBatchMsg().getPhaseinfo().getLengthFieldIndex(); + + TelegramInfoVO lenTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(strTelegramID); + if (lenTelegramVO == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_TELEGRAM_ID, new String[] {strRuleCode, strPhaseCode, strTelegramID}); + return batchDoc; + } + String strLenTelegramClsName = lenTelegramVO.getTelegramClsName(); + String strLenMsgMetaDstcd = lenTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName(strLenTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (strLenMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 HEADER 수신 Telegram ID = "+ strTelegramID +"], [{전문종별코드} 필드 Index = "+ nLengthFieldIdx +"]", logHeader); + logger.debug("{} ☞ [전문 HEADER 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 HEADER 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 길이결정 텔러그램 클래스를 생성한다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram Class 생성...... ("+ strLenTelegramClsName +")", logHeader); + this.ll_telegram = (TelegramService) Class.forName(strLenTelegramClsName).newInstance(); + if (this.ll_telegram == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + // 길이결정용 텔레그램 인스탄스에 BatchDoc 지정하고 메시지메타코드도 지정한다. + this.ll_telegram.setEAIBatchMessage(batchDoc); + this.ll_telegram.setTelegramCode(strLenMsgMetaDstcd); + this.ll_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문헤더 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPreExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 소켓에서 필드별로 데이터를 읽어들인다. + logger.debug("{} ▶ SOCKET 에서 전문 HEADER 데이터 수신 대기중......", logHeader); + for (int i=0; i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + String msg = new String(aField); + logger.debug("{} ☞ 전문 HEADER Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ msg +"] ["+ item.getFieldName() +"]", logHeader); + if ( msg.trim().equals("")){ + logger.debug("{} ☞ 전문 DATA HEXADUMP \n"+ CommonLib.getDumpMessage(aField) , logHeader); + } + //읽어들인 필드 데이터 저장 + this.ll_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutHeader.write(bout.toByteArray()); //Stage Logging 용 (header formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 HEADER Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM025", new String[] { item.getFieldName() }); //전문 HEADER Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }// end for + + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue(this.ll_telegram.getTelegramType()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (this.ll_telegram.getTrClass() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.ll_telegram.getOpCode() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue(this.ll_telegram.getResCode() ); //Stage Logging 용 + //수신전문의 응답코드 설정 + batchDoc.getBatchMsg().getBody().setLastResCode(this.ll_telegram.getResCode()); + // 전문 header 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramHeader(new String(boutHeader.toByteArray())); + + //============================================================================================== + // 수신한 헤더의 '전문종별코드' 값으로 해당 전문 처리용 텔레그램 ID를 찾아낸다. + logger.debug("{} ▶ {전문종별코드} 값에 의한 전문 BODY 수신 Telegram 정보 검색......", logHeader); + String recvTelegramID = this.ll_telegram.getRealRecvTelegram(); + if (recvTelegramID.equalsIgnoreCase("")) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_UNEXPECTED_TELEGRAM, new String[] {this.ll_telegram.getTelegramType(), strRuleCode, strPhaseCode}); + return batchDoc; + } + + TelegramInfoVO recvTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(recvTelegramID); + String strRecvTelegramClsName = recvTelegramVO.getTelegramClsName(); + String strRecvMsgMetaDstcd = recvTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName(strRecvTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (strRecvMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 BODY 수신 Telegram ID = "+ recvTelegramID +"]", logHeader); + logger.debug("{} ☞ [전문 BODY 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 BODY 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 전문헤더 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.ll_telegram.doValidation() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPostExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스에서 오류 응답코드를 설정하고도 return true를 한 경우를 체크 + if (!this.ll_telegram.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) { + doErrorAction(this.ll_telegram, "BECEAIFJM028", new String[] { strLenTelegramClsName }); //전문 HEADER 수신 클래스에서 오류 응답코드 설정 후 true 가 리턴되었습니다. 해당 클래스를 검토 바랍니다. ({1}) + return batchDoc; + } + + //############################################################################################## + // 이하 BODY 처리 부분 # + //############################################################################################## + + //============================================================================================== + // 수신용 텔레그램 인스탄스를 생성시킨다. + logger.debug("{} ▶ 전문 BODY 수신 Telegram Class 생성...... ("+ strRecvTelegramClsName +")", logHeader); + this.rv_telegram = (TelegramService)Class.forName(strRecvTelegramClsName).newInstance(); + if (this.rv_telegram == null) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + // 텔레그램인스탄스에 메시지 메타코드를 지정하고, EAIBatchMessage를 지정한다. + this.rv_telegram.setEAIBatchMessage(batchDoc); + this.rv_telegram.setTelegramCode(strRecvMsgMetaDstcd); + this.rv_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문 Body 수신 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문결정용 텔레그램 (ll_telegram)의 수신필드 값을 실제 텔레그램(rv_telegram)으로 복사한다. + logger.debug("{} ▶ (전문 HEADER 수신 데이터 -> 전문 BODY 수신 데이터) 복사......", logHeader); + for (int i=0; i< this.ll_telegram.getFieldCount(); i++) { + this.rv_telegram.setFieldDataByIndex(i, this.ll_telegram.getFieldDataByIndex(i)); + } + + //============================================================================================== + // Header 전문필드 값 복사 후 전문 Body를 수신하기 전에 Header 값을 가지고 전처리할 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecuteAfterCopy() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecuteAfterCopy() == false) { + doErrorAction(this.rv_telegram, "BECEAIFJM024", new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + //더 읽어들일 필드가 있다면... + if (this.ll_telegram.getFieldCount() < this.rv_telegram.getFieldCount()) { + logger.debug("{} ▶ SOCKET 에서 전문 BODY 데이터 수신 대기중......", logHeader); + } + for (int i=this.ll_telegram.getFieldCount(); i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 nRemainBytes 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + logger.info("{} ☞ 전문 BODY Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(bout.toByteArray()) +"] ["+ item.getFieldName() +"]", logHeader); + + //읽어들인 필드 데이터 저장 + this.rv_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutBody.write(bout.toByteArray()); //Stage Logging 용 (body formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM026", new String[] { item.getFieldName() }); //전문 BODY Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + + //비정형 길이('XX')인 경우 + } else { + + //Informal 필드의 길이 계산 (읽어들일 길이 = '전문길이'필드 값 - Informal필드 이전에 읽어들인 전체 길이) + int nInformalFldLen = this.rv_telegram.getCalculatedLength(i); + if (nInformalFldLen < 0) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_FIELD_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + byte[] aInformalBuffer = new byte[4096]; + int nRemainBytes = nInformalFldLen; + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(strRecvMsgMetaDstcd, i+1); //log용 + + //Socket 에서 Informal 필드 데이터 Read (계산된 필드 길이만큼 읽어들인다.) + try { + while (nRemainBytes > 0) { + int nInformalBuffer = (nRemainBytes > 4096)? 4096 : nRemainBytes; + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aInformalBuffer, nInformalBuffer); //한번에 nInformalBuffer 길이만큼 읽지 않을수도 있음 + nRemainBytes -= nReadBytes; + + //읽어들인 데이터를 파일로 저장 + boolean successSave = this.rv_telegram.doInformalField(i, aInformalBuffer, nReadBytes); + if (successSave == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_ACTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + } + logger.info("{} ☞ 전문 BODY Informal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader); + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Informal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM027", new String[] { item.getFieldName() }); //전문 BODY Informal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }//end if + }//end for + + // 전문 body 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramBody(new String(boutBody.toByteArray())); + + //============================================================================================== + // 전문 Body 수신 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.rv_telegram.doValidation() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPostExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.rv_telegram.getOpCode() ); //Stage Logging 용 + + //============================================================================================== + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. + //(다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록) + super.setPreviousTelegramComponent(this.rv_telegram); + + //============================================================================================== + // 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 맞는 다음 단계 결정 + logger.debug("{} ▶ 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 따른 다음 단계 결정......", logHeader); + this.nextPhaseInfoVO = this.rv_telegram.getNextStage(); + + //조건에 맞는 다음 단계를 찾은 경우 + if (this.nextPhaseInfoVO != null) { + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"]", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계가 없는데 응답코드가 '정상'이 아니고, 작업유형이 응답송수신인 경우 오류전문을 송신한다. + } else if (!this.rv_telegram.getSendResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) && + (batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND) || + batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_RECEIVE))) { + logger.error("{} ☞ ★★★★★ 다음 단계 못 찾았음 ★★★★★ => 오류전문 전송", logHeader); + this.nextPhaseInfoVO = (PhaseInfoVO)curr_poss_stage.get(0); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"] (오류전문 송신용)", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계를 못찾은 경우 + } else { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_NOTFOUND_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + } + + public int recvData(DataInputStream din, int timeoutMilisec, int timeoutRepeatCount, byte[] buffer, int len) throws Exception + { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + int timoutCount = 0; + + String recievedData = batchDoc.getBatchMsg().getBody().getRecvedMsg(); + int rlen = recievedData.getBytes().length; + if ( rlen > len ) { // 이미 읽어 메모리에 가지고 있는 데이터가 읽어야 할 데이터 보다 많으면 + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, len); + batchDoc.getBatchMsg().getBody().setRecvedMsg( StringUtil.substring( recievedData, len)); + return len; + } else{ + if ( rlen > 0 ){ + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, rlen); + } + batchDoc.getBatchMsg().getBody().setRecvedMsg( "" ); + } + if ( rlen == len ) + return len; + int i = 0; + while (true) { + try { + i++; + readBytes = din.read(buffer, rlen, len - rlen); + if (readBytes < 0) { + String errMsg = ExceptionUtil.getErrorCode(ErrorKeys.ERROR_END_OF_STREAM); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + if (logger.isInfo()) { + byte[] dumpBuffer = Arrays.copyOfRange(buffer, rlen, len - rlen); + logger.info("Recv <<<<<< {}", LoggingUtil.asciiDump(dumpBuffer)); + logger.info("Recv <<<<<< {}", LoggingUtil.hexDump(dumpBuffer)); + } + return readBytes+ rlen; //socket 에서 읽어들인 byte 수 리턴 (1 이상) + + } catch (SocketTimeoutException ex) { + timoutCount++; + logger.warn("{"+logHeader+"} ☆☆☆☆☆ SocketTimeoutException 발생 !! ☆☆☆☆☆", ex); + logger.warn("{"+logHeader+"} >>> [Timeout 발생회수 : "+ timoutCount +"], [Timeout 반복설정회수 : "+ timeoutRepeatCount +"], [soTimeout : "+ (timeoutMilisec/1000) +"]"); + if (timoutCount > timeoutRepeatCount) { + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_TIMEOUT_OVER, new String[] { timoutCount+"", (timeoutMilisec/1000)+"" }); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초] + } + continue; + } catch (java.io.IOException ex) { // 20240627 + logger.warn("{"+logHeader+"} ★★★★★ Socket 에서 데이터 수신 시 IOExceptionIOException 발생 ",ex); + logger.warn("★★★★★ Socket 에서 데이터 수신 시 IOExceptionIOException 발생 ! readBytes:"+readBytes); + if(i < 5) + continue; + else { + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_EXCEPTION); + throw new Exception(errMsg); + } + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + logger.error("{} ★★★★★ Socket 에서 데이터 수신 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_EXCEPTION); + /* + System.out.println("recv socket : "+ socket ); + System.out.println("recv socket.isBound() : "+ socket.isBound() ); + System.out.println("recv socket.isClosed() : "+ socket.isClosed() ); + System.out.println("recv socket.isConnected() : "+ socket.isConnected() ); + System.out.println("recv socket.isInputShutdown() : "+ socket.isInputShutdown() ); + System.out.println("recv socket.isOutputShutdown() : "+ socket.isOutputShutdown()); + */ + //예외발생시 socket 종료 (remote에서 socket을 끊어도 socket.isClosed() 가 false 를 반환할 수 있다.) + bs_man.closeRunningSocket(strUUID); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + } + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/RECV2.java b/src/com/eactive/eai/batch/job/jobModule/Component/RECV2.java new file mode 100644 index 0000000..22fc2bb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/RECV2.java @@ -0,0 +1,501 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LoggingUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramItemVO; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * Rule에 정의된 {전문종별코드} 만을 수신하는 RECV Flow Component (정의되지 않은 전문은 무시함) + */ +public class RECV2 extends JobComponent implements JobComponentService +{ + + private TelegramService ll_telegram = null; + private TelegramService rv_telegram = null; + + ByteArrayOutputStream boutHeader = new ByteArrayOutputStream(); + ByteArrayOutputStream boutBody = new ByteArrayOutputStream(); + + /** + * JobComponentService functions + */ + public BatchDoc execute() throws Exception + { + + // UUID, 흐름규칙 코드 구하기 + logger.debug("{} ■ Node Count = " + batchDoc.getBatchMsg().getBody().getNodeCount(), logHeader); + + //============================================================================================== + // 소켓을 찾는다. + logger.debug("{} ▶ SOCKET 검색......", logHeader); + socket = bs_man.getRunningSocket(strUUID); + if (socket == null ) { + doErrorAction(null, ErrorKeys.ERROR_NO_SOCKET, new String[] {strUUID}); + return batchDoc; + } + DataInputStream din = new DataInputStream(socket.getInputStream()); + + //============================================================================================== + // RECV 단계의 타임아웃과 반복시도 횟수값을 알아내기위한 공용저장공간 뒤지기 + logger.debug("{} ▶ JobProcessData 검색......", logHeader); + HashMap currdata_hm = JobProcessData.getInstance().getBatchStageData(strUUID); + if (currdata_hm == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_PROCDATA, new String[] {strUUID}); + return batchDoc; + } + @SuppressWarnings("unchecked") + ArrayList curr_poss_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (curr_poss_stage == null || curr_poss_stage.size() == 0) { + doErrorAction(null, ErrorKeys.ERROR_NO_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + + //============================================================================================== + // PhaseInfo 정보에서 RECV 용 TIMEOUT과 반복 횟수를 읽어들인다. + logger.debug("{} ▶ SOCKET Timeout 설정......", logHeader); + PhaseInfoVO pvo = curr_poss_stage.get(0); + int nTimeout = pvo.getTOVal() * 1000; // 타임아웃 시간 (msec) + int nRepeatCount = pvo.getRepeat(); + socket.setSoTimeout(nTimeout); + logger.debug("{} ☞ [Timeout = " + pvo.getTOVal() + "초], [Retry count = " + nRepeatCount +"]", logHeader); + + //############################################################################################## + // 이하 HEADER 처리 부분 # + //############################################################################################## + + //============================================================================================== + // EAIBatchMessage의 노드정보에서 전문결정용 텔레그램 클래스를 찾아낸다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram 정보 검색......", logHeader); + String strTelegramID = batchDoc.getBatchMsg().getPhaseinfo().getLengthTelegramID(); + int nLengthFieldIdx = batchDoc.getBatchMsg().getPhaseinfo().getLengthFieldIndex(); + + TelegramInfoVO lenTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(strTelegramID); + if (lenTelegramVO == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_TELEGRAM_ID, new String[] {strRuleCode, strPhaseCode, strTelegramID}); + return batchDoc; + } + String strLenTelegramClsName = lenTelegramVO.getTelegramClsName(); + String strLenMsgMetaDstcd = lenTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName(strLenTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (strLenMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 HEADER 수신 Telegram ID = "+ strTelegramID +"], [{전문종별코드} 필드 Index = "+ nLengthFieldIdx +"]", logHeader); + logger.debug("{} ☞ [전문 HEADER 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 HEADER 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 길이결정 텔러그램 클래스를 생성한다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram Class 생성...... ("+ strLenTelegramClsName +")", logHeader); + this.ll_telegram = (TelegramService) Class.forName(strLenTelegramClsName).newInstance(); + if (this.ll_telegram == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + // 길이결정용 텔레그램 인스탄스에 BatchDoc 지정하고 메시지메타코드도 지정한다. + this.ll_telegram.setEAIBatchMessage(batchDoc); + this.ll_telegram.setTelegramCode(strLenMsgMetaDstcd); + this.ll_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문헤더 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPreExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 소켓에서 필드별로 데이터를 읽어들인다. + logger.debug("{} ▶ SOCKET 에서 전문 HEADER 데이터 수신 대기중......", logHeader); + for (int i=0; i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + String msg = new String(aField); + logger.debug("{} ☞ 전문 HEADER Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ msg +"] ["+ item.getFieldName() +"]", logHeader); + if ( msg.trim().equals("")){ + logger.debug("{} ☞ 전문 DATA HEXADUMP \n"+ CommonLib.getDumpMessage(aField) , logHeader); + } + //읽어들인 필드 데이터 저장 + this.ll_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutHeader.write(bout.toByteArray()); //Stage Logging 용 (header formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 HEADER Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM025", new String[] { item.getFieldName() }); //전문 HEADER Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }// end for + + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue(this.ll_telegram.getTelegramType()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (this.ll_telegram.getTrClass() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.ll_telegram.getOpCode() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue(this.ll_telegram.getResCode() ); //Stage Logging 용 + //수신전문의 응답코드 설정 + batchDoc.getBatchMsg().getBody().setLastResCode(this.ll_telegram.getResCode()); + // 전문 header 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramHeader(new String(boutHeader.toByteArray())); + + //============================================================================================== + // 수신한 헤더의 '전문종별코드' 값으로 해당 전문 처리용 텔레그램 ID를 찾아낸다. + logger.debug("{} ▶ {전문종별코드} 값에 의한 전문 BODY 수신 Telegram 정보 검색......", logHeader); + String recvTelegramID = this.ll_telegram.getRealRecvTelegram(); + if (recvTelegramID.equalsIgnoreCase("")) { + //################################### RECV1 과 다른 부분 ################################### + logger.warn("{"+logHeader+"} ☞ ☆☆☆☆☆ Rule 에 정의되지 않은 {전문종별코드} 수신 됨 ☆☆☆☆☆"); + // 다음단계를 지정하지 않았으므로 , 다시 동일한 단계 수행. + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_UNEXPECTED_TELEGRAM_IGNORE, new String[] { this.ll_telegram.getTelegramType() }); + + //garvage 데이터 크기를 구해서, 통신자원에서 제거해준다. + int nGarvageSize = this.ll_telegram.getRemainDataLength(); + if (nGarvageSize < 0) { + doErrorAction(this.ll_telegram, "BECEAIFJM029"); //통신자원에서 해제하기 위한 전문 BODY 의 잔여 데이터 사이즈를 구할 수 없습니다. 전문결정 Telegram Class 검토가 필요합니다. + return batchDoc; + } + logger.info("{} ☞ [전문 BODY 잔여 데이터 사이즈 = " + nGarvageSize + "]", logHeader); + + byte[] aGarvageBuffer = new byte[4096]; + int nRemainBytes = nGarvageSize; + + //Socket 에서 남아있는 전체 데이터 Read (계산된 필드 길이만큼 읽어들인다.) + try { + while (nRemainBytes > 0) { + int nReadLen = (nRemainBytes > 4096)? 4096 : nRemainBytes; + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aGarvageBuffer, nReadLen); //한번에 aGarvageBuffer 길이만큼 읽지 않을수도 있음 + nRemainBytes -= nReadBytes; + + // noop (읽은 데이터는 버린다) + } + logger.info("{} ☞ 전문 BODY 잔여 데이터 수신 완료 !!", logHeader); + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY 잔여 데이터 수신 실패 ★★★★★", logHeader); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM030"); //통신자원에서 해제하기 위한 전문 BODY 의 잔여 데이터 수신 시 오류가 발생하였습니다. + return batchDoc; + } + + return batchDoc; + //########################################################################################## + } + + TelegramInfoVO recvTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(recvTelegramID); + String strRecvTelegramClsName = recvTelegramVO.getTelegramClsName(); + String strRecvMsgMetaDstcd = recvTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName(strRecvTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (strRecvMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 BODY 수신 Telegram ID = "+ recvTelegramID +"]", logHeader); + logger.debug("{} ☞ [전문 BODY 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 BODY 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 전문헤더 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.ll_telegram.doValidation() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPostExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스에서 오류 응답코드를 설정하고도 return true를 한 경우를 체크 + if (!this.ll_telegram.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) { + doErrorAction(this.ll_telegram, "BECEAIFJM028", new String[] { strLenTelegramClsName }); //전문 HEADER 수신 클래스에서 오류 응답코드 설정 후 true 가 리턴되었습니다. 해당 클래스를 검토 바랍니다. ({1}) + return batchDoc; + } + + //############################################################################################## + // 이하 BODY 처리 부분 # + //############################################################################################## + + //============================================================================================== + // 수신용 텔레그램 인스탄스를 생성시킨다. + logger.debug("{} ▶ 전문 BODY 수신 Telegram Class 생성...... ("+ strRecvTelegramClsName +")", logHeader); + this.rv_telegram = (TelegramService)Class.forName(strRecvTelegramClsName).newInstance(); + if (this.rv_telegram == null) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + // 텔레그램인스탄스에 메시지 메타코드를 지정하고, EAIBatchMessage를 지정한다. + this.rv_telegram.setEAIBatchMessage(batchDoc); + this.rv_telegram.setTelegramCode(strRecvMsgMetaDstcd); + this.rv_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문 Body 수신 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문결정용 텔레그램 (ll_telegram)의 수신필드 값을 실제 텔레그램(rv_telegram)으로 복사한다. + logger.debug("{} ▶ (전문 HEADER 수신 데이터 -> 전문 BODY 수신 데이터) 복사......", logHeader); + for (int i=0; i< this.ll_telegram.getFieldCount(); i++) { + this.rv_telegram.setFieldDataByIndex(i, this.ll_telegram.getFieldDataByIndex(i)); + } + + //============================================================================================== + // Header 전문필드 값 복사 후 전문 Body를 수신하기 전에 Header 값을 가지고 전처리할 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecuteAfterCopy() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecuteAfterCopy() == false) { + doErrorAction(this.rv_telegram, "BECEAIFJM024", new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + //더 읽어들일 필드가 있다면... + if (this.ll_telegram.getFieldCount() < this.rv_telegram.getFieldCount()) { + logger.debug("{} ▶ SOCKET 에서 전문 BODY 데이터 수신 대기중......", logHeader); + } + for (int i=this.ll_telegram.getFieldCount(); i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 nRemainBytes 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + logger.info("{} ☞ 전문 BODY Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(bout.toByteArray()) +"] ["+ item.getFieldName() +"]", logHeader); + + //읽어들인 필드 데이터 저장 + this.rv_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutBody.write(bout.toByteArray()); //Stage Logging 용 (body formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM026", new String[] { item.getFieldName() }); //전문 BODY Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + + //비정형 길이('XX')인 경우 + } else { + + //Informal 필드의 길이 계산 (읽어들일 길이 = '전문길이'필드 값 - Informal필드 이전에 읽어들인 전체 길이) + int nInformalFldLen = this.rv_telegram.getCalculatedLength(i); + if (nInformalFldLen < 0) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_FIELD_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + byte[] aInformalBuffer = new byte[4096]; + int nRemainBytes = nInformalFldLen; + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(strRecvMsgMetaDstcd, i+1); //log용 + + //Socket 에서 Informal 필드 데이터 Read (계산된 필드 길이만큼 읽어들인다.) + try { + while (nRemainBytes > 0) { + int nInformalBuffer = (nRemainBytes > 4096)? 4096 : nRemainBytes; + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aInformalBuffer, nInformalBuffer); //한번에 nInformalBuffer 길이만큼 읽지 않을수도 있음 + nRemainBytes -= nReadBytes; + + //읽어들인 데이터를 파일로 저장 + boolean successSave = this.rv_telegram.doInformalField(i, aInformalBuffer, nReadBytes); + if (successSave == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_ACTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + } + logger.info("{} ☞ 전문 BODY Informal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader); + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Informal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM027", new String[] { item.getFieldName() }); //전문 BODY Informal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }//end if + }//end for + + // 전문 body 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramBody(new String(boutBody.toByteArray())); + + //============================================================================================== + // 전문 Body 수신 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.rv_telegram.doValidation() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPostExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.rv_telegram.getOpCode() ); //Stage Logging 용 + + //============================================================================================== + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. + //(다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록) + super.setPreviousTelegramComponent(this.rv_telegram); + + //============================================================================================== + // 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 맞는 다음 단계 결정 + logger.debug("{} ▶ 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 따른 다음 단계 결정......", logHeader); + this.nextPhaseInfoVO = this.rv_telegram.getNextStage(); + + //조건에 맞는 다음 단계를 찾은 경우 + if (this.nextPhaseInfoVO != null) { + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"]", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계가 없는데 응답코드가 '정상'이 아니고, 작업유형이 응답송수신인 경우 오류전문을 송신한다. + } else if (!this.rv_telegram.getSendResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) && + (batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND) || + batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_RECEIVE))) { + logger.error("{} ☞ ★★★★★ 다음 단계 못 찾았음 ★★★★★ => 오류전문 전송", logHeader); + this.nextPhaseInfoVO = (PhaseInfoVO)curr_poss_stage.get(0); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"] (오류전문 송신용)", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계를 못찾은 경우 + } else { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_NOTFOUND_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + } + + public int recvData(DataInputStream din, int timeoutMilisec, int timeoutRepeatCount, byte[] buffer, int len) throws Exception + { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + int timoutCount = 0; + + while (true) { + try { + readBytes = din.read(buffer, 0, len); + if (readBytes < 0) { + String errMsg = ExceptionUtil.getErrorCode(ErrorKeys.ERROR_END_OF_STREAM); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + if (logger.isInfo()) { + byte[] dumpBuffer = Arrays.copyOfRange(buffer, 0, len); + logger.info("Recv <<<<<< {}", LoggingUtil.asciiDump(dumpBuffer)); + logger.info("Recv <<<<<< {}", LoggingUtil.hexDump(dumpBuffer)); + } + return readBytes; //socket 에서 읽어들인 byte 수 리턴 (1 이상) + + } catch (SocketTimeoutException ex) { + timoutCount++; + logger.warn("{"+logHeader+"} ☆☆☆☆☆ SocketTimeoutException 발생 !! ☆☆☆☆☆", ex); + logger.warn("{"+logHeader+"} >>> [Timeout 발생회수 : "+ timoutCount +"], [Timeout 반복설정회수 : "+ timeoutRepeatCount +"], [soTimeout : "+ (timeoutMilisec/1000) +"]"); + if (timoutCount > timeoutRepeatCount) { + String errMsg = ExceptionUtil.getErrorCode(ErrorKeys.ERROR_TIMEOUT_OVER, new String[] { timoutCount+"", (timeoutMilisec/1000)+"" }); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초] + } + continue; + + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + logger.error("{} ★★★★★ Socket 에서 데이터 수신 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_EXCEPTION); + /* + System.out.println("recv socket : "+ socket ); + System.out.println("recv socket.isBound() : "+ socket.isBound() ); + System.out.println("recv socket.isClosed() : "+ socket.isClosed() ); + System.out.println("recv socket.isConnected() : "+ socket.isConnected() ); + System.out.println("recv socket.isInputShutdown() : "+ socket.isInputShutdown() ); + System.out.println("recv socket.isOutputShutdown() : "+ socket.isOutputShutdown()); + */ + //예외발생시 socket 종료 (remote에서 socket을 끊어도 socket.isClosed() 가 false 를 반환할 수 있다.) + bs_man.closeRunningSocket(strUUID); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + } + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/RECVM.java b/src/com/eactive/eai/batch/job/jobModule/Component/RECVM.java new file mode 100644 index 0000000..5020cbb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/RECVM.java @@ -0,0 +1,675 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramItemVO; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * Rule에 정의되지 않은 {전문종별코드} 수신 시 작업을 중지하는 RECV Flow Component + */ +public class RECVM extends JobComponent implements JobComponentService +{ + + private TelegramService ll_telegram = null; + private TelegramService rv_telegram = null; + private byte[] LL_STRING = {(byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x30}; + + ByteArrayOutputStream boutHeader = new ByteArrayOutputStream(); + ByteArrayOutputStream boutBody = new ByteArrayOutputStream(); + + /** + * JobComponentService functions + */ + public BatchDoc execute() throws Exception + { + + // UUID, 흐름규칙 코드 구하기 + logger.debug("{} ■ Node Count = " + batchDoc.getBatchMsg().getBody().getNodeCount(), logHeader); + + //============================================================================================== + // 소켓을 찾는다. + logger.debug("{} ▶ SOCKET 검색......", logHeader); + socket = bs_man.getRunningSocket(strUUID); + if (socket == null ) { + doErrorAction(null, ErrorKeys.ERROR_NO_SOCKET, new String[] {strUUID}); + return batchDoc; + } + DataInputStream din = new DataInputStream(socket.getInputStream()); + + //============================================================================================== + // RECV 단계의 타임아웃과 반복시도 횟수값을 알아내기위한 공용저장공간 뒤지기 + logger.debug("{} ▶ JobProcessData 검색......", logHeader); + HashMap currdata_hm = JobProcessData.getInstance().getBatchStageData(strUUID); + if (currdata_hm == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_PROCDATA, new String[] {strUUID}); + return batchDoc; + } + @SuppressWarnings("unchecked") + ArrayList curr_poss_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (curr_poss_stage == null || curr_poss_stage.size() == 0) { + doErrorAction(null, ErrorKeys.ERROR_NO_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + + //============================================================================================== + // PhaseInfo 정보에서 RECV 용 TIMEOUT과 반복 횟수를 읽어들인다. + logger.debug("{} ▶ SOCKET Timeout 설정......", logHeader); + PhaseInfoVO pvo = curr_poss_stage.get(0); + int nTimeout = pvo.getTOVal() * 1000; // 타임아웃 시간 (msec) + int nRepeatCount = pvo.getRepeat(); + socket.setSoTimeout(nTimeout); + logger.debug("{} ☞ [Timeout = " + pvo.getTOVal() + "초], [Retry count = " + nRepeatCount +"]", logHeader); + + //############################################################################################## + // 이하 HEADER 처리 부분 # + //############################################################################################## + + //============================================================================================== + // EAIBatchMessage의 노드정보에서 전문결정용 텔레그램 클래스를 찾아낸다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram 정보 검색......", logHeader); + String strTelegramID = batchDoc.getBatchMsg().getPhaseinfo().getLengthTelegramID(); + int nLengthFieldIdx = batchDoc.getBatchMsg().getPhaseinfo().getLengthFieldIndex(); + + TelegramInfoVO lenTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(strTelegramID); + if (lenTelegramVO == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_TELEGRAM_ID, new String[] {strRuleCode, strPhaseCode, strTelegramID}); + return batchDoc; + } + String strLenTelegramClsName = lenTelegramVO.getTelegramClsName(); + String strLenMsgMetaDstcd = lenTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName(strLenTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (strLenMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 HEADER 수신 Telegram ID = "+ strTelegramID +"], [{전문종별코드} 필드 Index = "+ nLengthFieldIdx +"]", logHeader); + logger.debug("{} ☞ [전문 HEADER 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 HEADER 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 길이결정 텔러그램 클래스를 생성한다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram Class 생성...... ("+ strLenTelegramClsName +")", logHeader); + this.ll_telegram = (TelegramService) Class.forName(strLenTelegramClsName).newInstance(); + if (this.ll_telegram == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + // 길이결정용 텔레그램 인스탄스에 BatchDoc 지정하고 메시지메타코드도 지정한다. + this.ll_telegram.setEAIBatchMessage(batchDoc); + this.ll_telegram.setTelegramCode(strLenMsgMetaDstcd); + this.ll_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문헤더 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPreExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + this.ll_telegram.setFieldDataByIndex(0, LL_STRING); + boutHeader.write(LL_STRING); //Stage Logging 용 (header formal 데이터) + + //============================================================================================== + // 소켓에서 필드별로 데이터를 읽어들인다. + logger.debug("{} ▶ SOCKET 에서 전문 HEADER 데이터 수신 대기중......", logHeader); + for (int i=1; i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + String msg = new String(aField); + logger.debug("{} ☞ 전문 HEADER Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ msg +"] ["+ item.getFieldName() +"]", logHeader); + if ( msg.trim().equals("")){ + logger.debug("{} ☞ 전문 DATA HEXADUMP \n"+ CommonLib.getDumpMessage(aField) , logHeader); + } + //읽어들인 필드 데이터 저장 + this.ll_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutHeader.write(bout.toByteArray()); //Stage Logging 용 (header formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 HEADER Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM025", new String[] { item.getFieldName() }); //전문 HEADER Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }// end for + + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue(this.ll_telegram.getTelegramType()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (this.ll_telegram.getTrClass() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.ll_telegram.getOpCode() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue(this.ll_telegram.getResCode() ); //Stage Logging 용 + //수신전문의 응답코드 설정 + batchDoc.getBatchMsg().getBody().setLastResCode(this.ll_telegram.getResCode()); + // 전문 header 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramHeader(new String(boutHeader.toByteArray())); + + //============================================================================================== + // 수신한 헤더의 '전문종별코드' 값으로 해당 전문 처리용 텔레그램 ID를 찾아낸다. + logger.debug("{} ▶ {전문종별코드} 값에 의한 전문 BODY 수신 Telegram 정보 검색......", logHeader); + String recvTelegramID = this.ll_telegram.getRealRecvTelegram(); + if (recvTelegramID.equalsIgnoreCase("")) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_UNEXPECTED_TELEGRAM, new String[] {this.ll_telegram.getTelegramType(), strRuleCode, strPhaseCode}); + return batchDoc; + } + + TelegramInfoVO recvTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(recvTelegramID); + String strRecvTelegramClsName = recvTelegramVO.getTelegramClsName(); + String strRecvMsgMetaDstcd = recvTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName(strRecvTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (strRecvMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 BODY 수신 Telegram ID = "+ recvTelegramID +"]", logHeader); + logger.debug("{} ☞ [전문 BODY 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 BODY 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 전문헤더 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.ll_telegram.doValidation() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPostExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스에서 오류 응답코드를 설정하고도 return true를 한 경우를 체크 + if (!this.ll_telegram.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) { + doErrorAction(this.ll_telegram, "BECEAIFJM028", new String[] { strLenTelegramClsName }); //전문 HEADER 수신 클래스에서 오류 응답코드 설정 후 true 가 리턴되었습니다. 해당 클래스를 검토 바랍니다. ({1}) + return batchDoc; + } + + //############################################################################################## + // 이하 BODY 처리 부분 # + //############################################################################################## + + //============================================================================================== + // 수신용 텔레그램 인스탄스를 생성시킨다. + logger.debug("{} ▶ 전문 BODY 수신 Telegram Class 생성...... ("+ strRecvTelegramClsName +")", logHeader); + this.rv_telegram = (TelegramService)Class.forName(strRecvTelegramClsName).newInstance(); + if (this.rv_telegram == null) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + // 텔레그램인스탄스에 메시지 메타코드를 지정하고, EAIBatchMessage를 지정한다. + this.rv_telegram.setEAIBatchMessage(batchDoc); + this.rv_telegram.setTelegramCode(strRecvMsgMetaDstcd); + this.rv_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문 Body 수신 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문결정용 텔레그램 (ll_telegram)의 수신필드 값을 실제 텔레그램(rv_telegram)으로 복사한다. + logger.debug("{} ▶ (전문 HEADER 수신 데이터 -> 전문 BODY 수신 데이터) 복사......", logHeader); + for (int i=0; i< this.ll_telegram.getFieldCount(); i++) { + this.rv_telegram.setFieldDataByIndex(i, this.ll_telegram.getFieldDataByIndex(i)); + } + + //============================================================================================== + // Header 전문필드 값 복사 후 전문 Body를 수신하기 전에 Header 값을 가지고 전처리할 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecuteAfterCopy() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecuteAfterCopy() == false) { + doErrorAction(this.rv_telegram, "BECEAIFJM024", new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + //더 읽어들일 필드가 있다면... + if (this.ll_telegram.getFieldCount() < this.rv_telegram.getFieldCount()) { + logger.debug("{} ▶ SOCKET 에서 전문 BODY 데이터 수신 대기중......", logHeader); + } + for (int i=this.ll_telegram.getFieldCount(); i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 nRemainBytes 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + logger.info("{} ☞ 전문 BODY Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(bout.toByteArray()) +"] ["+ item.getFieldName() +"]", logHeader); + + //읽어들인 필드 데이터 저장 + this.rv_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutBody.write(bout.toByteArray()); //Stage Logging 용 (body formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM026", new String[] { item.getFieldName() }); //전문 BODY Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + + //비정형 길이('XX')인 경우 + } else { + + //Informal 필드의 길이 계산 (읽어들일 길이 = '전문길이'필드 값 - Informal필드 이전에 읽어들인 전체 길이) + int nInformalFldLen = this.rv_telegram.getCalculatedLength(i); + if (nInformalFldLen < 0) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_FIELD_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + byte[] aInformalBuffer = new byte[4096]; + int nRemainBytes = nInformalFldLen; + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(strRecvMsgMetaDstcd, i+1); //log용 + + //Socket 에서 Informal 필드 데이터 Read (계산된 필드 길이만큼 읽어들인다.) + try { + while (nRemainBytes > 0) { + int nInformalBuffer = (nRemainBytes > 4096)? 4096 : nRemainBytes; + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aInformalBuffer, nInformalBuffer); //한번에 nInformalBuffer 길이만큼 읽지 않을수도 있음 + nRemainBytes -= nReadBytes; + + //읽어들인 데이터를 파일로 저장 + boolean successSave = this.rv_telegram.doInformalField(i, aInformalBuffer, nReadBytes); + if ( aInformalBuffer[nReadBytes-1] == 0x03){ + break; + } + if (successSave == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_ACTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + } + logger.info("{} ☞ 전문 BODY Informal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader); + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Informal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM027", new String[] { item.getFieldName() }); //전문 BODY Informal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }//end if + }//end for + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // 메가팩 대응 최종 필드 수신 시작 + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + if ( this.ll_telegram.getFieldCount() < this.rv_telegram.getFieldCount() ){ + int inx = this.rv_telegram.getFieldCount() - 1; + + //해당 필드 사이즈 조회 (integer 또는 'XX') + String strFldLen = this.rv_telegram.getFieldLength(inx); + + //정형 길이인 경우 + if (!strFldLen.trim().equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) { + + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + int nFldLen = Integer.parseInt(strFldLen) + 1; + byte[] aField = new byte[nFldLen]; + int nRemainBytes = nFldLen; + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(strRecvMsgMetaDstcd, inx+1); //log용 + + //Socket 에서 해당 필드 데이터 Read (필드 길이만큼 읽어들인다.) + try { + while (nRemainBytes > 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 nRemainBytes 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + logger.info("{} ☞ 전문 BODY Formal 필드 수신 완료 => "+ (inx+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(bout.toByteArray()) +"] ["+ item.getFieldName() +"]", logHeader); + + //읽어들인 필드 데이터 저장 + byte[] recvData = new byte[bout.toByteArray().length -1]; + System.arraycopy(bout.toByteArray(), 0, recvData, 0, recvData.length); + this.rv_telegram.setFieldDataByIndex(inx, recvData); + boutBody.write(recvData); //Stage Logging 용 (body formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Formal 필드 수신 실패 ★★★★★ => "+ (inx+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM026", new String[] { item.getFieldName() }); //전문 BODY Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + + //비정형 길이('XX')인 경우 + } else { + +// //Informal 필드의 길이 계산 (읽어들일 길이 = '전문길이'필드 값 - Informal필드 이전에 읽어들인 전체 길이) +// int nInformalFldLen = this.rv_telegram.getCalculatedLength(i); +// if (nInformalFldLen < 0) { +// doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_FIELD_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); +// this.rv_telegram.doPostExecute(); +// return batchDoc; +// } + + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + byte[] aInformalBuffer = new byte[4096]; +// int nRemainBytes = nInformalFldLen; + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(strRecvMsgMetaDstcd, inx+1); //log용 + + //Socket 에서 Informal 필드 데이터 Read (계산된 필드 길이만큼 읽어들인다.) + try { + + int nReadBytes = this.recvData2(din, nTimeout, nRepeatCount, aInformalBuffer, 4096); //한번에 nInformalBuffer 길이만큼 읽지 않을수도 있음 + + //읽어들인 데이터를 파일로 저장 + boolean successSave = this.rv_telegram.doInformalField(inx, aInformalBuffer, nReadBytes); + + if (successSave == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_ACTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + logger.info("{} ☞ 전문 BODY Informal 필드 수신 완료 => "+ (inx+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nReadBytes +"(사이즈)] ["+ item.getFieldName() +"]", logHeader); + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Informal 필드 수신 실패 ★★★★★ => "+ (inx+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] [XXX(사이즈)] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM027", new String[] { item.getFieldName() }); //전문 BODY Informal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }//end if + + + + + }else{ // 헤더 수신 콤포넌트의 필드 개수와 전문 수신 콤포넌트의 필드 개수가 같으면 + // 헤더 필드의 마지막은 XX가 아닐것이다. 더 이상 읽을 필드가 없으며 EEFE만 처리하면 된다. + byte[] eof = new byte[2]; + this.recvData(din, nTimeout, nRepeatCount, eof, 2); + } + /////////////////////////////////////////////////////////////////////////////////////////////////////// + // 메가팩 대응 최종 필드 수신 종료 + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + + + + // 전문 body 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramBody(new String(boutBody.toByteArray())); + + //============================================================================================== + // 전문 Body 수신 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.rv_telegram.doValidation() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPostExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.rv_telegram.getOpCode() ); //Stage Logging 용 + + //============================================================================================== + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. + //(다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록) + super.setPreviousTelegramComponent(this.rv_telegram); + + //============================================================================================== + // 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 맞는 다음 단계 결정 + logger.debug("{} ▶ 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 따른 다음 단계 결정......", logHeader); + this.nextPhaseInfoVO = this.rv_telegram.getNextStage(); + + //조건에 맞는 다음 단계를 찾은 경우 + if (this.nextPhaseInfoVO != null) { + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"]", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계가 없는데 응답코드가 '정상'이 아니고, 작업유형이 응답송수신인 경우 오류전문을 송신한다. + } else if (!this.rv_telegram.getSendResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) && + (batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND) || + batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_RECEIVE))) { + logger.error("{} ☞ ★★★★★ 다음 단계 못 찾았음 ★★★★★ => 오류전문 전송", logHeader); + this.nextPhaseInfoVO = (PhaseInfoVO)curr_poss_stage.get(0); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"] (오류전문 송신용)", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계를 못찾은 경우 + } else { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_NOTFOUND_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + } + + public int recvData(DataInputStream din, int timeoutMilisec, int timeoutRepeatCount, byte[] buffer, int len) throws Exception + { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + int timoutCount = 0; + + String recievedData = batchDoc.getBatchMsg().getBody().getRecvedMsg(); + int rlen = recievedData.getBytes().length; + if ( rlen > len ) { // 이미 읽어 메모리에 가지고 있는 데이터가 읽어야 할 데이터 보다 많으면 + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, len); + batchDoc.getBatchMsg().getBody().setRecvedMsg( StringUtil.substring( recievedData, len)); + return len; + } else{ + if ( rlen > 0 ){ + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, rlen); + } + batchDoc.getBatchMsg().getBody().setRecvedMsg( "" ); + } + if ( rlen == len ) + return len; + + while (true) { + try { + readBytes = din.read(buffer, rlen, len - rlen); + if (readBytes < 0) { + String errMsg = ExceptionUtil.getErrorCode(ErrorKeys.ERROR_END_OF_STREAM); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + + // 여기서 읽어 들인 buffer를 검사하여 FFFF가 있으면 FF로 치환 하여야 한다. + int procBytes = readBytes; + ByteArrayOutputStream tempBuffer = new ByteArrayOutputStream(); + for ( int inx = rlen; inx < rlen + readBytes; inx++){ + if ( buffer[inx] == (byte)0xff){ + inx++; + procBytes --; + //}else{ + + } + if ( ( inx > rlen + readBytes -1) && (buffer[inx-1] == (byte)0xff) ){ // 마지막 바이트가 ff 이면 한바이트 더 읽어서 처리 해야 한다. + byte[] mbuffer = new byte[1]; + din.read(mbuffer, 0, 1); + tempBuffer.write(mbuffer, 0, 1); + procBytes ++; + break; + }else{ + tempBuffer.write(buffer, inx, 1); + } + } + + System.arraycopy(tempBuffer.toByteArray(), 0, buffer, rlen, procBytes ); + + + return procBytes+ rlen; //socket 에서 읽어들인 byte 수 리턴 (1 이상) + + } catch (SocketTimeoutException ex) { + timoutCount++; + logger.warn("{"+logHeader+"} ☆☆☆☆☆ SocketTimeoutException 발생 !! ☆☆☆☆☆", ex); + logger.warn("{"+logHeader+"} >>> [Timeout 발생회수 : "+ timoutCount +"], [Timeout 반복설정회수 : "+ timeoutRepeatCount +"], [soTimeout : "+ (timeoutMilisec/1000) +"]"); + if (timoutCount > timeoutRepeatCount) { + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_TIMEOUT_OVER, new String[] { timoutCount+"", (timeoutMilisec/1000)+"" }); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초] + } + continue; + + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + logger.error("{} ★★★★★ Socket 에서 데이터 수신 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_EXCEPTION); + /* + System.out.println("recv socket : "+ socket ); + System.out.println("recv socket.isBound() : "+ socket.isBound() ); + System.out.println("recv socket.isClosed() : "+ socket.isClosed() ); + System.out.println("recv socket.isConnected() : "+ socket.isConnected() ); + System.out.println("recv socket.isInputShutdown() : "+ socket.isInputShutdown() ); + System.out.println("recv socket.isOutputShutdown() : "+ socket.isOutputShutdown()); + */ + //예외발생시 socket 종료 (remote에서 socket을 끊어도 socket.isClosed() 가 false 를 반환할 수 있다.) + bs_man.closeRunningSocket(strUUID); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + } + } + } + + public int recvData2(DataInputStream din, int timeoutMilisec, int timeoutRepeatCount, byte[] buffer, int len) throws Exception + { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + int timoutCount = 0; + + String recievedData = batchDoc.getBatchMsg().getBody().getRecvedMsg(); + int rlen = recievedData.getBytes().length; + if ( rlen > len ) { // 이미 읽어 메모리에 가지고 있는 데이터가 읽어야 할 데이터 보다 많으면 + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, len); + batchDoc.getBatchMsg().getBody().setRecvedMsg( StringUtil.substring( recievedData, len)); + return len; + } else{ + if ( rlen > 0 ){ + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, rlen); + } + batchDoc.getBatchMsg().getBody().setRecvedMsg( "" ); + } + if ( rlen == len ) + return len; + + while (true) { + try { + readBytes = din.read(buffer, rlen, 1); + if (readBytes < 0) { + String errMsg = ExceptionUtil.getErrorCode(ErrorKeys.ERROR_END_OF_STREAM); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + //return readBytes+ rlen; //socket 에서 읽어들인 byte 수 리턴 (1 이상) + if ( buffer[rlen] == (byte)0xff ){ + byte[] tbuffer = new byte[1]; + din.read(tbuffer, 0, 1); + if ( tbuffer[0] == (byte)0xef ){ + return rlen; + } + } + rlen += readBytes; + + } catch (SocketTimeoutException ex) { + timoutCount++; + logger.warn("{"+logHeader+"} ☆☆☆☆☆ SocketTimeoutException 발생 !! ☆☆☆☆☆", ex); + logger.warn("{"+logHeader+"}>>> [Timeout 발생회수 : "+ timoutCount +"], [Timeout 반복설정회수 : "+ timeoutRepeatCount +"], [soTimeout : "+ (timeoutMilisec/1000) +"]"); + if (timoutCount > timeoutRepeatCount) { + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_TIMEOUT_OVER, new String[] { timoutCount+"", (timeoutMilisec/1000)+"" }); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초] + } + continue; + + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + logger.error("{} ★★★★★ Socket 에서 데이터 수신 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_EXCEPTION); + /* + System.out.println("recv socket : "+ socket ); + System.out.println("recv socket.isBound() : "+ socket.isBound() ); + System.out.println("recv socket.isClosed() : "+ socket.isClosed() ); + System.out.println("recv socket.isConnected() : "+ socket.isConnected() ); + System.out.println("recv socket.isInputShutdown() : "+ socket.isInputShutdown() ); + System.out.println("recv socket.isOutputShutdown() : "+ socket.isOutputShutdown()); + */ + //예외발생시 socket 종료 (remote에서 socket을 끊어도 socket.isClosed() 가 false 를 반환할 수 있다.) + bs_man.closeRunningSocket(strUUID); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + } + } + } + + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/RECVX.java b/src/com/eactive/eai/batch/job/jobModule/Component/RECVX.java new file mode 100644 index 0000000..2e46acf --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/RECVX.java @@ -0,0 +1,480 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramItemVO; +import com.eactive.eai.batch.telegram.TelegramManager; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * Rule에 정의되지 않은 {전문종별코드} 수신 시 작업을 중지하는 RECV Flow Component + */ +public class RECVX extends JobComponent implements JobComponentService +{ + + private TelegramService ll_telegram = null; + private TelegramService rv_telegram = null; + + ByteArrayOutputStream boutHeader = new ByteArrayOutputStream(); + ByteArrayOutputStream boutBody = new ByteArrayOutputStream(); + + /** + * JobComponentService functions + */ + public BatchDoc execute() throws Exception + { + + // UUID, 흐름규칙 코드 구하기 + logger.debug("{} ■ Node Count = " + batchDoc.getBatchMsg().getBody().getNodeCount(), logHeader); + + //============================================================================================== + // 소켓을 찾는다. + logger.debug("{} ▶ SOCKET 검색......", logHeader); + socket = bs_man.getRunningSocket(strUUID); + if (socket == null ) { + doErrorAction(null, ErrorKeys.ERROR_NO_SOCKET, new String[] {strUUID}); + return batchDoc; + } + DataInputStream din = new DataInputStream(socket.getInputStream()); + + //============================================================================================== + // RECV 단계의 타임아웃과 반복시도 횟수값을 알아내기위한 공용저장공간 뒤지기 + logger.debug("{} ▶ JobProcessData 검색......", logHeader); + HashMap currdata_hm = JobProcessData.getInstance().getBatchStageData(strUUID); + if (currdata_hm == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_PROCDATA, new String[] {strUUID}); + return batchDoc; + } + @SuppressWarnings("unchecked") + ArrayList curr_poss_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (curr_poss_stage == null || curr_poss_stage.size() == 0) { + doErrorAction(null, ErrorKeys.ERROR_NO_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + + //============================================================================================== + // PhaseInfo 정보에서 RECV 용 TIMEOUT과 반복 횟수를 읽어들인다. + logger.debug("{} ▶ SOCKET Timeout 설정......", logHeader); + PhaseInfoVO pvo = curr_poss_stage.get(0); + int nTimeout = pvo.getTOVal() * 1000; // 타임아웃 시간 (msec) + int nRepeatCount = pvo.getRepeat(); + socket.setSoTimeout(nTimeout); + logger.debug("{} ☞ [Timeout = " + pvo.getTOVal() + "초], [Retry count = " + nRepeatCount +"]", logHeader); + + //############################################################################################## + // 이하 HEADER 처리 부분 # + //############################################################################################## + + //============================================================================================== + // EAIBatchMessage의 노드정보에서 전문결정용 텔레그램 클래스를 찾아낸다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram 정보 검색......", logHeader); + String strTelegramID = batchDoc.getBatchMsg().getPhaseinfo().getLengthTelegramID(); + int nLengthFieldIdx = batchDoc.getBatchMsg().getPhaseinfo().getLengthFieldIndex(); + + TelegramInfoVO lenTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(strTelegramID); + if (lenTelegramVO == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_TELEGRAM_ID, new String[] {strRuleCode, strPhaseCode, strTelegramID}); + return batchDoc; + } + String strLenTelegramClsName = lenTelegramVO.getTelegramClsName(); + String strLenMsgMetaDstcd = lenTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName(strLenTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (strLenMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 HEADER 수신 Telegram ID = "+ strTelegramID +"], [{전문종별코드} 필드 Index = "+ nLengthFieldIdx +"]", logHeader); + logger.debug("{} ☞ [전문 HEADER 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 HEADER 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 길이결정 텔러그램 클래스를 생성한다. + logger.debug("{} ▶ 전문 HEADER 수신 Telegram Class 생성...... ("+ strLenTelegramClsName +")", logHeader); + this.ll_telegram = (TelegramService) Class.forName(strLenTelegramClsName).newInstance(); + if (this.ll_telegram == null) { + doErrorAction(null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + // 길이결정용 텔레그램 인스탄스에 BatchDoc 지정하고 메시지메타코드도 지정한다. + this.ll_telegram.setEAIBatchMessage(batchDoc); + this.ll_telegram.setTelegramCode(strLenMsgMetaDstcd); + this.ll_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문헤더 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPreExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 소켓에서 필드별로 데이터를 읽어들인다. + logger.debug("{} ▶ SOCKET 에서 전문 HEADER 데이터 수신 대기중......", logHeader); + for (int i=0; i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + String msg = new String(aField); + logger.debug("{} ☞ 전문 HEADER Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ msg +"] ["+ item.getFieldName() +"]", logHeader); + if ( msg.trim().equals("")){ + logger.debug("{} ☞ 전문 DATA HEXADUMP \n"+ CommonLib.getDumpMessage(aField) , logHeader); + } + //읽어들인 필드 데이터 저장 + this.ll_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutHeader.write(bout.toByteArray()); //Stage Logging 용 (header formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 HEADER Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM025", new String[] { item.getFieldName() }); //전문 HEADER Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }// end for + + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue(this.ll_telegram.getTelegramType()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (this.ll_telegram.getTrClass() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.ll_telegram.getOpCode() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue(this.ll_telegram.getResCode() ); //Stage Logging 용 + //수신전문의 응답코드 설정 + batchDoc.getBatchMsg().getBody().setLastResCode(this.ll_telegram.getResCode()); + // 전문 header 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramHeader(new String(boutHeader.toByteArray())); + + //============================================================================================== + // 수신한 헤더의 '전문종별코드' 값으로 해당 전문 처리용 텔레그램 ID를 찾아낸다. + logger.debug("{} ▶ {전문종별코드} 값에 의한 전문 BODY 수신 Telegram 정보 검색......", logHeader); + String recvTelegramID = this.ll_telegram.getRealRecvTelegram(); + if (recvTelegramID.equalsIgnoreCase("")) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_UNEXPECTED_TELEGRAM, new String[] {this.ll_telegram.getTelegramType(), strRuleCode, strPhaseCode}); + return batchDoc; + } + + TelegramInfoVO recvTelegramVO = TelegramInfoManager.getInstance().getTelegramInfo(recvTelegramID); + String strRecvTelegramClsName = recvTelegramVO.getTelegramClsName(); + String strRecvMsgMetaDstcd = recvTelegramVO.getMsgMetaDstcd(); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName(strRecvTelegramClsName); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (strRecvMsgMetaDstcd ); //Stage Logging 용 + logger.debug("{} ☞ [전문 BODY 수신 Telegram ID = "+ recvTelegramID +"]", logHeader); + logger.debug("{} ☞ [전문 BODY 수신 Telegram Class = "+ strLenTelegramClsName +"], [전문 BODY 수신 전문메시지ID = "+ strLenMsgMetaDstcd +"]", logHeader); + + //============================================================================================== + // 전문헤더 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.ll_telegram.doValidation() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.ll_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 HEADER 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.ll_telegram.doPostExecute() == false) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {strTelegramID, strLenTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문헤더 클래스에서 오류 응답코드를 설정하고도 return true를 한 경우를 체크 + if (!this.ll_telegram.getResolveResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS)) { + doErrorAction(this.ll_telegram, "BECEAIFJM028", new String[] { strLenTelegramClsName }); //전문 HEADER 수신 클래스에서 오류 응답코드 설정 후 true 가 리턴되었습니다. 해당 클래스를 검토 바랍니다. ({1}) + return batchDoc; + } + + //############################################################################################## + // 이하 BODY 처리 부분 # + //############################################################################################## + + //============================================================================================== + // 수신용 텔레그램 인스탄스를 생성시킨다. + logger.debug("{} ▶ 전문 BODY 수신 Telegram Class 생성...... ("+ strRecvTelegramClsName +")", logHeader); + this.rv_telegram = (TelegramService)Class.forName(strRecvTelegramClsName).newInstance(); + if (this.rv_telegram == null) { + doErrorAction(this.ll_telegram, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + // 텔레그램인스탄스에 메시지 메타코드를 지정하고, EAIBatchMessage를 지정한다. + this.rv_telegram.setEAIBatchMessage(batchDoc); + this.rv_telegram.setTelegramCode(strRecvMsgMetaDstcd); + this.rv_telegram.setNextStageInfo(curr_poss_stage); + + //============================================================================================== + // 전문 Body 수신 클래스의 doPreExecute() 메소드를 호출한다. (전문필드 배열 생성) + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + // 전문결정용 텔레그램 (ll_telegram)의 수신필드 값을 실제 텔레그램(rv_telegram)으로 복사한다. + logger.debug("{} ▶ (전문 HEADER 수신 데이터 -> 전문 BODY 수신 데이터) 복사......", logHeader); + for (int i=0; i< this.ll_telegram.getFieldCount(); i++) { + this.rv_telegram.setFieldDataByIndex(i, this.ll_telegram.getFieldDataByIndex(i)); + } + + //============================================================================================== + // Header 전문필드 값 복사 후 전문 Body를 수신하기 전에 Header 값을 가지고 전처리할 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPreExecuteAfterCopy() 메소드 호출......", logHeader); + if (this.rv_telegram.doPreExecuteAfterCopy() == false) { + doErrorAction(this.rv_telegram, "BECEAIFJM024", new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + //============================================================================================== + //더 읽어들일 필드가 있다면... + if (this.ll_telegram.getFieldCount() < this.rv_telegram.getFieldCount()) { + logger.debug("{} ▶ SOCKET 에서 전문 BODY 데이터 수신 대기중......", logHeader); + } + for (int i=this.ll_telegram.getFieldCount(); i 0) { + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aField, nRemainBytes); //한번에 nRemainBytes 길이만큼 읽지 않을수도 있음 + bout.write(aField, 0, nReadBytes); + nRemainBytes -= nReadBytes; + } + logger.info("{} ☞ 전문 BODY Formal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(bout.toByteArray()) +"] ["+ item.getFieldName() +"]", logHeader); + + //읽어들인 필드 데이터 저장 + this.rv_telegram.setFieldDataByIndex(i, bout.toByteArray()); + boutBody.write(bout.toByteArray()); //Stage Logging 용 (body formal 데이터) + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Formal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM026", new String[] { item.getFieldName() }); //전문 BODY Formal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + + //비정형 길이('XX')인 경우 + } else { + + //Informal 필드의 길이 계산 (읽어들일 길이 = '전문길이'필드 값 - Informal필드 이전에 읽어들인 전체 길이) + int nInformalFldLen = this.rv_telegram.getCalculatedLength(i); + if (nInformalFldLen < 0) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_FIELD_LENGTH, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + byte[] aInformalBuffer = new byte[4096]; + int nRemainBytes = nInformalFldLen; + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(strRecvMsgMetaDstcd, i+1); //log용 + + //Socket 에서 Informal 필드 데이터 Read (계산된 필드 길이만큼 읽어들인다.) + try { + while (nRemainBytes > 0) { + int nInformalBuffer = (nRemainBytes > 4096)? 4096 : nRemainBytes; + int nReadBytes = this.recvData(din, nTimeout, nRepeatCount, aInformalBuffer, nInformalBuffer); //한번에 nInformalBuffer 길이만큼 읽지 않을수도 있음 + nRemainBytes -= nReadBytes; + + //읽어들인 데이터를 파일로 저장 + boolean successSave = this.rv_telegram.doInformalField(i, aInformalBuffer, nReadBytes); + if ( aInformalBuffer[nReadBytes-1] == 0x03){ + break; + } + if (successSave == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_INFORMAL_ACTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + } + logger.info("{} ☞ 전문 BODY Informal 필드 수신 완료 => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader); + + } catch (Exception ex) { + logger.error("{} ☞ ★★★★★ 전문 BODY Informal 필드 수신 실패 ★★★★★ => "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nInformalFldLen +"(사이즈)] ["+ item.getFieldName() +"]", logHeader, ex); + doErrorAction(ex, this.ll_telegram, "BECEAIFJM027", new String[] { item.getFieldName() }); //전문 BODY Informal 필드 [{1}] 수신 시 오류가 발생하였습니다. + return batchDoc; + } + //ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + }//end if + }//end for + + // 전문 body 수신 데이터 설정 + batchDoc.getBatchMsg().setTelegramBody(new String(boutBody.toByteArray())); + + //============================================================================================== + // 전문 Body 수신 클래스의 doExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doValidation() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doValidation() 메소드 호출......", logHeader); + if (this.rv_telegram.doValidation() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_RECV_VALIDATION); + this.rv_telegram.doPostExecute(); + return batchDoc; + } + + //============================================================================================== + // 전문 Body 수신 클래스의 doPostExecute() 메소드를 호출한다. + logger.debug("{} ▶ 전문 BODY 수신 클래스의 doPostExecute() 메소드 호출......", logHeader); + if (this.rv_telegram.doPostExecute() == false) { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_POST_EXECUTION, new String[] {recvTelegramID, strRecvTelegramClsName}); + return batchDoc; + } + + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (this.rv_telegram.getOpCode() ); //Stage Logging 용 + + //============================================================================================== + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. + //(다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록) + super.setPreviousTelegramComponent(this.rv_telegram); + + //============================================================================================== + // 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 맞는 다음 단계 결정 + logger.debug("{} ▶ 조건(전문종별코드,업무관리코드,거래구분코드,응답코드) 에 따른 다음 단계 결정......", logHeader); + this.nextPhaseInfoVO = this.rv_telegram.getNextStage(); + + //조건에 맞는 다음 단계를 찾은 경우 + if (this.nextPhaseInfoVO != null) { + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"]", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계가 없는데 응답코드가 '정상'이 아니고, 작업유형이 응답송수신인 경우 오류전문을 송신한다. + } else if (!this.rv_telegram.getSendResponseCode().equals(TelegramKeys.RPS_HDB_RET_CODE_SUCCESS) && + (batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND) || + batchDoc.getBatchMsg().getHeader().getProcessType().equals(CommonKeys.PROCESS_RESPONSE_RECEIVE))) { + logger.error("{} ☞ ★★★★★ 다음 단계 못 찾았음 ★★★★★ => 오류전문 전송", logHeader); + this.nextPhaseInfoVO = (PhaseInfoVO)curr_poss_stage.get(0); + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.info("{} ☞ [다음 단계 Pahse Code = "+ nextPhaseInfoVO.getNextPhaseCode() +"] (오류전문 송신용)", logHeader); + return batchDoc; + + //조건에 맞는 다음 단계를 못찾은 경우 + } else { + doErrorAction(this.rv_telegram, ErrorKeys.ERROR_NOTFOUND_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + } + + public int recvData(DataInputStream din, int timeoutMilisec, int timeoutRepeatCount, byte[] buffer, int len) throws Exception + { + if (buffer == null || buffer.length == 0) throw new Exception(""); + + int readBytes = 0; + int timoutCount = 0; + + String recievedData = batchDoc.getBatchMsg().getBody().getRecvedMsg(); + int rlen = recievedData.getBytes().length; + if ( rlen > len ) { // 이미 읽어 메모리에 가지고 있는 데이터가 읽어야 할 데이터 보다 많으면 + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, len); + batchDoc.getBatchMsg().getBody().setRecvedMsg( StringUtil.substring( recievedData, len)); + return len; + } else{ + if ( rlen > 0 ){ + System.arraycopy( recievedData.getBytes(), 0, buffer, 0, rlen); + } + batchDoc.getBatchMsg().getBody().setRecvedMsg( "" ); + } + if ( rlen == len ) + return len; + + while (true) { + try { + readBytes = din.read(buffer, rlen, len - rlen); + if (readBytes < 0) { + String errMsg = ExceptionUtil.getErrorCode(ErrorKeys.ERROR_END_OF_STREAM); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다. + } + return readBytes+ rlen; //socket 에서 읽어들인 byte 수 리턴 (1 이상) + + } catch (SocketTimeoutException ex) { + timoutCount++; + logger.warn("{"+logHeader+"} ☆☆☆☆☆ SocketTimeoutException 발생 !! ☆☆☆☆☆", ex); + logger.warn("{"+logHeader+"} >>> [Timeout 발생회수 : "+ timoutCount +"], [Timeout 반복설정회수 : "+ timeoutRepeatCount +"], [soTimeout : "+ (timeoutMilisec/1000) +"]"); + if (timoutCount > timeoutRepeatCount) { + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_TIMEOUT_OVER, new String[] { timoutCount+"", (timeoutMilisec/1000)+"" }); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초] + } + continue; + + } catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException + logger.error("{} ★★★★★ Socket 에서 데이터 수신 시 오류 발생 !! ★★★★★", logHeader, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, ErrorKeys.ERROR_EXCEPTION); + /* + System.out.println("recv socket : "+ socket ); + System.out.println("recv socket.isBound() : "+ socket.isBound() ); + System.out.println("recv socket.isClosed() : "+ socket.isClosed() ); + System.out.println("recv socket.isConnected() : "+ socket.isConnected() ); + System.out.println("recv socket.isInputShutdown() : "+ socket.isInputShutdown() ); + System.out.println("recv socket.isOutputShutdown() : "+ socket.isOutputShutdown()); + */ + //예외발생시 socket 종료 (remote에서 socket을 끊어도 socket.isClosed() 가 false 를 반환할 수 있다.) + bs_man.closeRunningSocket(strUUID); + throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다. + } + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/SEND1.java b/src/com/eactive/eai/batch/job/jobModule/Component/SEND1.java new file mode 100644 index 0000000..c9d2682 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/SEND1.java @@ -0,0 +1,254 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LoggingUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramItemVO; +import com.eactive.eai.batch.telegram.TelegramManager; + +/** + * 정형필드 및 비정형필드 데이터 전체를 버퍼에 담아서 한번에 전송하는 SEND Flow Component + */ +public class SEND1 extends JobComponent implements JobComponentService +{ + + private static int DEFAULT_PACKET_SIZE = 4096; + + /** + * JobComponentService functions + */ + public BatchDoc execute() throws Exception + { + //logger.info("{} 현 " + this.C_TYPE + " 단계 시작합니다. " , logHeader); + + // UUID, 흐름규칙 코드 구하기 + logger.debug("{} 1. node count [" + batchDoc.getBatchMsg().getBody().getNodeCount() + "]", logHeader); + + // 2. 현 단계 시작 시간 셋팅 + //batchDoc.getEAIBatchMessage().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash16()); + // 3. 소켓을 찾는다. + socket = bs_man.getRunningSocket(strUUID); + if (socket == null ) { + logger.error("{} 일괄처리용 소켓을 찾을 수 없습니다.", logHeader); + // socket 이 없다면... + doErrorAction(null, ErrorKeys.ERROR_NO_SOCKET, new String[] {strUUID}); + return batchDoc; + } +// DataInputStream din = new DataInputStream(socket.getInputStream()); + DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); + logger.debug("{} 2. found socket", logHeader); + // 4. LifeCycle을 통해 현 단계 룰정보를 읽어온다. + JobProcessData jobdata_Manager = JobProcessData.getInstance(); + HashMap currdata_hm = jobdata_Manager.getBatchStageData(strUUID); + if (currdata_hm == null) { + logger.error("{} JobProcessData 가 지정된 UUID 로 없습니다. 체크해보세요.. ", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_PROCDATA, new String[] {strUUID}); + return batchDoc; + } + @SuppressWarnings("unchecked") + ArrayList curr_poss_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (curr_poss_stage == null || curr_poss_stage.size() == 0) { + logger.error("{} 현재 단계의 다음진행사항 데이터가 지정되어 있지 않습니다. ", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + // 5. Telegram 클래스의 이름을 알아낸다. - SEND 일때는 한가지뿐이다. + // - RECEIVE 일때는 NODEINFO에서 얻어낸다. + // SEND단계 에서 무조건 첫번째 PhaseInfoVO를 읽어들이도록 한다. + // SEND단계 에서 보낼수 있는 전문의 종류는 오직 한 종류 이어야 한다. + PhaseInfoVO pvo = curr_poss_stage.get(0); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (pvo.getPhaseSeq() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(pvo.getTelegramID()); //Stage Logging 용 + String strTelegramID = pvo.getTelegramID().trim(); + String strTelegramType = pvo.getTelegramType(); + if (strTelegramID.length() == 0) { + logger.error("{} SEND stage : No TELEGRAM_ID assigned in DB table", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_TELEGRAM_ID, new String[] {strRuleCode, strPhaseCode, strTelegramID}); + return batchDoc; + } else { + logger.debug("{} 3. 현단계 텔레그램 전문 ID [" + strTelegramID + "]", logHeader); + } + // 6. 텔러그램 클래스를 생성한다. + // >> 텔레그램 클래스를 찾자 --> TelegramInfoDAO + TelegramInfoVO telegraminfoVO = TelegramInfoManager.getInstance().getTelegramInfo(strTelegramID); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName(telegraminfoVO.getTelegramClsName()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (telegraminfoVO.getMsgMetaDstcd() ); //Stage Logging 용 + logger.debug("{} 3.1. 전문 송신 클래스 생성...", logHeader); + logger.debug("{} => @@@@@@@@@@@@@@@@@@@@@@@@@@@@ ClassName: ["+ telegraminfoVO.getTelegramClsName() +"] @@@@@@@@@@@@@@@@@@@@@@@@@@@@", logHeader); + TelegramService telegramInst = null; + try { + telegramInst= (TelegramService)Class.forName(telegraminfoVO.getTelegramClsName()).newInstance(); + if (telegramInst == null) { + // 지정된 클래스가 없다... 장애처리 + logger.error("{} 지정된 이름을 가지는 클래스가 없습니다. telegramInst is null", logHeader);// 20250910 npe telegramInst 삭제 + doErrorAction(null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + telegramInst.setTelegramType(strTelegramType); + } catch (Exception e) { + doErrorAction(e, null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + logger.debug("{} 4. telegram class [" + telegraminfoVO.getTelegramClsName() + "] generated ok", logHeader); + // 6.1 여기에서 텔레그램클래스에서 필요한 값들을 셋팅해 준다. : 전문종별, 거래구분코드, 응답코드, 업무관리구분 + String strSndValue_TelegramType = pvo.getTelegramType(); + String strSndValue_OpCode = pvo.getOpCode(); + String strSndValue_TrClass = pvo.getTrClass(); + + // 7. 텔레그램 클래스 인스탄스에 EAIBatchMessageDocument를 지정한다. + telegramInst.setEAIBatchMessage(batchDoc); + // 8. 텔레그램 클래스에 메시지메타코드 를 지정해준다. + telegramInst.setTelegramCode(telegraminfoVO.getMsgMetaDstcd()); + // 9. 메시지메타코드를 이용하여 전문의 각 필드를 생성해준다. + boolean rcB = telegramInst.doPreExecute(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doPreExecute 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + // 10. RULE DB에서 읽은 조립시 참조값들을 넣어준다. + telegramInst.setFldTelegramType(strSndValue_TelegramType); + telegramInst.setFldOpCode(strSndValue_OpCode); + telegramInst.setFldTrClass(strSndValue_TrClass); + logger.debug("{} 5. get basic value for compiling telegram", logHeader); + // 11. 송신전문을 조립한다. + boolean rcCompile = telegramInst.doExecute(); + if (!rcCompile) { + logger.error("{} 전문조립중 장애 발생 ", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_EXECUTION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue(telegramInst.getTelegramType()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (telegramInst.getTrClass() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (telegramInst.getOpCode() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue(telegramInst.getResCode() ); //Stage Logging 용 + logger.debug("{} 6. doExecute called : compile ok!", logHeader); + // 12. 조립된 송신전문 Validation + rcB = telegramInst.doValidation(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doValidation 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_SEND_VALIDATION); + return batchDoc; + } + logger.debug("{} 7. doValidation called ", logHeader); + // 13. 소켓을 WRITE 한다. + try { + ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); + int nDataLength = telegramInst.getSendLength(); // 총 송신 대상 길이 + logger.info("{} telegram length to send is " + nDataLength + " :텔레그램 데이터 송신시작 ", logHeader); + + for (int i=0; i OK", logHeader); + + } else { + byte[] aField = telegramInst.getFieldDataByIndex(i); + outBuffer.write(aField, 0, aField.length); + + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(telegraminfoVO.getMsgMetaDstcd(), i+1); //log용 + logger.info("{} - Wrote FORMAL field data to buffer : "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"] => OK", logHeader); + } + } + if (outBuffer.size() > 0 && outBuffer.size() == nDataLength) { + byte[] byteArray = outBuffer.toByteArray(); + if (logger.isInfo()) { + logger.info("Send >>>>>> {}", LoggingUtil.asciiDump(byteArray)); + logger.info("Send >>>>>> {}", LoggingUtil.hexDump(byteArray)); + } + dout.write(byteArray, 0, byteArray.length); + logger.info("{} >>> Wrote FORMAL & INFORMAL field data to socket : " + outBuffer.size() + " bytes", logHeader); + + } else { + logger.error("{} SEND function failed : no data found in ByteArrayOutputStream", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_SHORT_WRITE_ERROR, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName(), nDataLength+"", outBuffer.size()+""}); + telegramInst.doPostExecute(); + return batchDoc; + } + logger.debug("{} 8. all Field sent ok : " + telegramInst.getFieldCount(), logHeader); + + } catch (Exception ex) { + logger.error("{} ★★★★★ socket write error !! ★★★★★", logHeader, ex); + doErrorAction(ex, telegramInst, ErrorKeys.ERROR_WRITE_ERROR); + telegramInst.doPostExecute(); + return batchDoc; + } + + // 14. 실행 후 작업 수행 + rcB = telegramInst.doPostExecute(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doPostValidation 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_POST_EXECUTION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + logger.debug("{} 9. doPostExecute called", logHeader); + + // 텔레그램클래스에 넘겨주었던 배치메세지를 다시 받는다. + this.batchDoc = telegramInst.getEAIBatchMessage(); + + // 15. 현 단계 수행 전문을 일단 저장 + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. (다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록) + super.setPreviousTelegramComponent(telegramInst); + + // 16. 다음 단계 결정 : 실질적인 다음 단계 결정은 각 텔레그램 클래스 에서 하도록 하자 + telegramInst.setNextStageInfo(curr_poss_stage); + this.nextPhaseInfoVO = telegramInst.getNextStage(); + // 다음단계를 찾을 수 없으면 장애처리하도록 한다. - 20060406 by khs + if (this.nextPhaseInfoVO == null) { + // 정상적인 다음 단계를 찾을 수 없는 경우... + logger.error("{} not found next stage ... ["+telegramInst.getTelegramType()+"]", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_NOTFOUND_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.debug("{} 10. decide next Stage [" + batchDoc.getBatchMsg().getBody().getNextPhaseCode()+"]", logHeader); + // 17. 현 단계 종료 시간 셋팅 + //batchDoc.getEAIBatchMessage().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash16()); + // 현 단계에 대한 로깅 20060410 by khs + //LogUtil.setLog(batchDoc); + return batchDoc; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/SEND2.java b/src/com/eactive/eai/batch/job/jobModule/Component/SEND2.java new file mode 100644 index 0000000..4775abb --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/SEND2.java @@ -0,0 +1,258 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.common.LoggingUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramItemVO; +import com.eactive.eai.batch.telegram.TelegramManager; + +/** + * 정형필드 는 버퍼에 모아서 전송하고 비정형 필드는 패킷 사이즈 만큼 반복적으로 전송하는 SEND Flow Component + */ +public class SEND2 extends JobComponent implements JobComponentService +{ + + private static int DEFAULT_PACKET_SIZE = 4096; + + /** + * JobComponentService functions + */ + public BatchDoc execute() throws Exception + { + //logger.info("{} 현 " + this.C_TYPE + " 단계 시작합니다. " , logHeader); + + // UUID, 흐름규칙 코드 구하기 + logger.debug("{} 1. node count [" + batchDoc.getBatchMsg().getBody().getNodeCount() + "]", logHeader); + + // 2. 현 단계 시작 시간 셋팅 + //batchDoc.getEAIBatchMessage().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash16()); + // 3. 소켓을 찾는다. + socket = bs_man.getRunningSocket(strUUID); + if (socket == null ) { + logger.error("{} 일괄처리용 소켓을 찾을 수 없습니다.", logHeader); + // socket 이 없다면... + doErrorAction(null, ErrorKeys.ERROR_NO_SOCKET, new String[] {strUUID}); + return batchDoc; + } +// DataInputStream din = new DataInputStream(socket.getInputStream()); + DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); + logger.debug("{} 2. found socket", logHeader); + // 4. LifeCycle을 통해 현 단계 룰정보를 읽어온다. + JobProcessData jobdata_Manager = JobProcessData.getInstance(); + HashMap currdata_hm = jobdata_Manager.getBatchStageData(strUUID); + if (currdata_hm == null) { + logger.error("{} JobProcessData 가 지정된 UUID 로 없습니다. 체크해보세요.. ", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_PROCDATA, new String[] {strUUID}); + return batchDoc; + } + @SuppressWarnings("unchecked") + ArrayList curr_poss_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (curr_poss_stage == null || curr_poss_stage.size() == 0) { + logger.error("{} 현재 단계의 다음진행사항 데이터가 지정되어 있지 않습니다. ", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + // 5. Telegram 클래스의 이름을 알아낸다. - SEND 일때는 한가지뿐이다. + // - RECEIVE 일때는 NODEINFO에서 얻어낸다. + // SEND단계 에서 무조건 첫번째 PhaseInfoVO를 읽어들이도록 한다. + // SEND단계 에서 보낼수 있는 전문의 종류는 오직 한 종류 이어야 한다. + PhaseInfoVO pvo = curr_poss_stage.get(0); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (pvo.getPhaseSeq() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(pvo.getTelegramID()); //Stage Logging 용 + String strTelegramID = pvo.getTelegramID().trim(); + String strTelegramType = pvo.getTelegramType(); + if (strTelegramID.length() == 0) { + logger.error("{} SEND stage : No TELEGRAM_ID assigned in DB table", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_TELEGRAM_ID, new String[] {strRuleCode, strPhaseCode, strTelegramID}); + return batchDoc; + } else { + logger.debug("{} 3. 현단계 텔레그램 전문 ID [" + strTelegramID + "]", logHeader); + } + // 6. 텔러그램 클래스를 생성한다. + // >> 텔레그램 클래스를 찾자 --> TelegramInfoDAO + TelegramInfoVO telegraminfoVO = TelegramInfoManager.getInstance().getTelegramInfo(strTelegramID); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName(telegraminfoVO.getTelegramClsName()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (telegraminfoVO.getMsgMetaDstcd() ); //Stage Logging 용 + logger.debug("{} 3.1. 전문 송신 클래스 생성...", logHeader); + logger.debug("{} => @@@@@@@@@@@@@@@@@@@@@@@@@@@@ ClassName: ["+ telegraminfoVO.getTelegramClsName() +"] @@@@@@@@@@@@@@@@@@@@@@@@@@@@", logHeader); + TelegramService telegramInst = null; + try { + telegramInst= (TelegramService)Class.forName(telegraminfoVO.getTelegramClsName()).newInstance(); + if (telegramInst == null) { + // 지정된 클래스가 없다... 장애처리 + logger.error("{} 지정된 이름을 가지는 클래스가 없습니다. telegramInst is null ", logHeader);// 20250910 npe telegramInst del + doErrorAction(null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + telegramInst.setTelegramType(strTelegramType); + } catch (Exception e) { + doErrorAction(e, null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + logger.debug("{} 4. telegram class [" + telegraminfoVO.getTelegramClsName() + "] generated ok", logHeader); + // 6.1 여기에서 텔레그램클래스에서 필요한 값들을 셋팅해 준다. : 전문종별, 거래구분코드, 응답코드, 업무관리구분 + String strSndValue_TelegramType = pvo.getTelegramType(); + String strSndValue_OpCode = pvo.getOpCode(); + String strSndValue_TrClass = pvo.getTrClass(); + + // 7. 텔레그램 클래스 인스탄스에 EAIBatchMessageDocument를 지정한다. + telegramInst.setEAIBatchMessage(batchDoc); + // 8. 텔레그램 클래스에 메시지메타코드 를 지정해준다. + telegramInst.setTelegramCode(telegraminfoVO.getMsgMetaDstcd()); + // 9. 메시지메타코드를 이용하여 전문의 각 필드를 생성해준다. + boolean rcB = telegramInst.doPreExecute(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doPreExecute 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + // 10. RULE DB에서 읽은 조립시 참조값들을 넣어준다. + telegramInst.setFldTelegramType(strSndValue_TelegramType); + telegramInst.setFldOpCode(strSndValue_OpCode); + telegramInst.setFldTrClass(strSndValue_TrClass); + logger.debug("{} 5. get basic value for compiling telegram", logHeader); + // 11. 송신전문을 조립한다. + boolean rcCompile = telegramInst.doExecute(); + if (!rcCompile) { + logger.error("{} 전문조립중 장애 발생 ", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_EXECUTION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue(telegramInst.getTelegramType()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (telegramInst.getTrClass() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (telegramInst.getOpCode() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue(telegramInst.getResCode() ); //Stage Logging 용 + logger.debug("{} 6. doExecute called : compile ok!", logHeader); + // 12. 조립된 송신전문 Validation + rcB = telegramInst.doValidation(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doValidation 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_SEND_VALIDATION); + return batchDoc; + } + logger.debug("{} 7. doValidation called ", logHeader); + // 13. 소켓을 WRITE 한다. + try { + ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); + int nDataLength = telegramInst.getSendLength(); // 총 송신 대상 길이 + logger.info("{} telegram length to send is " + nDataLength + " :텔레그램 데이터 송신시작 ", logHeader); + + for (int i=0; i 0) { + //비정형 필드 데이터를 송신하기 전에 정형 필드 데이터를 담아놨던 Buffer를 송신한다. + // XX가 맨처음인 경우에는 write 하지 않음. 2009.01.12 + dout.write(outBuffer.toByteArray(), 0, outBuffer.size()); + logger.info("{} >>> Wrote ACCUMULATED FORMAL field data to socket : " + outBuffer.size() + " bytes", logHeader); + //정형 필드 Buffer 초기화 + outBuffer.reset(); //outBuffer = new ByteArrayOutputStream(); + } + + // 비정형 필드의 길이 계산 + int nFieldLength = telegramInst.getCalculatedLength(i); + if (nFieldLength<0) { + logger.error("{} not calculated of informal Field ["+ (i+1) +"] data length", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_INFORMAL_FIELD_LENGTH, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + telegramInst.doPostExecute(); + return batchDoc; + } + int nFieldSentBytes = 0; //비정형필드 데이터 Write(또는 Send) 바이트 + int readLen = 0; + int nPacketSize = batchDoc.getBatchMsg().getHeader().getPacketSize(); + + if (nPacketSize <=0 ){ + logger.info("{} (INFORAML field data read buffer size = "+ nPacketSize +"/ DEFAULT_PACKET_SIZE ["+DEFAULT_PACKET_SIZE+"]로 설정합니다.", logHeader); + nPacketSize = DEFAULT_PACKET_SIZE; //nPacketSize 값이 0보다 크거나 같으면 기본값 4096 설정.. + } + byte[] aBuffer = new byte[nPacketSize]; + logger.info("{} INFORMAL field write start...", logHeader); + logger.info("{} (INFORAML field data read buffer size = "+ nPacketSize +" (= Packet Size))", logHeader); + while (nFieldSentBytes < nFieldLength) { + // 비정형 필드의 데이터를 읽어온다. + readLen = telegramInst.getInformalFieldSendData(i, aBuffer); + if (readLen < 0) { + logger.error("{} read file content error in Telegram [getInformalFieldSendData]", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_READ_FILE, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + telegramInst.doPostExecute(); + return batchDoc; + } + dout.write(aBuffer, 0, readLen); + nFieldSentBytes += readLen; + } + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(telegraminfoVO.getMsgMetaDstcd(), i+1); //log용 + logger.info("{} >>> Wrote INFORMAL field data to socket : "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"(비정형)] ["+ nFieldSentBytes +"(사이즈)]["+ new String(aBuffer) +" ["+ item.getFieldName() +"] => OK", logHeader); + + } else { + byte[] aField = telegramInst.getFieldDataByIndex(i); + outBuffer.write(aField, 0, aField.length); + + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(telegraminfoVO.getMsgMetaDstcd(), i+1); //log용 + logger.info("{} - Wrote FORMAL field data to buffer : "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"] => OK", logHeader); + } + } + if (outBuffer.size() > 0) { + byte[] byteArray = outBuffer.toByteArray(); + if (logger.isInfo()) { + logger.info("Send >>>>>> {}", LoggingUtil.asciiDump(byteArray)); + logger.info("Send >>>>>> {}", LoggingUtil.hexDump(byteArray)); + } + dout.write(byteArray, 0, byteArray.length); + logger.info("{} >>> Wrote ACCUMULATED FORMAL field data to socket : " + outBuffer.size() + " bytes", logHeader); + } + logger.debug("{} 8. all Field sent ok : " + telegramInst.getFieldCount(), logHeader); + + } catch (Exception ex) { + logger.error("{} ★★★★★ socket write error !! ★★★★★", logHeader, ex); + doErrorAction(ex, telegramInst, ErrorKeys.ERROR_WRITE_ERROR); + doErrorAction(telegramInst, ErrorKeys.ERROR_WRITE_ERROR); + telegramInst.doPostExecute(); + return batchDoc; + } + + // 14. 실행 후 작업 수행 + rcB = telegramInst.doPostExecute(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doPostValidation 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_POST_EXECUTION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + logger.debug("{} 9. doPostExecute called", logHeader); + + // 텔레그램클래스에 넘겨주었던 배치메세지를 다시 받는다. + this.batchDoc = telegramInst.getEAIBatchMessage(); + + // 15. 현 단계 수행 전문을 일단 저장 + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. (다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록) + super.setPreviousTelegramComponent(telegramInst); + + // 16. 다음 단계 결정 : 실질적인 다음 단계 결정은 각 텔레그램 클래스 에서 하도록 하자 + telegramInst.setNextStageInfo(curr_poss_stage); + this.nextPhaseInfoVO = telegramInst.getNextStage(); + // 다음단계를 찾을 수 없으면 장애처리하도록 한다. - 20060406 by khs + if (this.nextPhaseInfoVO == null) { + // 정상적인 다음 단계를 찾을 수 없는 경우... + logger.error("{} not found next stage ... ["+telegramInst.getTelegramType()+"]", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_NOTFOUND_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.debug("{} 10. decide next Stage [" + batchDoc.getBatchMsg().getBody().getNextPhaseCode()+"]", logHeader); + // 17. 현 단계 종료 시간 셋팅 + //batchDoc.getEAIBatchMessage().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash16()); + // 현 단계에 대한 로깅 20060410 by khs + //LogUtil.setLog(batchDoc); + return batchDoc; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/Component/SENDM.java b/src/com/eactive/eai/batch/job/jobModule/Component/SENDM.java new file mode 100644 index 0000000..72a83f1 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/Component/SENDM.java @@ -0,0 +1,261 @@ +package com.eactive.eai.batch.job.jobModule.Component; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.batch.job.jobConstant.ErrorKeys; +import com.eactive.eai.batch.job.jobHandle.JobProcessData; +import com.eactive.eai.batch.job.jobItem.TelegramService; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager; +import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO; +import com.eactive.eai.batch.telegram.TelegramItemVO; +import com.eactive.eai.batch.telegram.TelegramManager; + +/** + * 길이바이트를 사용하지 않고 전문 종료 구분자를 전송하는 SEND Flow Component + */ +public class SENDM extends JobComponent implements JobComponentService +{ + + private static int DEFAULT_PACKET_SIZE = 4096; + private byte[] TERM_STRING = {(byte) '\377', (byte) '\357'}; + + /** + * JobComponentService functions + */ + public BatchDoc execute() throws Exception + { + //logger.info("{} 현 " + this.C_TYPE + " 단계 시작합니다. " , logHeader); + + // UUID, 흐름규칙 코드 구하기 + logger.debug("{} 1. node count [" + batchDoc.getBatchMsg().getBody().getNodeCount() + "]", logHeader); + + // 2. 현 단계 시작 시간 셋팅 + //batchDoc.getEAIBatchMessage().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash16()); + // 3. 소켓을 찾는다. + socket = bs_man.getRunningSocket(strUUID); + if (socket == null ) { + logger.error("{} 일괄처리용 소켓을 찾을 수 없습니다.", logHeader); + // socket 이 없다면... + doErrorAction(null, ErrorKeys.ERROR_NO_SOCKET, new String[] {strUUID}); + return batchDoc; + } +// DataInputStream din = new DataInputStream(socket.getInputStream()); + DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); + logger.debug("{} 2. found socket", logHeader); + // 4. LifeCycle을 통해 현 단계 룰정보를 읽어온다. + JobProcessData jobdata_Manager = JobProcessData.getInstance(); + HashMap currdata_hm = jobdata_Manager.getBatchStageData(strUUID); + if (currdata_hm == null) { + logger.error("{} JobProcessData 가 지정된 UUID 로 없습니다. 체크해보세요.. ", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_PROCDATA, new String[] {strUUID}); + return batchDoc; + } + @SuppressWarnings("unchecked") + ArrayList curr_poss_stage = (ArrayList) currdata_hm.get(JobProcessData.PROCDATA_NEXTSTAGE); + if (curr_poss_stage == null || curr_poss_stage.size() == 0) { + logger.error("{} 현재 단계의 다음진행사항 데이터가 지정되어 있지 않습니다. ", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + // 5. Telegram 클래스의 이름을 알아낸다. - SEND 일때는 한가지뿐이다. + // - RECEIVE 일때는 NODEINFO에서 얻어낸다. + // SEND단계 에서 무조건 첫번째 PhaseInfoVO를 읽어들이도록 한다. + // SEND단계 에서 보낼수 있는 전문의 종류는 오직 한 종류 이어야 한다. + PhaseInfoVO pvo = curr_poss_stage.get(0); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (pvo.getPhaseSeq() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(pvo.getTelegramID()); //Stage Logging 용 + String strTelegramID = pvo.getTelegramID().trim(); + String strTelegramType = pvo.getTelegramType(); + if (strTelegramID.length() == 0) { + logger.error("{} SEND stage : No TELEGRAM_ID assigned in DB table", logHeader); + doErrorAction(null, ErrorKeys.ERROR_NO_TELEGRAM_ID, new String[] {strRuleCode, strPhaseCode, strTelegramID}); + return batchDoc; + } else { + logger.debug("{} 3. 현단계 텔레그램 전문 ID [" + strTelegramID + "]", logHeader); + } + // 6. 텔러그램 클래스를 생성한다. + // >> 텔레그램 클래스를 찾자 --> TelegramInfoDAO + TelegramInfoVO telegraminfoVO = TelegramInfoManager.getInstance().getTelegramInfo(strTelegramID); + batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName(telegraminfoVO.getTelegramClsName()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (telegraminfoVO.getMsgMetaDstcd() ); //Stage Logging 용 + logger.debug("{} 3.1. 전문 송신 클래스 생성...", logHeader); + logger.debug("{} => @@@@@@@@@@@@@@@@@@@@@@@@@@@@ ClassName: ["+ telegraminfoVO.getTelegramClsName() +"] @@@@@@@@@@@@@@@@@@@@@@@@@@@@", logHeader); + TelegramService telegramInst = null; + try { + telegramInst= (TelegramService)Class.forName(telegraminfoVO.getTelegramClsName()).newInstance(); + if (telegramInst == null) { + // 지정된 클래스가 없다... 장애처리 + logger.error("{} 지정된 이름을 가지는 클래스가 없습니다. telegramInst is null", logHeader);// 20250910 npe + doErrorAction(null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + telegramInst.setTelegramType(strTelegramType); + } catch (Exception e) { + doErrorAction(e, null, ErrorKeys.ERROR_NO_CLASS_DEFINITION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + logger.debug("{} 4. telegram class [" + telegraminfoVO.getTelegramClsName() + "] generated ok", logHeader); + // 6.1 여기에서 텔레그램클래스에서 필요한 값들을 셋팅해 준다. : 전문종별, 거래구분코드, 응답코드, 업무관리구분 + String strSndValue_TelegramType = pvo.getTelegramType(); + String strSndValue_OpCode = pvo.getOpCode(); + String strSndValue_TrClass = pvo.getTrClass(); + + // 7. 텔레그램 클래스 인스탄스에 EAIBatchMessageDocument를 지정한다. + telegramInst.setEAIBatchMessage(batchDoc); + // 8. 텔레그램 클래스에 메시지메타코드 를 지정해준다. + telegramInst.setTelegramCode(telegraminfoVO.getMsgMetaDstcd()); + // 9. 메시지메타코드를 이용하여 전문의 각 필드를 생성해준다. + boolean rcB = telegramInst.doPreExecute(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doPreExecute 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_RECV_PRE_LENGTH, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + // 10. RULE DB에서 읽은 조립시 참조값들을 넣어준다. + telegramInst.setFldTelegramType(strSndValue_TelegramType); + telegramInst.setFldOpCode(strSndValue_OpCode); + telegramInst.setFldTrClass(strSndValue_TrClass); + logger.debug("{} 5. get basic value for compiling telegram", logHeader); + // 11. 송신전문을 조립한다. + boolean rcCompile = telegramInst.doExecute(); + if (!rcCompile) { + logger.error("{} 전문조립중 장애 발생 ", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_EXECUTION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue(telegramInst.getTelegramType()); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (telegramInst.getTrClass() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (telegramInst.getOpCode() ); //Stage Logging 용 + batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue(telegramInst.getResCode() ); //Stage Logging 용 + logger.debug("{} 6. doExecute called : compile ok!", logHeader); + // 12. 조립된 송신전문 Validation + rcB = telegramInst.doValidation(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doValidation 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_SEND_VALIDATION); + return batchDoc; + } + logger.debug("{} 7. doValidation called ", logHeader); + // 13. 소켓을 WRITE 한다. + try { + ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); + int nDataLength = telegramInst.getSendLength(); // 총 송신 대상 길이 + logger.info("{} telegram length to send is " + nDataLength + " :텔레그램 데이터 송신시작 ", logHeader); + + for (int i=1; i OK", logHeader); + + } else { + byte[] aField = telegramInst.getFieldDataByIndex(i); + outBuffer.write(aField, 0, aField.length); + + TelegramItemVO item = TelegramManager.getInstance().getTelegramField(telegraminfoVO.getMsgMetaDstcd(), i+1); //log용 + logger.info("{} - Wrote FORMAL field data to buffer : "+ (i+1) +". ["+ item.getFieldType() +"] ["+ item.getFieldLength() +"] ["+ new String(aField) +"] ["+ item.getFieldName() +"] => OK", logHeader); + } + } + if (outBuffer.size() > 0 && outBuffer.size() + 4 == nDataLength) { + // 여기서 outBuffer.toByteArray() 를 검사하여 FF 가 존재 하면 FFFF로 치환 하여야 한다. + ByteArrayOutputStream tempBuffer = new ByteArrayOutputStream(); + byte[] temp1 = outBuffer.toByteArray(); + for ( int inx = 0; inx < outBuffer.size(); inx++){ + if ( temp1[inx] == (byte)0xff) + tempBuffer.write(temp1, inx, 1); + tempBuffer.write(temp1, inx, 1); + } + + dout.write(tempBuffer.toByteArray(), 0, tempBuffer.size()); + + dout.write( TERM_STRING, 0, 2); + + logger.info("{} >>> Wrote FORMAL & INFORMAL field data to socket : " + outBuffer.size() + " bytes", logHeader); + + } else { + logger.error("{} SEND function failed : no data found in ByteArrayOutputStream", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_SHORT_WRITE_ERROR, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName(), nDataLength+"", outBuffer.size()+""}); + telegramInst.doPostExecute(); + return batchDoc; + } + logger.debug("{} 8. all Field sent ok : " + telegramInst.getFieldCount(), logHeader); + + } catch (Exception ex) { + logger.error("{} ★★★★★ socket write error !! ★★★★★", logHeader, ex); + doErrorAction(ex, telegramInst, ErrorKeys.ERROR_WRITE_ERROR); + telegramInst.doPostExecute(); + return batchDoc; + } + + // 14. 실행 후 작업 수행 + rcB = telegramInst.doPostExecute(); + if (!rcB) { + logger.error("{} 텔레그램 인스탄스 doPostValidation 실행 시 장애 발생", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_POST_EXECUTION, new String[] {strTelegramID, telegraminfoVO.getTelegramClsName()}); + return batchDoc; + } + logger.debug("{} 9. doPostExecute called", logHeader); + + // 텔레그램클래스에 넘겨주었던 배치메세지를 다시 받는다. + this.batchDoc = telegramInst.getEAIBatchMessage(); + + // 15. 현 단계 수행 전문을 일단 저장 + //현재 Telegram Component를 JobProcessData (PROCDATA_PRE_TELEGRAM) 에 저장해둔다. (다음 수행할 Telegram Component 가 현재 데이터를 참조할 수 있도록) + super.setPreviousTelegramComponent(telegramInst); + + // 16. 다음 단계 결정 : 실질적인 다음 단계 결정은 각 텔레그램 클래스 에서 하도록 하자 + telegramInst.setNextStageInfo(curr_poss_stage); + this.nextPhaseInfoVO = telegramInst.getNextStage(); + // 다음단계를 찾을 수 없으면 장애처리하도록 한다. - 20060406 by khs + if (this.nextPhaseInfoVO == null) { + // 정상적인 다음 단계를 찾을 수 없는 경우... + logger.error("{} not found next stage ... ["+telegramInst.getTelegramType()+"]", logHeader); + doErrorAction(telegramInst, ErrorKeys.ERROR_NOTFOUND_NEXTSTAGE, new String[] {strRuleCode, strPhaseCode}); + return batchDoc; + } + batchDoc.getBatchMsg().getBody().setNextPhaseCode(nextPhaseInfoVO.getNextPhaseCode()); + logger.debug("{} 10. decide next Stage [" + batchDoc.getBatchMsg().getBody().getNextPhaseCode()+"]", logHeader); + // 17. 현 단계 종료 시간 셋팅 + //batchDoc.getEAIBatchMessage().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash16()); + // 현 단계에 대한 로깅 20060410 by khs + //LogUtil.setLog(batchDoc); + return batchDoc; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/job/jobModule/ReSendReqSend.java b/src/com/eactive/eai/batch/job/jobModule/ReSendReqSend.java new file mode 100644 index 0000000..a50a8e2 --- /dev/null +++ b/src/com/eactive/eai/batch/job/jobModule/ReSendReqSend.java @@ -0,0 +1,125 @@ +package com.eactive.eai.batch.job.jobModule; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.UCMsgSenderUtil; +import com.eactive.eai.common.util.UUIDGenerator; + +public class ReSendReqSend { + + protected static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public static BatchDoc insertJobToQueue(BatchDoc batchDoc){ + + SchedulerMessageManager manager = SchedulerMessageManager.getInstance(); + SchedulerMessageVO scheduleInfo = null; + + try { + scheduleInfo = manager.getReqSendSchedule( batchDoc.getBatchMsg().getHeader().getScheduleCode()); + + + //String strEndTime = scheduleInfo.getEndTime(); + String strReStartTime = DatetimeUtil.getNextTime((scheduleInfo.getRecvRetrySecs()/60)).substring(0, 4); + + //int endTime = Integer.parseInt(strEndTime); + //int reStartTime = Integer.parseInt(strReStartTime); + + long endDateTime = Long.parseLong(batchDoc.getBatchMsg().getHeader().getScheduleETime()); //전송 종료 시각 + long startDateTime = Long.parseLong(DatetimeUtil.getCurrentDate() +strReStartTime+"00" + "000"); + +//System.out.println("ReSendReqSend ] endDateTime / startDateTime - ["+endDateTime +"/"+ startDateTime +"]"); + + + int rerytCount = scheduleInfo.getRecvRetryCnt(); + int failCount = scheduleInfo.getRecvFailCnt(); + + if (endDateTime > startDateTime && (rerytCount ==0 || failCount < rerytCount)){ //종료시간안에 있어야 재송신하기 위한 작업큐에 등록한다.) + + //BATCH작업 요청메시지ID 및 스케쥴 송수신 시각 설정 + //요구송신의 재처리의 경우 UUID는 새로 생성해야 한다. + String uuid = UUIDGenerator.getUUID(); + + //scheduleInfo.setUUID (uuid);//로깅을 위해 새로운 uuid 할당한다. 2009.9.22 sub_uuid만 변경한다. + scheduleInfo.setUUID(batchDoc.getBatchMsg().getHeader().getUUID()); + scheduleInfo.setSubUUID (uuid); + scheduleInfo.setFilePath (batchDoc.getBatchMsg().getHeader().getFilePath()); + scheduleInfo.setFileName (batchDoc.getBatchMsg().getHeader().getFileName()); + scheduleInfo.setRenamedFileName(batchDoc.getBatchMsg().getHeader().getRenamedFileName()); + scheduleInfo.setInstitutionName(batchDoc.getBatchMsg().getHeader().getInstitutionName()); + scheduleInfo.setProcessName(batchDoc.getBatchMsg().getHeader().getProcessName()); + scheduleInfo.setHdrInfoName(batchDoc.getBatchMsg().getHeader().getHdrInfoName()); + + + scheduleInfo.setStartTime(""+startDateTime); + scheduleInfo.setEndTime(""+endDateTime); + + + BatchDoc newBatchDoc = EAIBatchMsgManager.createBatchMsg(true); + newBatchDoc.getBatchMsg().getHeader().setBatchStartTime(CalendarUtil.getCurrentTimeNoDash()); + newBatchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + + //JOB QUEUE 테이블에 등록 + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(scheduleInfo); + logger.info("[요구송신 재처리를 위한 전처리 단계 수행] ==> 배치 JOB QUEUE 테이블 INSERT 건수: "+ resultCnt); + + //DB로그를 위해서 조회정보를 batchDoc에 세팅 + //newBatchDoc.getEAIBatchMessage().getHeader().setUUID(uuid); + newBatchDoc.getBatchMsg().getHeader().setUUID(scheduleInfo.getUUID()); + newBatchDoc.getBatchMsg().getBody().setSubUUID(uuid); + + newBatchDoc.getBatchMsg().getHeader().setScheduleSTime(scheduleInfo.getStartTime()); //전송 시작 시각 + newBatchDoc.getBatchMsg().getHeader().setScheduleETime(scheduleInfo.getEndTime()); + newBatchDoc.getBatchMsg().getHeader().setLayerCode(CommonKeys.LAYER_SCHEDULER); + newBatchDoc.getBatchMsg().getHeader().setBizCode(batchDoc.getBatchMsg().getHeader().getBizCode()); + newBatchDoc.getBatchMsg().getHeader().setBlockSize(batchDoc.getBatchMsg().getHeader().getBlockSize()); + newBatchDoc.getBatchMsg().getHeader().setFileName(batchDoc.getBatchMsg().getHeader().getFileName()); + newBatchDoc.getBatchMsg().getHeader().setScheduleCode(batchDoc.getBatchMsg().getHeader().getScheduleCode()); + newBatchDoc.getBatchMsg().getHeader().setProcessType(batchDoc.getBatchMsg().getHeader().getProcessType()); + newBatchDoc.getBatchMsg().getHeader().setInstitutionCode(batchDoc.getBatchMsg().getHeader().getInstitutionCode()); + newBatchDoc.getBatchMsg().getHeader().setUserID(batchDoc.getBatchMsg().getHeader().getUserID()); + newBatchDoc.getBatchMsg().getHeader().setUserName(batchDoc.getBatchMsg().getHeader().getUserName()); + newBatchDoc.getBatchMsg().getHeader().setSystemConnCode(batchDoc.getBatchMsg().getHeader().getSystemConnCode()); + newBatchDoc.getBatchMsg().getHeader().setRemoteIP(batchDoc.getBatchMsg().getHeader().getRemoteIP()); + newBatchDoc.getBatchMsg().getHeader().setRuleCode(batchDoc.getBatchMsg().getHeader().getRuleCode()); + newBatchDoc.getBatchMsg().getHeader().setProcessCode(batchDoc.getBatchMsg().getHeader().getProcessCode()); + + newBatchDoc.getBatchMsg().getBody().setWLIServerName(batchDoc.getBatchMsg().getBody().getWLIServerName()); + newBatchDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); + newBatchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + newBatchDoc.getBatchMsg().getBody().setErrorCode(0); + newBatchDoc.getBatchMsg().getBody().setErrorMsg(""); + newBatchDoc.getBatchMsg().getBody().setRetryCount(scheduleInfo.getRecvFailCnt()); + + //요구송신 재처리에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (newBatchDoc); + }else { + if (scheduleInfo != null) {// 20250910 obl + String msg = "[요구송신 재처리를 위한 전처리 단계 수행] "+ scheduleInfo.getScheduleCode() +" | "+ scheduleInfo.getProcessCode() +" | "+ scheduleInfo.getInstitutionCode() +" | "+ scheduleInfo.getBizCode() +" | "+ scheduleInfo.getStartTime() +" | "+ scheduleInfo.getEndTime() +" ==> 종료시간이 되었거나 재시도 회수를 초과하여 JOB QUEUE에 등록하지 않음. (미완료 작업건수/재시도 횟수: "+ scheduleInfo.getRecvFailCnt() +"/"+scheduleInfo.getRecvRetryCnt()+") - endTime/reStartTime" +"["+endDateTime +"/"+ startDateTime +"]\n" + batchDoc.getBatchMsg().getBody().getErrorMsg() ; + batchDoc.getBatchMsg().getBody().setErrorMsg(msg); + logger.warn(msg); + }else { + batchDoc.getBatchMsg().getBody().setErrorMsg("[요구송신 재처리를 위한 전처리 단계 수행] scheduleInfo is null"); + logger.warn("[요구송신 재처리를 위한 전처리 단계 수행] scheduleInfo is null"); + } + UCMsgSenderUtil.sendUCMsg(batchDoc); + } + + return batchDoc; + + }catch (Exception ex) { + String errMsg = "요구 송신 재처리를 위해 Queue에 데이터 insert시 오류가 발생했습니다. - ["+batchDoc.getBatchMsg().getHeader().getProcessCode()+"/"+scheduleInfo.getScheduleCode()+"]\n" + batchDoc.getBatchMsg().getBody().getErrorMsg(); + batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + UCMsgSenderUtil.sendUCMsg(batchDoc); + logger.error( ex.getMessage(), ex); + + return batchDoc; + } + } +} diff --git a/src/com/eactive/eai/batch/logger/LogDAO.java b/src/com/eactive/eai/batch/logger/LogDAO.java new file mode 100644 index 0000000..cf934f7 --- /dev/null +++ b/src/com/eactive/eai/batch/logger/LogDAO.java @@ -0,0 +1,1054 @@ +package com.eactive.eai.batch.logger; + +import java.sql.ResultSet; +import java.util.ArrayList; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.scheduler.JobFileTransferVO; +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class LogDAO extends BaseDAO implements LogQuery +{ + + public static final int LOG_MASTER_ERROR_DESC_FIELD_LENGTH = 1000; + public static final int LOG_STAGE_ERROR_DESC_FIELD_LENGTH = 1000; + public static final int LOG_FILE_ERROR_DESC_FIELD_LENGTH = 1000; + + /** + * 1. 기능 : 해당 배치 Job의 Master, Stage 로그가 존재하는지를 조회한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Master 로그 존재여부 + * @exception DAOException DB select 가 실패한 경우, 조회 건수가 없는 경우 + **/ + public int[] existLogCount(BatchDoc msgDoc) throws DAOException { + + ResultSet rs = null; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + String layerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getLayerCode() , " "); //Layer구분코드 + String subLayerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubLayerCode() , " "); //Sub_Layer구분코드 +// String ruleCode = StringUtil.nvlTrim(msgDoc.getEAIBatchMessage().getPhaseinfo().getRuleCode() , " "); //Rule코드 +// String phaseCode = StringUtil.nvlTrim(msgDoc.getEAIBatchMessage().getPhaseinfo().getPhaseCode() , " "); //Rule단계코드 + int nodeCount = msgDoc.getBatchMsg().getBody().getNodeCount(); //NodeCount + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() , " "); //실제파일명 + + try { + + this.connect(SELECT_EXIST_LOG_COUNT); // logger.debug("{ LogDAO.existLogCount() } 수행 SQL 문 : \n"+ SELECT_EXIST_LOG_COUNT); + + index = 1; + this.preparedStatement.setString(index++, uuid ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ uuid +"]"); + this.preparedStatement.setString(index++, subUuid ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ subUuid +"]"); + this.preparedStatement.setString(index++, uuid ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ uuid +"]"); + this.preparedStatement.setString(index++, subUuid ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ subUuid +"]"); + this.preparedStatement.setString(index++, layerCode ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ layerCode +"]"); + this.preparedStatement.setString(index++, subLayerCode); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ subLayerCode +"]"); + //this.preparedStatement.setString(index++, ruleCode ); //logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ ruleCode +"]"); + //this.preparedStatement.setString(index++, phaseCode ); //logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ phaseCode +"]"); + this.preparedStatement.setString (index++, "" + nodeCount ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ nodeCount +"]"); + this.preparedStatement.setString(index++, uuid ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ uuid +"]"); + this.preparedStatement.setString(index++, subUuid ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ subUuid +"]"); + this.preparedStatement.setString(index++, fileName ); // logger.debug("{ LogDAO.existLogCount() } 바인드("+(index-1)+") : ["+ fileName +"]"); + + rs = executeQuery(); + + rs.next(); + int[] existLogCnt = new int[3]; + existLogCnt[0] = rs.getInt("LogMasterCnt"); + existLogCnt[1] = rs.getInt("LogStageCnt"); + existLogCnt[2] = rs.getInt("LogFileCnt"); + logger.info("[ DB로그 ] ==> DB로그 존재 건수 : MASTER_LOG="+ existLogCnt[0] +", STAGE_LOG="+ existLogCnt[1] +", FILE_LOG="+ existLogCnt[2] +" [UUID: "+ uuid +", SUB_UUID: "+ subUuid +"]"); + + return existLogCnt; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG019", new String[] {uuid, subUuid}); + throw new DAOException(errMsg); //배치 DB로그 존재여부 조회시 오류가 발생하였습니다.[UUID: {1}] [SUB_UUID: {2}] + } finally { + disconnect(); + } + } + + + /** + * 1. 기능 : 배치 Job 시작 시 Master 로그를 insert 한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Master 로그 테이블의 insert Row 수 + * @exception DAOException DB insert 가 실패한 경우, insert 건수가 없는 경우 + **/ + public int insertLogMaster(BatchDoc msgDoc) throws DAOException { + + int retValue = 0; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + int retryCount = msgDoc.getBatchMsg().getBody().getRetryCount(); //작업재시도회수 + String scheduleCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getScheduleCode() , " "); //스케쥴코드 + String msgCreateTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getBatchStartTime() , " "); //메시지생성시간 + String institutionCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getInstitutionCode(), " "); //대외기관코드 + String processCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessCode() , " "); //Process 테이블 FK + String processType = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessType() , " "); //Job 유형구분 + String userID = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUserID() , " "); //사용자ID + String userName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUserName() , " "); //사용자명 + String sysConnCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getSystemConnCode() , " "); //연결정보ID + String remoteIP = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getRemoteIP() , " "); //Remote IP + String ruleCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getRuleCode() , " "); //RuleCode + String weblogicName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getWLIServerName() , " "); //웹로직서버명 + String phaseStartTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseStartTime() , " "); //단계시작시간 + String phaseEndTime = " "; //단계종료시간 (공백 설정) + String errorDesc = " "; //에러메시지 (공백 설정) + + //진행상태: SocketServer 에서 호출된 경우 '시작'상태로, 그 외 '대기'상태로 설정 + String layerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getLayerCode() ); //Layer구분코드 + String status = layerCode.equals(CommonKeys.LAYER_SOCKET_SERVER)? LogManager.LOG_TYPE_START : LogManager.LOG_TYPE_QUEUE; + + try { + + this.connect(INSERT_LOG_MASTER); + + index = 1; + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + this.preparedStatement.setInt (index++, retryCount ); + this.preparedStatement.setString(index++, scheduleCode ); + this.preparedStatement.setString(index++, msgCreateTime ); + this.preparedStatement.setString(index++, institutionCode); + this.preparedStatement.setString(index++, processCode ); + this.preparedStatement.setString(index++, processType ); + this.preparedStatement.setString(index++, userID ); + this.preparedStatement.setString(index++, userName ); + this.preparedStatement.setString(index++, sysConnCode ); + this.preparedStatement.setString(index++, remoteIP ); + this.preparedStatement.setString(index++, ruleCode ); + this.preparedStatement.setString(index++, weblogicName ); + this.preparedStatement.setString(index++, phaseStartTime ); + this.preparedStatement.setString(index++, phaseEndTime ); + this.preparedStatement.setString(index++, status ); + this.preparedStatement.setString(index++, errorDesc ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> Master DB로그 INSERT 건수 : "+ retValue +" ["+ uuid +" / "+ subUuid +"]"); + + if (retValue == 0) throw new DAOException("BECEAICLG008"); //배치로그 Master 테이블 insert 건수가 0 건입니다. + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG009"); //배치로그 Master 테이블 insert 시 오류가 발생하였습니다. + throw new DAOException(errMsg); + } finally { + disconnect(); + } + return retValue; + } + + + /** + * 1. 기능 : 배치 Job 단계 시작 시 Stage 로그를 insert 한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Stage 로그 테이블의 insert Row 수 + * @exception DAOException DB insert 가 실패한 경우, insert 건수가 없는 경우 + **/ + public int insertLogStage(BatchDoc msgDoc, String logType, String errorDesc) throws DAOException { + + int retValue = 0; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //SUB_UUID + String layerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getLayerCode() ); //Layer구분코드 + String subLayerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubLayerCode() ); //Sub_Layer구분코드 + String ruleCode = " "; + String phaseCode = " "; + String phaseType = " "; + String flowClassName = " "; + String lengthTelegramId = " "; + String lengthClassName = " "; + String lengthMsgCode = " "; + String phaseSeq = " "; + String phaseTelegramId = " "; + String phaseClassName = " "; + String phaseMsgCode = " "; + String telegramTypeValue = " "; + String bizCodeValue = " "; + String controlCodeValue = " "; + String responseCodeValue = " "; + if (msgDoc.getBatchMsg().getPhaseinfo() != null) { + ruleCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getRuleCode() , " "); //규칙코드 + phaseCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getPhaseCode() , " "); //단계코드 + phaseType = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getPhaseType() , " "); //단계유형 (SEND/RECV/END/EEND) + flowClassName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getFlowClassName() , " "); //유형별수행클래스 + lengthTelegramId = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getLengthTelegramID() , " "); //전문결정TelegramID (RECV 일때 사용) + lengthClassName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getLengthClassName() , " "); //전문결정수행클래스 (RECV 일때 사용) + lengthMsgCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getLengthMsgCode() , " "); //전문결정전문메시지코드 (RECV 일때 사용) + phaseSeq = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getPhaseSeq() , " "); //단계순번 + phaseTelegramId = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getPhaseTelegramID() , " "); //단계TelegramID + phaseClassName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getPhaseClassName() , " "); //단계수행클래스 + phaseMsgCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getPhaseMsgCode() , " "); //단계전문메시지코드 + telegramTypeValue = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getTelegramTypeValue()," "); //전문종별코드 값 + bizCodeValue = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getBizCodeValue() ," "); //거래구분코드 값 + controlCodeValue = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getControlCodeValue() ," "); //업무관리코드 값 + responseCodeValue = StringUtil.nvlTrim(msgDoc.getBatchMsg().getPhaseinfo().getResponseCodeValue()," "); //응답코드 값 + } + int nodeCount = msgDoc.getBatchMsg().getBody().getNodeCount(); //NodeCount + String jobCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getJobCode() , " "); //Job 테이블 FK + String institutionCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getInstitutionCode(), " "); //대외기관코드 + String processCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessCode() , " "); //Process 테이블 FK + String processType = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessType() , " "); //Job 유형구분 + String bizCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getBizCode() , " "); //거래구분코드 + String filePath = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFilePath() , " "); //파일패스 + String realFileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() , " "); //실제파일명 + String renamedFileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getRenamedFileName(), " "); //변경된파일명 + String weblogicName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getWLIServerName() , " "); //웹로직서버명 + String phaseStartTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseStartTime() , " "); //단계시작시간 + String phaseEndTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseEndTime() , " "); //단계종료시간 + + String telegramHeader = " "; + String telegramBody = " "; + //DB로그 레벨이 '전문저장'인 경우 전문 설정 + if (LogManager.mBatchDBLogLevel != null && LogManager.mBatchDBLogLevel.equals(LogManager.BATCH_DBLOG_LEVEL_ALL)) { + //telegramHeader = StringUtil.nvlTrim(msgDoc.getEAIBatchMessage().getTelegramHeader() , " "); //전문Header + //telegramBody = StringUtil.nvlTrim(msgDoc.getEAIBatchMessage().getTelegramBody() , " "); //전문Body + telegramHeader = splitStringByByteSize(msgDoc.getBatchMsg().getTelegramHeader(), 1, 4000, " ")[0]; //전문Header + telegramBody = splitStringByByteSize(msgDoc.getBatchMsg().getTelegramBody() , 1, 4000, " ")[0]; //전문Body + } + + //파라미터로 받은 errorDesc 은 무시하고 batchMsgDod 에 있는 메시지를 저장한다. + errorDesc = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getErrorMsg() , " "); //에러메시지 + errorDesc = tailStringByByteSize(errorDesc, LOG_STAGE_ERROR_DESC_FIELD_LENGTH, "(상위메시지절삭)..."); //길이 초과시 잘라냄 + if (!errorDesc.equals(" ")) logType = LogManager.LOG_TYPE_ERROR; + +// int seqNum = msgDoc.getEAIBatchMessage().getBody().getSeqNum(); +// int BlockNum = msgDoc.getEAIBatchMessage().getBody().getBlockNum(); +// logger.debug("[ DB로그 DEBUG ] ==> BlockNum[" +BlockNum + "]seqNum ["+ seqNum +"]"); + +// if ( (1==0) && seqNum != 0 && seqNum != 1 && BlockNum != 0 ){ +// try { +// this.connect(UPDATE_LAST_LOG_STAGE); +// index = 1; +// this.preparedStatement.setString(index++, ruleCode ); +// this.preparedStatement.setString(index++, phaseCode ); +// this.preparedStatement.setString(index++, phaseSeq ); +// this.preparedStatement.setString(index++, phaseType ); +// this.preparedStatement.setString(index++, flowClassName ); +// this.preparedStatement.setString(index++, lengthTelegramId ); +// this.preparedStatement.setString(index++, lengthClassName ); +// this.preparedStatement.setString(index++, lengthMsgCode ); +// this.preparedStatement.setString(index++, phaseTelegramId ); +// this.preparedStatement.setString(index++, phaseClassName ); +// this.preparedStatement.setString(index++, phaseMsgCode ); +// this.preparedStatement.setString(index++, telegramTypeValue); +// this.preparedStatement.setString(index++, bizCodeValue ); +// this.preparedStatement.setString(index++, controlCodeValue ); +// this.preparedStatement.setString(index++, responseCodeValue); +// this.preparedStatement.setInt (index++, nodeCount ); +// this.preparedStatement.setString(index++, jobCode ); +// this.preparedStatement.setString(index++, institutionCode ); +// this.preparedStatement.setString(index++, processCode ); +// this.preparedStatement.setString(index++, processType ); +// this.preparedStatement.setString(index++, bizCode ); +// this.preparedStatement.setString(index++, filePath ); +// this.preparedStatement.setString(index++, realFileName ); +// this.preparedStatement.setString(index++, renamedFileName ); +// this.preparedStatement.setString(index++, weblogicName ); +// this.preparedStatement.setString(index++, phaseStartTime ); +// this.preparedStatement.setString(index++, phaseEndTime ); +// this.preparedStatement.setString(index++, logType ); +// this.preparedStatement.setString(index++, errorDesc ); +// this.preparedStatement.setString(index++, telegramHeader ); +// this.preparedStatement.setString(index++, telegramBody ); +// this.preparedStatement.setString(index++, uuid ); +// this.preparedStatement.setString(index++, subUuid ); +// this.preparedStatement.setString(index++, layerCode ); +// this.preparedStatement.setString(index++, subLayerCode ); +// this.preparedStatement.setString(index++, uuid ); +// this.preparedStatement.setString(index++, subUuid ); +// this.preparedStatement.setString(index++, layerCode ); +// this.preparedStatement.setString(index++, subLayerCode ); +// +// retValue = this.executeUpdate(); +// logger.info("[ DB로그 ] ==> Stage DB로그 UPDATE 건수 : "+ retValue +" ["+ uuid +" / "+ layerCode +" / "+ subLayerCode +" / "+ nodeCount +"]"); +// +// } catch (DAOException ex) { +// throw ex; +// }catch (Exception ex) { +// String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG011"); //배치로그 Stage 테이블 insert 시 오류가 발생하였습니다. +// throw new DAOException(errMsg); +// }finally { +// disconnect(); +// } +// if (retValue > 0) return retValue; +// } + + try { + this.connect(INSERT_LOG_STAGE); + index = 1; + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + this.preparedStatement.setString(index++, layerCode ); + this.preparedStatement.setString(index++, subLayerCode ); + this.preparedStatement.setString(index++, ruleCode ); + this.preparedStatement.setString(index++, phaseCode ); + this.preparedStatement.setString(index++, phaseSeq ); + this.preparedStatement.setString(index++, phaseType ); + this.preparedStatement.setString(index++, flowClassName ); + this.preparedStatement.setString(index++, lengthTelegramId ); + this.preparedStatement.setString(index++, lengthClassName ); + this.preparedStatement.setString(index++, lengthMsgCode ); + this.preparedStatement.setString(index++, phaseTelegramId ); + this.preparedStatement.setString(index++, phaseClassName ); + this.preparedStatement.setString(index++, phaseMsgCode ); + this.preparedStatement.setString(index++, telegramTypeValue); + this.preparedStatement.setString(index++, bizCodeValue ); + this.preparedStatement.setString(index++, controlCodeValue ); + this.preparedStatement.setString(index++, responseCodeValue); + this.preparedStatement.setInt (index++, nodeCount ); + this.preparedStatement.setString(index++, jobCode ); + this.preparedStatement.setString(index++, institutionCode ); + this.preparedStatement.setString(index++, processCode ); + this.preparedStatement.setString(index++, processType ); + this.preparedStatement.setString(index++, bizCode ); + this.preparedStatement.setString(index++, filePath ); + this.preparedStatement.setString(index++, realFileName ); + this.preparedStatement.setString(index++, renamedFileName ); + this.preparedStatement.setString(index++, weblogicName ); + this.preparedStatement.setString(index++, phaseStartTime ); + this.preparedStatement.setString(index++, phaseEndTime ); + this.preparedStatement.setString(index++, logType ); + this.preparedStatement.setString(index++, errorDesc ); + this.preparedStatement.setString(index++, telegramHeader ); + this.preparedStatement.setString(index++, telegramBody ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> Stage DB로그 INSERT 건수 : "+ retValue +" ["+ uuid +" / "+ layerCode +" / "+ subLayerCode +" / "+ nodeCount +"]"); + + if (retValue == 0) throw new DAOException("BECEAICLG010"); //배치로그 Stage 테이블 insert 건수가 0 건입니다. + } catch (DAOException ex) { + logger.info("[ DB로그 ] ==> Stage DB로그 INSERT 건수 : "+ retValue +" ["+ uuid +" / "+ layerCode +" / "+ subLayerCode +" / "+ nodeCount +"]"); + try { + this.prepareStatement(UPDATE_LOG_STAGE); + index = 1; + this.preparedStatement.setString(index++, ruleCode ); + this.preparedStatement.setString(index++, phaseCode ); + this.preparedStatement.setString(index++, phaseSeq ); + this.preparedStatement.setString(index++, phaseType ); + this.preparedStatement.setString(index++, flowClassName ); + this.preparedStatement.setString(index++, lengthTelegramId ); + this.preparedStatement.setString(index++, lengthClassName ); + this.preparedStatement.setString(index++, lengthMsgCode ); + this.preparedStatement.setString(index++, phaseTelegramId ); + this.preparedStatement.setString(index++, phaseClassName ); + this.preparedStatement.setString(index++, phaseMsgCode ); + this.preparedStatement.setString(index++, telegramTypeValue); + this.preparedStatement.setString(index++, bizCodeValue ); + this.preparedStatement.setString(index++, controlCodeValue ); + this.preparedStatement.setString(index++, responseCodeValue); + this.preparedStatement.setString(index++, jobCode ); + this.preparedStatement.setString(index++, institutionCode ); + this.preparedStatement.setString(index++, processCode ); + this.preparedStatement.setString(index++, processType ); + this.preparedStatement.setString(index++, bizCode ); + this.preparedStatement.setString(index++, filePath ); + this.preparedStatement.setString(index++, realFileName ); + this.preparedStatement.setString(index++, renamedFileName ); + this.preparedStatement.setString(index++, weblogicName ); + this.preparedStatement.setString(index++, phaseStartTime ); + this.preparedStatement.setString(index++, phaseEndTime ); + this.preparedStatement.setString(index++, logType ); + this.preparedStatement.setString(index++, errorDesc ); + this.preparedStatement.setString(index++, telegramHeader ); + this.preparedStatement.setString(index++, telegramBody ); + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + this.preparedStatement.setString(index++, layerCode ); + this.preparedStatement.setString(index++, subLayerCode ); + this.preparedStatement.setInt (index++, nodeCount ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> Stage DB로그 UPDATE 건수 : "+ retValue +" ["+ uuid +" / "+ layerCode +" / "+ subLayerCode +" / "+ nodeCount +"]"); + + } catch (DAOException ex1) { + logger.debug("INSERT_LOG_STAGE -->\n" + INSERT_LOG_STAGE ); + logger.debug("UPDATE_LOG_STAGE -->\n" + UPDATE_LOG_STAGE ); + logger.debug("[insertLogStage]uuid -->"+uuid .length()+"["+uuid +"]"); + logger.debug("[insertLogStage]subUuid -->"+subUuid .length()+"["+subUuid +"]"); + logger.debug("[insertLogStage]layerCode -->"+layerCode .length()+"["+layerCode +"]"); + logger.debug("[insertLogStage]subLayerCode -->"+subLayerCode .length()+"["+subLayerCode +"]"); + logger.debug("[insertLogStage]ruleCode -->"+ruleCode .length()+"["+ruleCode +"]"); + logger.debug("[insertLogStage]phaseCode -->"+phaseCode .length()+"["+phaseCode +"]"); + logger.debug("[insertLogStage]phaseSeq -->"+phaseSeq .length()+"["+phaseSeq +"]"); + logger.debug("[insertLogStage]phaseType -->"+phaseType .length()+"["+phaseType +"]"); + logger.debug("[insertLogStage]flowClassName -->"+flowClassName .length()+"["+flowClassName +"]"); + logger.debug("[insertLogStage]lengthTelegramId -->"+lengthTelegramId .length()+"["+lengthTelegramId +"]"); + logger.debug("[insertLogStage]lengthClassName -->"+lengthClassName .length()+"["+lengthClassName +"]"); + logger.debug("[insertLogStage]lengthMsgCode -->"+lengthMsgCode .length()+"["+lengthMsgCode +"]"); + logger.debug("[insertLogStage]phaseTelegramId -->"+phaseTelegramId .length()+"["+phaseTelegramId +"]"); + logger.debug("[insertLogStage]phaseClassName -->"+phaseClassName .length()+"["+phaseClassName +"]"); + logger.debug("[insertLogStage]phaseMsgCode -->"+phaseMsgCode .length()+"["+phaseMsgCode +"]"); + logger.debug("[insertLogStage]telegramTypeValue-->"+telegramTypeValue.length()+"["+telegramTypeValue+"]"); + logger.debug("[insertLogStage]bizCodeValue -->"+bizCodeValue .length()+"["+bizCodeValue +"]"); + logger.debug("[insertLogStage]controlCodeValue -->"+controlCodeValue .length()+"["+controlCodeValue +"]"); + logger.debug("[insertLogStage]responseCodeValue-->"+responseCodeValue.length()+"["+responseCodeValue+"]"); + logger.debug("[insertLogStage]nodeCount -->["+nodeCount +"]"); + logger.debug("[insertLogStage]jobCode -->"+jobCode .length()+"["+jobCode +"]"); + logger.debug("[insertLogStage]institutionCode -->"+institutionCode .length()+"["+institutionCode +"]"); + logger.debug("[insertLogStage]processCode -->"+processCode .length()+"["+processCode +"]"); + logger.debug("[insertLogStage]processType -->"+processType .length()+"["+processType +"]"); + logger.debug("[insertLogStage]bizCode -->"+bizCode .length()+"["+bizCode +"]"); + logger.debug("[insertLogStage]filePath -->"+filePath .length()+"["+filePath +"]"); + logger.debug("[insertLogStage]realFileName -->"+realFileName .length()+"["+realFileName +"]"); + logger.debug("[insertLogStage]renamedFileName -->"+renamedFileName .length()+"["+renamedFileName +"]"); + logger.debug("[insertLogStage]weblogicName -->"+weblogicName .length()+"["+weblogicName +"]"); + logger.debug("[insertLogStage]phaseStartTime -->"+phaseStartTime .length()+"["+phaseStartTime +"]"); + logger.debug("[insertLogStage]phaseEndTime -->"+phaseEndTime .length()+"["+phaseEndTime +"]"); + logger.debug("[insertLogStage]logType -->"+logType .length()+"["+logType +"]"); + logger.debug("[insertLogStage]errorDesc -->"+errorDesc .length()+"["+errorDesc +"]"); + logger.debug("[insertLogStage]telegramHeader -->"+telegramHeader .length()+"["+telegramHeader +"]"); + logger.debug("[insertLogStage]telegramBody -->"+telegramBody .length()+"["+telegramBody +"]"); + + throw ex1; + } catch (Exception ex2) { + String errMsg = ExceptionUtil.getErrorCode(ex2, "BECEAICLG011"); //배치로그 Stage 테이블 insert 시 오류가 발생하였습니다. + throw new DAOException(errMsg); + } + } catch(Exception ex3){ + String errMsg = ExceptionUtil.getErrorCode(ex3, "BECEAICLG011"); //배치로그 Stage 테이블 insert 시 오류가 발생하였습니다. + throw new DAOException(errMsg); + } finally { + disconnect(); + } + + return retValue; + } + + + /** + * 1. 기능 : 배치 Job 종료 시 (정상종료, 에러종료, 사용자중지) Master 로그를 update 한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Master 로그 테이블의 update Row 수 + * @exception DAOException DB update 가 실패한 경우, update 건수가 없는 경우 + **/ + public int updateLogMasterFinish(BatchDoc msgDoc, String logType, String errorDesc) throws DAOException { + + int retValue = 0; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + String phaseEndTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseEndTime() , " "); //단계종료시간 + + //파라미터로 받은 errorDesc 은 무시하고 batchMsgDod 에 있는 메시지를 저장한다. + errorDesc = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getErrorMsg() , " "); //에러메시지 + errorDesc = tailStringByByteSize(errorDesc, LOG_MASTER_ERROR_DESC_FIELD_LENGTH, "(상위메시지절삭)..."); //길이 초과시 잘라냄 + + try { + + this.connect(UPDATE_MASTER_LOG_FINISH); + + index = 1; + this.preparedStatement.setString(index++, phaseEndTime ); + this.preparedStatement.setString(index++, logType ); //처리결과 코드 (logType 값이랑 동일) + this.preparedStatement.setString(index++, errorDesc ); + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> Master DB로그 작업종료 UPDATE 건수 : "+ retValue +" ["+ uuid +", / "+ subUuid +"]"); + + if (retValue == 0) { + String errMsg = ExceptionUtil.getErrorCode("BECEAICLG012", new String[] {uuid, subUuid}); //배치로그 Master 테이블 종료 update 건수가 0 건입니다.(UUID: ?, subUUID: ?) + throw new DAOException(errMsg); + } + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG013", new String[] {uuid, subUuid}); //배치로그 Master 테이블 종료 update 시 오류가 발생하였습니다.(UUID: ?, subUUID: ?) + throw new DAOException(errMsg); + } finally { + disconnect(); + } + return retValue; + } + + + /** + * 1. 기능 : 배치 Job 단계 진행시 로그 Master의 필드가 결정되는 경우 로그 Master를 update 한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Master 로그 테이블의 update Row 수 + * @exception DAOException DB update 가 실패한 경우, update 건수가 없는 경우 + **/ + public int updateLogMaster(BatchDoc msgDoc) throws DAOException { + + int retValue = 0; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + String scheduleCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getScheduleCode() ); //스케쥴코드 + String institutionCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getInstitutionCode()); //대외기관코드 + String processCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessCode() ); //Process 테이블 FK + String processType = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessType() ); //Job 유형구분 + String userID = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUserID() ); //사용자ID + String userName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUserName() ); //사용자명 + String sysConnCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getSystemConnCode() ); //연결정보ID + String ruleCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getRuleCode() ); //RuleCode + String flowStartTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseStartTime() ); //단계시작시간 + + //진행상태: ScheduleHandler 에서 호출된 경우 '시작'상태로 UPDATE, 그 외 '대기'상태로 UPDATE + String subLayerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubLayerCode() ); //Sub_Layer구분코드 + String status = subLayerCode.equals(CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING)? LogManager.LOG_TYPE_START : LogManager.LOG_TYPE_QUEUE; + + try { + + this.connect(UPDATE_MASTER_LOG_CONTINUE); + + index = 1; + this.preparedStatement.setString(index++, scheduleCode ); + this.preparedStatement.setString(index++, institutionCode); + this.preparedStatement.setString(index++, processCode ); + this.preparedStatement.setString(index++, processType ); + this.preparedStatement.setString(index++, userID ); + this.preparedStatement.setString(index++, userName ); + this.preparedStatement.setString(index++, sysConnCode ); + this.preparedStatement.setString(index++, ruleCode ); + this.preparedStatement.setString(index++, flowStartTime ); + this.preparedStatement.setString(index++, status ); + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> Master DB로그 추가 정의값 UPDATE 건수 : "+ retValue +" ["+ uuid +", / "+ subUuid +"]"); + + if (retValue == 0) { + String errMsg = ExceptionUtil.getErrorCode("BECEAICLG014", new String[] {uuid, subUuid}); //배치로그 Master 테이블 진행 update 건수가 0 건입니다.(UUID: ?, subUUID: ?) + throw new DAOException(errMsg); + } + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG015", new String[] {uuid, subUuid}); //배치로그 Master 테이블 진행 update 시 오류가 발생하였습니다.(UUID: ?, subUUID: ?) + throw new DAOException(errMsg); + } finally { + disconnect(); + } + return retValue; + } + + public int existLogFileCount(BatchDoc msgDoc) throws DAOException { + + ResultSet rs = null; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName()); //실제파일명 + + try { + + this.connect(SELECT_FILE_LOG_EXIST_COUNT); + //logger.debug("{ LogDAO.existLogFileCount() } 수행 SQL 문 : \n"+ SELECT_FILE_LOG_EXIST_COUNT); + + index = 1; + this.preparedStatement.setString(index++, uuid ); //logger.debug("{ LogDAO.existLogFileCount() } 바인드("+(index-1)+") : ["+ uuid +"]"); + this.preparedStatement.setString(index++, subUuid ); //logger.debug("{ LogDAO.existLogFileCount() } 바인드("+(index-1)+") : ["+ subUuid +"]"); + this.preparedStatement.setString(index++, fileName ); //logger.debug("{ LogDAO.existLogFileCount() } 바인드("+(index-1)+") : ["+ fileName +"]"); + + rs = executeQuery(); + rs.next(); + int logFileCnt = rs.getInt("LogFileCnt"); + logger.info("[ DB로그 ] ==> File DB로그 존재 건수 : "+ logFileCnt +" ["+ uuid +" / "+ subUuid +" / "+ fileName +"]"); + + return logFileCnt; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG020", new String[] {uuid, subUuid, fileName}); + throw new DAOException(errMsg); //배치 DB로그 File 데이터 존재여부 조회시 오류가 발생하였습니다. [UUID: {1}] [SUB_UUID: {2}] + } finally { + disconnect(); + } + } + + public int insertLogFile(BatchDoc msgDoc) throws DAOException { + + int retValue = 0; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //SUB_UUID + String jobCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getJobCode() , " "); //Job 테이블 FK + String institutionCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getInstitutionCode(), " "); //대외기관코드 + String processCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessCode() , " "); //Process 테이블 FK + String processType = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getProcessType() , " "); //Job 유형구분 + String bizCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getBizCode() , " "); //거래구분코드 + String filePath = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFilePath() , " "); //파일패스 + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() , " "); //실제파일명 + String renamedFileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getRenamedFileName(), " "); //변경된파일명 + long recCnt = msgDoc.getBatchMsg().getHeader().getTotRecCnt(); //자료건수 + long fileSize = msgDoc.getBatchMsg().getHeader().getFileSize(); //파일사이즈 + String weblogicName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getWLIServerName() , " "); //웹로직서버명 + String phaseStartTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseStartTime() , " "); //단계시작시간 + String phaseEndTime = " "; //단계종료시간 (공백 설정) + String resultCode = LogManager.LOG_TYPE_START; //처리구분코드 ('시작'값 설정) + String errorDesc = " "; //에러메시지 (공백 설정) + String hdrInfoName = StringUtil.nvl(msgDoc.getBatchMsg().getHeader().getHdrInfoName() , " "); //체크파일내용 + String fileHeader = StringUtil.nvl(msgDoc.getBatchMsg().getFileHeader() , " "); //파일Header + String fileTrailer = StringUtil.nvl(msgDoc.getBatchMsg().getFileTrailer() , " "); //파일Trailer +// if ( fileHeader.getBytes().length > 4000){ +// fileHeader = fileHeader.substring(0, 4000); +// } +// if ( fileTrailer.getBytes().length > 4000){ +// fileTrailer = fileTrailer.substring(0, 4000); +// } + + if ( fileHeader.getBytes().length > 4000){ + fileHeader = new String(fileHeader.getBytes(), 0, 2000);//20250312 + } + if ( fileTrailer.getBytes().length > 4000){ + fileTrailer = new String(fileTrailer.getBytes(), 0, 2000);//20250312 + } + try { + + this.connect(INSERT_LOG_FILE); + + index = 1; + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + this.preparedStatement.setString(index++, processCode ); + this.preparedStatement.setString(index++, institutionCode); + this.preparedStatement.setString(index++, jobCode ); + this.preparedStatement.setString(index++, processType ); + this.preparedStatement.setString(index++, bizCode ); + this.preparedStatement.setString(index++, filePath ); + this.preparedStatement.setString(index++, fileName ); + this.preparedStatement.setString(index++, renamedFileName); + this.preparedStatement.setLong (index++, recCnt ); + this.preparedStatement.setLong (index++, fileSize ); + this.preparedStatement.setString(index++, weblogicName ); + this.preparedStatement.setString(index++, phaseStartTime ); + this.preparedStatement.setString(index++, phaseEndTime ); + this.preparedStatement.setString(index++, resultCode ); + this.preparedStatement.setString(index++, errorDesc ); + this.preparedStatement.setString(index++, hdrInfoName ); + this.preparedStatement.setString(index++, fileHeader ); + this.preparedStatement.setString(index++, fileTrailer ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> File DB로그 INSERT 건수 : "+ retValue +" ["+ uuid +" / "+ subUuid +" / "+ fileName +"]"); + + if (retValue == 0) { + String errMsg = ExceptionUtil.getErrorCode("BECEAICLG021", new String[] {uuid, subUuid, fileName}); + throw new DAOException(errMsg); //배치로그 File 테이블 insert 건수가 0 건입니다. [UUID: {1}] [SUB_UUID: {2}] [FILE_NAME: {3}] + } + + return retValue; + + + } catch (DAOException ex) { + logger.debug( "LogDAO.insertLogFile() >>> 수행 SQL 문 : \n"+ INSERT_LOG_FILE); + logger.debug( "LogDAO.insertLogFile() >>>[uuid ][" + uuid + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[subUuid ][" + subUuid + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[processCode ][" + processCode + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[institutionCode][" + institutionCode + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[jobCode ][" + jobCode + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[processType ][" + processType + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[bizCode ][" + bizCode + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[filePath ][" + filePath + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[fileName ][" + fileName + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[renamedFileName][" + renamedFileName + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[recCnt ][" + recCnt + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[fileSize ][" + fileSize + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[weblogicName ][" + weblogicName + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[phaseStartTime ][" + phaseStartTime + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[phaseEndTime ][" + phaseEndTime + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[resultCode ][" + resultCode + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[errorDesc ][" + errorDesc + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[fileHeader ][" + fileHeader + "]"); + logger.debug( "LogDAO.insertLogFile() >>>[fileTrailer ][" + fileTrailer + "]"); + + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG022", new String[] {uuid, subUuid,}); + throw new DAOException(errMsg); //배치로그 File 테이블 insert 시 오류가 발생하였습니다. [UUID: {1}] [SUB_UUID: {2}] [FILE_NAME: {3}] + } finally { + disconnect(); + } + } + + public int updateLogFileRetry(BatchDoc msgDoc) throws DAOException { + + int retValue = 0; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + String jobCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getJobCode() ); //Job 테이블 FK + String bizCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getBizCode() ); //거래구분코드 + String filePath = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFilePath() ); //파일패스 + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() ); //실제파일명 + String renamedFileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getRenamedFileName()); //변경된파일명 + long recCnt = msgDoc.getBatchMsg().getHeader().getTotRecCnt(); //자료건수 + long fileSize = msgDoc.getBatchMsg().getHeader().getFileSize(); //파일사이즈 + String phaseStartTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseStartTime() ); //단계시작시간 + String phaseEndTime = " "; //단계종료시간 (공백 설정) + String resultCode = LogManager.LOG_TYPE_START; //처리구분코드 ('시작'값 설정) + String errorDesc = " "; //에러메시지 (공백 설정) + String hdrInfoName = StringUtil.nvl(msgDoc.getBatchMsg().getHeader().getHdrInfoName() ); //체크파일내용 + String fileHeader = StringUtil.nvl(msgDoc.getBatchMsg().getFileHeader() ); //파일Header + String fileTrailer = StringUtil.nvl(msgDoc.getBatchMsg().getFileTrailer() ); //파일Trailer + +// if ( fileHeader.getBytes().length > 4000){ +// fileHeader = fileHeader.substring(0, 4000); +// } +// if ( fileTrailer.getBytes().length > 4000){ +// fileTrailer = fileTrailer.substring(0, 4000); +// } + if ( fileHeader.getBytes().length > 4000){ + fileHeader = new String(fileHeader.getBytes(), 0, 2000);//20250312 + } + if ( fileTrailer.getBytes().length > 4000){ + fileTrailer = new String(fileTrailer.getBytes(), 0, 2000);//20250312 + } + + try { + + this.connect(UPDATE_FILE_LOG_RETRY); + + index = 1; + this.preparedStatement.setString(index++, jobCode ); + this.preparedStatement.setString(index++, bizCode ); + this.preparedStatement.setString(index++, filePath ); + this.preparedStatement.setString(index++, renamedFileName); + this.preparedStatement.setLong (index++, recCnt ); + this.preparedStatement.setLong (index++, fileSize ); + this.preparedStatement.setString(index++, phaseStartTime ); + this.preparedStatement.setString(index++, phaseEndTime ); + this.preparedStatement.setString(index++, resultCode ); + this.preparedStatement.setString(index++, errorDesc ); + this.preparedStatement.setString(index++, hdrInfoName ); + this.preparedStatement.setString(index++, fileHeader ); + this.preparedStatement.setString(index++, fileTrailer ); + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + this.preparedStatement.setString(index++, fileName ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> File DB로그 재시도 UPDATE 건수 : "+ retValue +" ["+ uuid +" / "+ subUuid +" / "+ fileName +"]"); + + if (retValue == 0) { + String errMsg = ExceptionUtil.getErrorCode("BECEAICLG023", new String[] {uuid, subUuid, fileName}); + throw new DAOException(errMsg); //배치로그 File 테이블 종료 update 건수가 0 건입니다. [UUID: {1}] [SUB_UUID: {2}] [FILE_NAME: {3}] + } + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG024", new String[] {uuid, subUuid, fileName}); + throw new DAOException(errMsg); //배치로그 File 테이블 종료 update 시 오류가 발생하였습니다. [UUID: {1}] [SUB_UUID: {2}] [FILE_NAME: {3}] + } finally { + disconnect(); + } + } + + public int updateLogFileFinish(BatchDoc msgDoc, String logType, String errorDesc) throws DAOException { + + int retValue = 0; + int index = 0; + + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + String jobCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getJobCode() ); //Job 테이블 FK + String bizCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getBizCode() ); //거래구분코드 + String filePath = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFilePath() ); //파일패스 + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() ); //실제파일명 + String renamedFileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getRenamedFileName()); //변경된파일명 + long recCnt = msgDoc.getBatchMsg().getHeader().getTotRecCnt(); //자료건수 + long fileSize = msgDoc.getBatchMsg().getHeader().getFileSize(); //파일사이즈 + String phaseEndTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseEndTime() ); //단계종료시간 + String hdrInfoName = StringUtil.nvl(msgDoc.getBatchMsg().getHeader().getHdrInfoName() ); //체크파일내용 + String fileHeader = StringUtil.nvl(msgDoc.getBatchMsg().getFileHeader() ); //파일Header + String fileTrailer = StringUtil.nvl(msgDoc.getBatchMsg().getFileTrailer() ); //파일Trailer + +// if ( fileHeader.getBytes().length > 4000){ +// fileHeader = fileHeader.substring(0, 4000); +// } +// if ( fileTrailer.getBytes().length > 4000){ +// fileTrailer = fileTrailer.substring(0, 4000); +// } + if ( fileHeader.getBytes().length > 4000){ + fileHeader = new String(fileHeader.getBytes(), 0, 2000);//20250312 + } + if ( fileTrailer.getBytes().length > 4000){ + fileTrailer = new String(fileTrailer.getBytes(), 0, 2000);//20250312 + } + + //파라미터로 받은 errorDesc 은 무시하고 batchMsgDod 에 있는 메시지를 저장한다. + errorDesc = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getErrorMsg() , " "); //에러메시지 + errorDesc = tailStringByByteSize(errorDesc, LOG_FILE_ERROR_DESC_FIELD_LENGTH, "(상위메시지절삭)..."); //길이 초과시 잘라냄 + + try { + + this.connect(UPDATE_FILE_LOG_FINISH); + + index = 1; + this.preparedStatement.setString(index++, jobCode ); + this.preparedStatement.setString(index++, bizCode ); + this.preparedStatement.setString(index++, filePath ); + this.preparedStatement.setString(index++, renamedFileName); + this.preparedStatement.setLong (index++, recCnt ); + this.preparedStatement.setLong (index++, fileSize ); + this.preparedStatement.setString(index++, phaseEndTime ); + this.preparedStatement.setString(index++, logType ); + this.preparedStatement.setString(index++, errorDesc ); + this.preparedStatement.setString(index++, hdrInfoName ); + this.preparedStatement.setString(index++, fileHeader ); + this.preparedStatement.setString(index++, fileTrailer ); + this.preparedStatement.setString(index++, uuid ); + this.preparedStatement.setString(index++, subUuid ); + this.preparedStatement.setString(index++, fileName ); + + retValue = this.executeUpdate(); + logger.info("[ DB로그 ] ==> File DB로그 작업종료 UPDATE 건수 : "+ retValue +" ["+ uuid +" / "+ subUuid +" / "+ fileName +"]"); + + if (retValue == 0) { + String errMsg = ExceptionUtil.getErrorCode("BECEAICLG025", new String[] {uuid, subUuid, fileName}); + throw new DAOException(errMsg); //배치로그 File 테이블 종료 update 건수가 0 건입니다. [UUID: {1}] [SUB_UUID: {2}] [FILE_NAME: {3}] + } + return retValue; + + } catch (DAOException ex) { + logger.error("updateLogFileFinish 에러 발생 uuid:["+ uuid + "], subuuid:[" + subUuid + "],fileName:["+fileName+"]"); + logger.debug("UPDATE_FILE_LOG_FINISH :" + UPDATE_FILE_LOG_FINISH); + logger.debug("jobCode ->[" + jobCode + "]"); + logger.debug("bizCode ->[" + bizCode + "]"); + logger.debug("filePath ->[" + filePath + "]"); + logger.debug("renamedFileName->[" + renamedFileName + "]"); + logger.debug("recCnt ->[" + recCnt + "]"); + logger.debug("fileSize ->[" + fileSize + "]"); + logger.debug("phaseEndTime ->[" + phaseEndTime + "]"); + logger.debug("logType ->[" + logType + "]"); + logger.debug("errorDesc ->[" + errorDesc + "]"); + logger.debug("fileHeader ->[" + fileHeader + "]"); + logger.debug("fileTrailer ->[" + fileTrailer + "]"); + logger.debug("uuid ->[" + uuid + "]"); + logger.debug("subUuid ->[" + subUuid + "]"); + logger.debug("fileName ->[" + fileName + "]"); + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG026", new String[] {uuid, subUuid, fileName}); + throw new DAOException(errMsg); //배치로그 File 테이블 종료 update 시 오류가 발생하였습니다. [UUID: {1}] [SUB_UUID: {2}] [FILE_NAME: {3}] + } finally { + disconnect(); + } + } + + + /** + * 1. 기능 : 문자열을 주어진 크기의 Byte 길이로 주어진 분할개수 만큼 분할해서 배열로 리턴한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param srcString 소스 문자열 + * @param splitCount 분할 개수 + * @param splitByteSize 분할 Byte 길이 + * @param defaultValue 소스 문자열이 분할 개수에 못미치는 경우 디폴트 문자열 + * @return 소스 문자열을 분할 Byte 길이로 분할 개수 만큼 분할된 배열 + **/ + private static String[] splitStringByByteSize(String srcString, int splitCount, int splitByteSize, String defaultValue) { + + //파라미터 오류 체크 + if (splitCount <= 0 || splitByteSize <= 0) return null; + if (defaultValue != null && defaultValue.getBytes().length > splitByteSize) return null; + + //리턴 배열 생성 + String[] splitArray = new String[splitCount]; + for (int i=0; i 0) { + + //배열 복사 길이 계산 + //(분할위치가 한글을 깨지게 하는위치인지 체크하여 깨지는 위치이면 1 byte 적게 복사) + int copyByteSize = (leftByteSize < splitByteSize)? leftByteSize : splitByteSize - (StringUtil.isCrackedHangleIndex(srcByteArray, srcIndex+splitByteSize)? 1 : 0); + + //배열 복사 + byte[] destByteArray = new byte[copyByteSize]; + System.arraycopy(srcByteArray, srcIndex, destByteArray, 0, copyByteSize); + //목적 배열에 String으로 저장 + splitArray[splitIndex++] = new String(destByteArray); + srcIndex += copyByteSize; + + //logger.debug(splitArray[splitIndex-1]); //잘라낸 데이터 로그 프린트 + } + + return splitArray; + } + + //문자열이 byteSize를 초과하면 byteSize 만큼의 tail 문자열을 리턴한다. + //(옵션) tail 된 경우 맨앞에 특정문자열을 붙일 수 있다. 예) "(앞문자열절삭)" + private static String tailStringByByteSize(String srcString, int byteSize, String truncPrefixMsg) { + if (srcString == null || byteSize <= 0) return srcString; + + byte[] srcByteArray = srcString.getBytes(); + int offset = srcByteArray.length - byteSize; + if (offset <= 0) return srcString; //잘라낼 필요가 없으면 그대로 리턴 + + if (StringUtil.isCrackedHangleIndex(srcByteArray, offset) == true) offset++; + int tailLength = srcByteArray.length - offset; //offset 부터 문자열 끝까지 + String tailString = new String(srcByteArray, offset, tailLength); + + if (truncPrefixMsg == null) truncPrefixMsg = ""; + offset = truncPrefixMsg.getBytes().length; + if (offset > 0 && offset < tailLength) { + byte[] tailByteArray = tailString.getBytes(); + if (StringUtil.isCrackedHangleIndex(tailByteArray, offset) == true) offset++; + tailString = truncPrefixMsg + new String(tailByteArray, offset, tailByteArray.length - offset); + } + + return tailString; + } + + public ArrayList getFileLogSuccess() throws DAOException { + + try { + + this.connect(SELECT_FILE_LOG_SUCCESS); + //logger.debug("{ LogDAO.getFileToolLogSuccess() } 수행 SQL 문 : \n"+ SELECT_FILE_TOOL_LOG_SUCCESS); + + ResultSet rs = executeQuery(); + ArrayList alist = new ArrayList(); + while (rs.next()) { + JobFileTransferVO transLog = new JobFileTransferVO(); + transLog.setBjobBzwkDstcd (rs.getString("BjobBzwkDstcd" )); + transLog.setOsidInstiDstcd (rs.getString("OsidInstiDstcd" )); + transLog.setBjobTranDstcdName(rs.getString("BjobTranDstcdName")); + transLog.setBjobMsgDstcd (rs.getString("BjobMsgDstcd" )); + transLog.setSendRecvYn (rs.getString("BjobPtrnDstcd" ).substring(1,2)); + transLog.setSndrcvStartHMS (rs.getString("FileTrsmtStartHMS").substring(8,12)); + transLog.setSndrcvEndHMS (rs.getString("FileTrsmtEndHMS" ).substring(8,12)); + + alist.add(transLog); + } + return alist; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ("당일 거래 로그 조회 중에 오류가 발생했습니다. - "+e.getMessage()); + throw new DAOException(errMsg); + } finally { + disconnect(); + } + } + + public String getFileNameSeq(String procCode, String instiCode, String fileName, boolean flag) throws DAOException{ + + ResultSet rs = null; + int index = 0; + + try { + String sql = SELECT_FILE_NAME_SEQ; + if ( !flag ) + sql = SELECT_RENAMED_FILE_NAME_SEQ; + + this.connect(sql); // + logger.debug("{ LogDAO.getFileNameSeq() } 수행 SQL 문 : \n"+ SELECT_FILE_NAME_SEQ); + + index = 1; + this.preparedStatement.setString(index++, procCode ); + logger.debug("{ LogDAO.getFileNameSeq() } 바인드("+(index-1)+") : ["+ procCode +"]"); + this.preparedStatement.setString(index++, instiCode ); + logger.debug("{ LogDAO.getFileNameSeq() } 바인드("+(index-1)+") : ["+ instiCode +"]"); + this.preparedStatement.setString(index++, fileName ); + logger.debug("{ LogDAO.getFileNameSeq() } 바인드("+(index-1)+") : ["+ fileName +"]"); + + rs = executeQuery(); + + rs.next(); + + return rs.getString(1); + + } catch (Exception ex) { + return "001"; + } finally { + disconnect(); + } + } + + public boolean getFileLogSuccessCheck(String procCode, String instiCode, String bizCode, String fileName) throws DAOException{ + + ResultSet rs = null; + int index = 0; + + String sql = SELECT_FILE_LOG_SUCCESS_COUNT; + try { + + this.connect(sql); + logger.debug("{ LogDAO.getFileLogSuccessCheck() } 수행 SQL 문 : \n"+ SELECT_FILE_LOG_SUCCESS_COUNT); + + index = 1; + this.preparedStatement.setString(index++, procCode ); + logger.debug("{ LogDAO.getFileLogSuccessCheck() } 바인드("+(index-1)+") : ["+ procCode +"]"); + this.preparedStatement.setString(index++, instiCode ); + logger.debug("{ LogDAO.getFileLogSuccessCheck() } 바인드("+(index-1)+") : ["+ instiCode +"]"); + this.preparedStatement.setString(index++, bizCode ); + logger.debug("{ LogDAO.getFileLogSuccessCheck() } 바인드("+(index-1)+") : ["+ instiCode +"]"); + this.preparedStatement.setString(index++, fileName ); + logger.debug("{ LogDAO.getFileLogSuccessCheck() } 바인드("+(index-1)+") : ["+ fileName +"]"); + + rs = executeQuery(); + + rs.next(); + + return (rs.getInt(1) > 0) ? true : false; + + } catch (Exception e) { + String errMsg = ("당일 거래 로그 조회 중에 오류가 발생했습니다. - "+e.getMessage()); + throw new DAOException(errMsg); + } finally { + disconnect(); + } + } +} diff --git a/src/com/eactive/eai/batch/logger/LogManager.java b/src/com/eactive/eai/batch/logger/LogManager.java new file mode 100644 index 0000000..24e27fe --- /dev/null +++ b/src/com/eactive/eai/batch/logger/LogManager.java @@ -0,0 +1,478 @@ +package com.eactive.eai.batch.logger; + +import java.util.ArrayList; +import java.util.Properties; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.scheduler.JobFileTransferVO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; + + +public class LogManager +{ + + + //JPD 를 호출할때 인자를 결합하기위한 DELIMITER + //(LogSender.jpd, LogListener.jpd 에서 사용함) + //public static final String JPD_LOG_DELIMITER = "^||^"; + + //로그타입 정의 + public static final String LOG_TYPE_QUEUE = "Q"; //수행대기로그, DB에 들어가는 값임(1자리, 수정불가) + public static final String LOG_TYPE_START = "S"; //시작로그, DB에 들어가는 값임(1자리, 수정불가) + //public static final String LOG_TYPE_CONTINUE = "P"; //진행로그 + public static final String LOG_TYPE_END = "T"; //종료로그(정상종료), DB에 들어가는 값임(1자리, 수정불가) + public static final String LOG_TYPE_ERROR = "E"; //에러로그(비정상종료), DB에 들어가는 값임(1자리, 수정불가) + public static final String LOG_TYPE_CANCEL = "C"; //사용자중지로그, DB에 들어가는 값임(1자리, 수정불가) + public static final String LOG_TYPE_NOFILE = "N"; //요구수신파일없음, DB에 들어가는 값임(1자리, 수정불가) + // 송수신파일없음으로 변경 2008.12.30 + public static final String LOG_TYPE_UPDATE_MASTER = "U"; //Master로그UPDATE + + //배치메시지 DB로그 레벨 + public static final String PROP_GROUP_NAME_BATCH_DBLOG = "BatchDBLogInfo"; + public static final String PROP_NAME_BATCH_DBLOG_LEVEL = "batch.dblog.level"; + + //'batch.dblog.level' 프라퍼티가 가질 수 있는 값들 + public static final String BATCH_DBLOG_LEVEL_ALL = "1"; //전문저장 + public static final String BATCH_DBLOG_LEVEL_EXCEPT_TELEGRAM = "2"; //전문미저장 + + public static String mBatchDBLogLevel; + + + //디버그용 로그유틸 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + + + //singleton 객체 생성 + private static LogManager instance = new LogManager(); + //singleton 객체 리턴 + public static LogManager getInstance() { + return instance; + } + + //생성자 + private LogManager() { + //DB로그 레벨 설정 (프라퍼티 정보 조회) + String dbLogLevel = null; + try { + + dbLogLevel = PropManager.getInstance().getProperty(PROP_GROUP_NAME_BATCH_DBLOG, PROP_NAME_BATCH_DBLOG_LEVEL); + if (dbLogLevel == null) throw new Exception("BECEAICLG002"); //배치 DB로그 레벨 프라퍼티 정보를 읽어올 수 없습니다. + + if (!dbLogLevel.equals(BATCH_DBLOG_LEVEL_ALL) && + !dbLogLevel.equals(BATCH_DBLOG_LEVEL_EXCEPT_TELEGRAM)) throw new Exception("BECEAICLG003"); //배치 DB로그 레벨 프라퍼티 정보 값이 잘못 설정되어 있습니다. + + } catch (Exception ex) { + //에러로그 기록 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAICLG001"); //배치 DB로그 프라퍼티 정보를 읽어올 수 없습니다. + logger.error(errMsg, ex); + + //디폴트 '전문저장' 설정 + dbLogLevel = BATCH_DBLOG_LEVEL_ALL; + } + + mBatchDBLogLevel = dbLogLevel; + } + + + + /** + * 1. 기능 : 배치JOB의 시작 로그를 DB에 저장한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Master, Stage 로그 테이블의 반영 Row 수 합계 + * @exception Exception 필수 항목이 없는 경우, 해당 로그가 존재 또는 미존재 하는 경우, DB에 로그 저장이 실패한 경우 + **/ + public int setLogStart(BatchDoc msgDoc) throws Exception { + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + logger.info("[ DB로그 ] ■ JOB Start DB로그 호출됨. ["+ msgDoc.getBatchMsg().getHeader().getUUID() + +" / "+ msgDoc.getBatchMsg().getBody().getSubUUID() +"]"); + //========================================== + //1. 필수 항목 체크 + //========================================== + checkMandatoryFiled(msgDoc, LOG_TYPE_START, null); + + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + int resultCnt = 0; + + //========================================== + //2. INSERT 로그 Master (디폴트 단계종료시간:공백, 처리구분코드:S, 에러메시지:공백 설정) + //========================================== + resultCnt += dao.insertLogMaster(msgDoc); + + //========================================== + //3. INSERT 로그 Stage + //========================================== + resultCnt += dao.insertLogStage(msgDoc, LOG_TYPE_END, " "); + + logger.info("[ DB로그 ] JOB Start DB로그 종료. [수행시간 : "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec]"); + return resultCnt; + } + + + /** + * 1. 기능 : 배치JOB의 진행 로그를 DB에 저장한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Master, Stage 로그 테이블의 반영 Row 수 합계 + * @exception Exception 필수 항목이 없는 경우, 해당 로그가 존재 또는 미존재 하는 경우, DB에 로그 저장이 실패한 경우 + **/ + public int setLogStage(BatchDoc msgDoc) throws Exception { + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + logger.info("[ DB로그 ] ■ JOB Stage DB로그 호출됨. ["+ msgDoc.getBatchMsg().getHeader().getUUID() + +" / "+ msgDoc.getBatchMsg().getBody().getSubUUID() + +" / "+ msgDoc.getBatchMsg().getHeader().getLayerCode() + +" / "+ msgDoc.getBatchMsg().getBody().getSubLayerCode() + +" / "+ msgDoc.getBatchMsg().getBody().getNodeCount() + +"] ["+ (msgDoc.getBatchMsg().getPhaseinfo()==null? "" : msgDoc.getBatchMsg().getPhaseinfo().getRuleCode()) + +" / "+ (msgDoc.getBatchMsg().getPhaseinfo()==null? "" : msgDoc.getBatchMsg().getPhaseinfo().getPhaseCode()) +"]"); + //========================================== + //1. 필수 항목 체크 + //========================================== + checkMandatoryFiled(msgDoc, "", null); + + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + int resultCnt = 0; + + //========================================== + //3. INSERT 로그 Stage + //========================================== + resultCnt += dao.insertLogStage(msgDoc, LOG_TYPE_END, " "); + + logger.info("[ DB로그 ] Stage DB로그 종료. [수행시간 : "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec]"); + return resultCnt; + } + + + /** + * 1. 기능 : 배치JOB의 (정상)종료 로그를 DB에 저장한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @return Master, Stage 로그 테이블의 반영 Row 수 합계 + * @exception Exception 필수 항목이 없는 경우, 해당 로그가 존재 또는 미존재 하는 경우, DB에 로그 저장이 실패한 경우 + **/ + public int setLogEnd(BatchDoc msgDoc) throws Exception { + logger.info("[ DB로그 ] ■ JOB End DB로그 호출됨. ["+ msgDoc.getBatchMsg().getHeader().getUUID() + +" / "+ msgDoc.getBatchMsg().getBody().getSubUUID() +"]"); + //String processType = StringUtil.nvlTrim(msgDoc.getEAIBatchMessage().getHeader().getProcessType() ); //작업유형구분코드 + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() ); //파일명 + /* + if (processType.equals(CommonKeys.PROCESS_REQUEST_RECEIVE) && fileName.equals("")) { + logger.info("[ DB로그 ] ★ 요구수신 작업 완료후 파일 미수신으로 판단됨. (batchMsgDoc 에 파일명 없음)"); + return setLogFinish(msgDoc, LOG_TYPE_NOFILE, null); + } + */ + // 요구/응답 송수신 모든 경우에 대하여 송수신 파일이 없으면 송수신 파일 없음으로 세팅 + if (fileName.equals("")) { + return setLogFinish(msgDoc, LOG_TYPE_NOFILE, null); + } + return setLogFinish(msgDoc, LOG_TYPE_END, null); + } + + public int setLogError(BatchDoc msgDoc, String errorDesc) throws Exception { + logger.info("[ DB로그 ] ■ JOB Error DB로그 호출됨. ["+ msgDoc.getBatchMsg().getHeader().getUUID() + +" / "+ msgDoc.getBatchMsg().getBody().getSubUUID() +"]"); + return setLogFinish(msgDoc, LOG_TYPE_ERROR, errorDesc); + } + + public int setLogCancel(BatchDoc msgDoc, String errorDesc) throws Exception { + logger.info("[ DB로그 ] ■ JOB Cancel DB로그 호출됨. ["+ msgDoc.getBatchMsg().getHeader().getUUID() + +" / "+ msgDoc.getBatchMsg().getBody().getSubUUID() +"]"); + return setLogFinish(msgDoc, LOG_TYPE_CANCEL, errorDesc); + } + + /** + * 1. 기능 : 배치JOB의 에러(비정상종료) 로그를 DB에 저장한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @param logType 로그단계(start, terminate, error, cancel 값 중 하나) + * @param errorDesc 에러메시지 + * @return Master, Stage 로그 테이블의 반영 Row 수 합계 + * @exception Exception 필수 항목이 없는 경우, 해당 로그가 존재 또는 미존재 하는 경우, DB에 로그 저장이 실패한 경우 + **/ + private int setLogFinish(BatchDoc msgDoc, String logType, String errorDesc) throws Exception { + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + //========================================== + //1. 필수 항목 체크 + //========================================== + checkMandatoryFiled(msgDoc, logType, errorDesc); + if (errorDesc == null || errorDesc.trim().equals("")) errorDesc = " "; //종료 로그인경우 null 대신 space 입력 + + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + int resultCnt = 0; + checkJobCode(msgDoc); + + //========================================== + //2. '종료' 로그가 아닌경우 Master,Stage,File 로그가 존재하지 않으면 INSERT (시작단계에서 에러 또는 중지가 발생한 경우) + //========================================== + boolean existLogMaster = false; + boolean existLogStage = false; + boolean existLogFile = false; + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName()); + + if (logType != LOG_TYPE_END) { + int[] existLogCnt = dao.existLogCount(msgDoc); + existLogMaster = (existLogCnt[0] > 0)? true : false; + existLogStage = (existLogCnt[1] > 0)? true : false; + existLogFile = (existLogCnt[2] > 0)? true : false; + if (!existLogMaster) resultCnt += dao.insertLogMaster(msgDoc); + if (!existLogStage) resultCnt += dao.insertLogStage(msgDoc, logType, errorDesc); + if (!fileName.equals("")) { + if (!existLogFile) resultCnt += dao.insertLogFile(msgDoc); + resultCnt += dao.updateLogFileFinish(msgDoc, logType, errorDesc); + } + } + + //========================================== + //3. UPDATE 로그 Master (종료시간, 거래처리구분, 장애발생원인 필드) + //========================================== + resultCnt += dao.updateLogMasterFinish(msgDoc, logType, errorDesc); + + logger.info("[ DB로그 ] JOB Finish DB로그 종료. [수행시간 : "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec]"); + return resultCnt; + } + + public int updateLogMaster(BatchDoc msgDoc) throws Exception { + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + logger.info("[ DB로그 ] ■ JOB Update DB로그 호출됨. [UUID: "+ msgDoc.getBatchMsg().getHeader().getUUID() +"], [SUB_UUID: "+ msgDoc.getBatchMsg().getBody().getSubUUID() +"]"); + //========================================== + //1. UPDATE 로그 Master (시작단계 이후 로그 Master의 필드가 결정되는 경우 update) + //========================================== + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + int resultCnt = dao.updateLogMaster(msgDoc); + + logger.info("[ DB로그 ] JOB Update DB로그 종료. [수행시간 : "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec]"); + return resultCnt; + } + + + public int setLogFileStart(BatchDoc msgDoc) throws Exception { + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + logger.info("[ DB로그 ] ■ FILE Start DB로그 호출됨. ["+ msgDoc.getBatchMsg().getHeader().getUUID() + +" / "+ msgDoc.getBatchMsg().getBody().getSubUUID() + +" / "+ msgDoc.getBatchMsg().getHeader().getFileName() +"]"); + //========================================== + //1. 필수 항목 체크 + //========================================== + //checkMandatoryFiled(msgDoc, LOG_TYPE_CONTINUE, null); + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() ); //실제파일명 + if (fileName.equals("")) throw new Exception(ExceptionUtil.getErrorCode("BECEAICLG017", new String[] {"FileName"})); + + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + int resultCnt = 0; + checkJobCode(msgDoc); + + //========================================== + //3. INSERT 로그 File + //========================================== + if (dao.existLogFileCount(msgDoc) == 0) { //최초시도시 INSERT + resultCnt += dao.insertLogFile(msgDoc); + } else { //Timeout 발생후 재시도시 UPDATE + resultCnt += dao.updateLogFileRetry(msgDoc); + } + + logger.info("[ DB로그 ] FILE Start DB로그 종료. [수행시간 : "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec]"); + return resultCnt; + } + + + public int setLogFileEnd(BatchDoc msgDoc) throws Exception { + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + logger.info("[ DB로그 ] ■ FILE End DB로그 호출됨. ["+ msgDoc.getBatchMsg().getHeader().getUUID() + +" / "+ msgDoc.getBatchMsg().getBody().getSubUUID() + +" / "+ msgDoc.getBatchMsg().getHeader().getFileName() +"]"); + //========================================== + //1. 필수 항목 체크 + //========================================== + //checkMandatoryFiled(msgDoc, logType, errorDesc); + String fileName = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getFileName() ); //실제파일명 + if (fileName.equals("")) throw new Exception(ExceptionUtil.getErrorCode("BECEAICLG017", new String[] {"FileName"})); + + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + int resultCnt = 0; + + //========================================== + //3. UPDATE 로그 File (종료시간, 거래처리구분, 장애발생원인 필드) + //========================================== + resultCnt += dao.updateLogFileFinish(msgDoc, LOG_TYPE_END, " "); + + logger.info("[ DB로그 ] FILE End DB로그 종료. [수행시간 : "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec]"); + return resultCnt; + } + + + + /** + * 1. 기능 : 배치메시지 DB로그 시 배치메시지 내 필수항목을 체크하고 해당 메시지 존재여부를 체크한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @param logType 로그단계(start, terminate, error, cancel 값 중 하나) + * @param errorDesc 에러메시지 (로그단계가 error, cancel 인 경우 체크) + * @exception Exception 필수 항목이 없는 경우 + **/ + private void checkMandatoryFiled(BatchDoc msgDoc, String logType, String errorDesc) throws Exception { + + if (msgDoc == null) throw new Exception("BECEAICLG016"); //배치 DB로그 저장시 배치메시지 객체 파라미터가 null 입니다. + + //========================================== + //1. 공통 필수 항목 체크 + //========================================== + //Log Master 테이블 PK : uuid, subUuid + //Log Stage 테이블 PK : uuid, subUuid, layerCode, flowPhaseCode, stageSeq + String uuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getUUID() ); //UUID + String subUuid = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubUUID() ); //sub UUID + String layerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getHeader().getLayerCode() ); //Layer구분코드 + String subLayerCode = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getSubLayerCode() ); //SubLayer코드 + String phaseStartTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseStartTime() ); //단계시작시간 + String phaseEndTime = StringUtil.nvlTrim(msgDoc.getBatchMsg().getBody().getPhaseEndTime() ); //단계종료시간 + errorDesc = StringUtil.nvlTrim(errorDesc); + + + if (uuid .equals("")) throw new Exception(ExceptionUtil.getErrorCode("BECEAICLG017", new String[] {"UUID"})); //배치 DB로그 저장시 배치 메시지 객체의 '?' 항목이 null 또는 공백입니다. + if (subUuid .equals("")) throw new Exception(ExceptionUtil.getErrorCode("BECEAICLG017", new String[] {"SubUUID"})); + if (layerCode .equals("")) throw new Exception(ExceptionUtil.getErrorCode("BECEAICLG017", new String[] {"LayerCode"})); + if (subLayerCode .equals("")) throw new Exception(ExceptionUtil.getErrorCode("BECEAICLG017", new String[] {"subLayerCode"})); + if (phaseStartTime .equals("")) throw new Exception(ExceptionUtil.getErrorCode("BECEAICLG017", new String[] {"PhaseStartTime"})); + if (phaseEndTime .equals("")) msgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + + //========================================== + //2. 단계별 필수 항목 체크 + //========================================== + //에러 로그, 중지 로그인 경우 에러메시지 항목 체크 + if (logType.equals(LOG_TYPE_ERROR) || logType.equals(LOG_TYPE_CANCEL)) { + if (errorDesc.equals("")) throw new Exception("BECEAICLG018"); //배치 DB로그 저장시 에러메시지 파라미터가 null 또는 공백입니다. + } + + } + /** + * 1. 기능 : 배치메시지 DB로그 시 배치메시지 내 필수항목을 체크하고 해당 메시지 존재여부를 체크한다. + * 2. 처리 개요 : + * 3. 주의사항 + * + * @param msgDoc 배치메시지 Document + * @param logType 로그단계(start, terminate, error, cancel 값 중 하나) + * @param errorDesc 에러메시지 (로그단계가 error, cancel 인 경우 체크) + * @exception Exception 필수 항목이 없는 경우 + **/ + private void checkJobCode(BatchDoc msgDoc) { + String jobCode = msgDoc.getBatchMsg().getHeader().getJobCode(); + if ( jobCode == null || jobCode.trim().equals("") ){ + String processCode = msgDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = msgDoc.getBatchMsg().getHeader().getInstitutionCode(); + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + int orgIndex = 0; + ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); + for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex == 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + if (bizCodeEndIndex < 0 && 0 < fileName.length() + bizCodeEndIndex ) bizCodeEndIndex = fileName.length() + bizCodeEndIndex; + + + String bizCode = ""; + + try { + bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + }catch ( Exception e ){ + logger.warn(e.getLocalizedMessage(), e); + } + + // 거래 구분 코드 길이가 가변인 경우( END INDEX가 0인 경우) + if ( orgIndex == 0 ){ + String delStr = null; + try { + Properties orgInfo = PropManager.getInstance().getProperties( + "TelegramInfo{" + processCode + "_" + institutionCode + "}"); + delStr = orgInfo.getProperty( "del.string" ); + + } catch (Exception e) {} + + if ( delStr != null && !delStr.trim().equals("")){ + + int delIndex = bizCode.indexOf(delStr); + + if ( delIndex > -1 ) { + bizCode = bizCode.substring(0, delIndex ); + } + } + } + String msgBizCode = msgDoc.getBatchMsg().getHeader().getBizCode(); + if ( msgBizCode == null || msgBizCode.trim().equals("") ){ + msgDoc.getBatchMsg().getHeader().setBizCode( bizCode ) ; + } + BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); + + if ( info != null ){ + msgDoc.getBatchMsg().getHeader().setJobCode( info.getMsgDstCode() ); + } + } + + } + + public ArrayList getFileLogSuccess() throws DAOException { + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + return dao.getFileLogSuccess(); + } + + public String getFileNameSeq(String procCode, String instiCode, String fileName, boolean flag)throws DAOException{ + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + return dao.getFileNameSeq( procCode, instiCode, fileName, flag); + } + + public boolean getFileLogSuccessCheck(String procCode, String instiCode, String bizCode, String fileName)throws DAOException{ + LogDAO dao = (LogDAO)DAOFactory.newInstance().create(LogDAO.class); + return dao.getFileLogSuccessCheck( procCode, instiCode, bizCode, fileName); + } +} diff --git a/src/com/eactive/eai/batch/logger/LogQuery.java b/src/com/eactive/eai/batch/logger/LogQuery.java new file mode 100644 index 0000000..54355be --- /dev/null +++ b/src/com/eactive/eai/batch/logger/LogQuery.java @@ -0,0 +1,339 @@ +package com.eactive.eai.batch.logger; + +import com.eactive.eai.common.dao.Keys; + +public interface LogQuery +{ + + + /** + * 로그 Master 테이블에서 해당 메시지ID가 존재하는지 조회 + */ + public static final String SELECT_EXIST_LOG_COUNT = + "SELECT A.LogMasterCnt, B.LogStageCnt, C.LogFileCnt \n" + + "FROM ( SELECT COUNT(*) LogMasterCnt \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? ) A, \n" + + " ( SELECT COUNT(*) LogStageCnt \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ04 \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND BjobStgeID = RPAD( ? , 2, ' ') \n" + + " AND PrcssStgeDstcd = RPAD( ? , 2, ' ') \n" + + " AND BjobNodeCasNo = RPAD( ? , 10, ' ') ) B, \n" + + " ( SELECT COUNT(*) LogFileCnt \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND SndrcvFileName = ? ) C"; + + /** + * 로그 Master 테이블 INSERT + */ + public static final String INSERT_LOG_MASTER = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBJ03 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID , TelgmReTralCnt , \n" + + " BjobMsgScheID , BjobDmndMsgCretnHMS, OsidInstiDstcd , \n" + + " BjobBzwkDstcd , BjobPtrnDstcd , MsgSndrID , \n" + + " MsgSndrName , SysLnkgDstcd , LnkgIPInfoName , \n" + + " FlowRuleCd , EAISevrInstncName , TranStartHMS , \n" + + " TranEndHMS , TranPrcssDstcd , EAIObstclOccurCausCtnt, \n" + + " EAIObstclPrcssCtnt , ObstclPrcsrID , ObstclPrcssHMS ) \n" + + "VALUES ( \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ' ' , ' ' , ' ' )"; + + /** + * 로그 Stage 테이블 INSERT + */ + public static final String INSERT_LOG_STAGE = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBJ04 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID , BjobStgeID , \n" + + " PrcssStgeDstcd , BjobRuleCd , BjobStgeCd , \n" + + " BjobStgeSerno , BjobStgePtrnName , BjobFlowCmpoClsName , \n" + + " TelgmDcsnID , TelgmDcsnClsName , TelgmDcsnMsgCd , \n" + + " ThisStgeTelgmID , ThisStgeClsName , ThisStgeMsgCd , \n" + + " TelgmPertypCdValCtnt , TelgmDstcdValCtnt , TelgmMgtCdValCtnt , \n" + + " RspnsCdValCtnt , \n" + + " BjobNodeCasNo , BjobMsgDstcd , OsidInstiDstcd , \n" + + " BjobBzwkDstcd , BjobPtrnDstcd , BjobTranDstcdName , \n" + + " RqstRecvFileStorgDirName, SndrcvFileName , BkupSndrcvFileName , \n" + + " EAISevrInstncName , ThisStgeStartHMS , ThisStgeEndHMS , \n" + + " ThisStgePrcssRsultCd , EAIObstclOccurCausCtnt , BjobTelgmHdr , \n" + + " BjobTelgmTbody ) \n" + + "VALUES ( \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? , ? , ? , \n" + + " ? )"; + + /** + * 로그 Stage 테이블 UPDATE + */ + public static final String UPDATE_LAST_LOG_STAGE = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ04 \n" + + "SET BjobRuleCd = ? , \n" + + " BjobStgeCd = ? , \n" + + " BjobStgeSerno = ? , \n" + + " BjobStgePtrnName = ? , \n" + + " BjobFlowCmpoClsName = ? , \n" + + " TelgmDcsnID = ? , \n" + + " TelgmDcsnClsName = ? , \n" + + " TelgmDcsnMsgCd = ? , \n" + + " ThisStgeTelgmID = ? , \n" + + " ThisStgeClsName = ? , \n" + + " ThisStgeMsgCd = ? , \n" + + " TelgmPertypCdValCtnt = ? , \n" + + " TelgmDstcdValCtnt = ? , \n" + + " TelgmMgtCdValCtnt = ? , \n" + + " RspnsCdValCtnt = ? , \n" + + " BjobNodeCasNo = ? , \n" + + " BjobMsgDstcd = ? , \n" + + " OsidInstiDstcd = ? , \n" + + " BjobBzwkDstcd = ? , \n" + + " BjobPtrnDstcd = ? , \n" + + " BjobTranDstcdName = ? , \n" + + " RqstRecvFileStorgDirName = ? , \n" + + " SndrcvFileName = ? , \n" + + " BkupSndrcvFileName = ? , \n" + + " EAISevrInstncName = ? , \n" + + " ThisStgeStartHMS = ? , \n" + + " ThisStgeEndHMS = ? , \n" + + " ThisStgePrcssRsultCd = ? , \n" + + " EAIObstclOccurCausCtnt = ? , \n" + + " BjobTelgmHdr = ? , \n" + + " BjobTelgmTbody = ? \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND BjobStgeID = ? \n" + + " AND PrcssStgeDstcd = ? \n" + + " AND BjobNodeCasNo = ( SELECT MAX(BjobNodeCasNo ) \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ04 \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND BjobStgeID = ? \n" + + " AND PrcssStgeDstcd = ? )\n"; + + /** + * 로그 Stage 테이블 UPDATE + */ + public static final String UPDATE_LOG_STAGE = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ04 \n" + + "SET BjobRuleCd = ? , \n" + + " BjobStgeCd = ? , \n" + + " BjobStgeSerno = ? , \n" + + " BjobStgePtrnName = ? , \n" + + " BjobFlowCmpoClsName = ? , \n" + + " TelgmDcsnID = ? , \n" + + " TelgmDcsnClsName = ? , \n" + + " TelgmDcsnMsgCd = ? , \n" + + " ThisStgeTelgmID = ? , \n" + + " ThisStgeClsName = ? , \n" + + " ThisStgeMsgCd = ? , \n" + + " TelgmPertypCdValCtnt = ? , \n" + + " TelgmDstcdValCtnt = ? , \n" + + " TelgmMgtCdValCtnt = ? , \n" + + " RspnsCdValCtnt = ? , \n" + + " BjobMsgDstcd = ? , \n" + + " OsidInstiDstcd = ? , \n" + + " BjobBzwkDstcd = ? , \n" + + " BjobPtrnDstcd = ? , \n" + + " BjobTranDstcdName = ? , \n" + + " RqstRecvFileStorgDirName = ? , \n" + + " SndrcvFileName = ? , \n" + + " BkupSndrcvFileName = ? , \n" + + " EAISevrInstncName = ? , \n" + + " ThisStgeStartHMS = ? , \n" + + " ThisStgeEndHMS = ? , \n" + + " ThisStgePrcssRsultCd = ? , \n" + + " EAIObstclOccurCausCtnt = ? , \n" + + " BjobTelgmHdr = ? , \n" + + " BjobTelgmTbody = ? \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND BjobStgeID = ? \n" + + " AND PrcssStgeDstcd = ? \n" + + " AND BjobNodeCasNo = ? \n"; + + /** + * 로그 Master 테이블 UPDATE (종료시간, 거래처리구분, 장애발생원인 필드만) + */ + public static final String UPDATE_MASTER_LOG_FINISH = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + "SET TranEndHMS = ?, \n" + + " TranPrcssDstcd = ?, \n" + + " EAIObstclOccurCausCtnt = ? \n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ?"; + + /** + * 로그 Master 테이블 UPDATE (시작단계 이후 로그 Master의 필드가 결정되는 경우 update) + */ + public static final String UPDATE_MASTER_LOG_CONTINUE = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + "SET BjobMsgScheID = NVL(?, BjobMsgScheID ), \n" + + " OsidInstiDstcd = NVL(?, OsidInstiDstcd), \n" + + " BjobBzwkDstcd = NVL(?, BjobBzwkDstcd ), \n" + + " BjobPtrnDstcd = NVL(?, BjobPtrnDstcd ), \n" + + " MsgSndrID = NVL(?, MsgSndrID ), \n" + + " MsgSndrName = NVL(?, MsgSndrName ), \n" + + " SysLnkgDstcd = NVL(?, SysLnkgDstcd ), \n" + + " FlowRuleCd = NVL(?, FlowRuleCd ), \n" + + " TranStartHMS = NVL(?, TranStartHMS ), \n" + + " TranPrcssDstcd = NVL(?, TranPrcssDstcd) \n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ?"; + + /** + * 로그 File 테이블에서 해당 파일로그가 존재하는지 조회 + */ + public static final String SELECT_FILE_LOG_EXIST_COUNT = + "SELECT COUNT(*) LogFileCnt \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ? \n" + + "AND SndrcvFileName = ?"; + + /** + * 로그 File 테이블 INSERT + */ + public static final String INSERT_LOG_FILE = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBJ08 ( \n" + + " BjobDmndMsgID ,\n" + + " BjobDmndSubMsgID ,\n" + + " BjobBzwkDstcd ,\n" + + " OsidInstiDstcd ,\n" + + " BjobMsgDstcd ,\n" + + " BjobPtrnDstcd ,\n" + + " BjobTranDstcdName ,\n" + + " RqstRecvFileStorgDirName,\n" + + " SndrcvFileName ,\n" + + " BkupSndrcvFileName ,\n" + + " SndrcvRecCnt ,\n" + + " SndrcvFileSize ,\n" + + " EAISevrInstncName ,\n" + + " FileTrsmtStartHMS ,\n" + + " FileTrsmtEndHMS ,\n" + + " ThisStgePrcssRsultCd ,\n" + + " EAIObstclOccurCausCtnt ,\n" + + " HdrInfoName ,\n" + + " BjobFileHdrCtnt ,\n" + + " BjobFileTrailCtnt )\n" + + "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"; + + /** + * 파일 재시도시 로그 File 테이블 UPDATE (시작시간 등...) + */ + public static final String UPDATE_FILE_LOG_RETRY = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + "SET BjobMsgDstcd = NVL(?, BjobMsgDstcd ), \n" + + " BjobTranDstcdName = NVL(?, BjobTranDstcdName ), \n" + + " RqstRecvFileStorgDirName = NVL(?, RqstRecvFileStorgDirName), \n" + + " BkupSndrcvFileName = NVL(?, BkupSndrcvFileName ), \n" + + " SndrcvRecCnt = NVL(?, SndrcvRecCnt ), \n" + + " SndrcvFileSize = NVL(?, SndrcvFileSize ), \n" + + " FileTrsmtStartHMS = NVL(?, FileTrsmtStartHMS ), \n" + + " FileTrsmtEndHMS = NVL(?, FileTrsmtEndHMS ), \n" + + " ThisStgePrcssRsultCd = NVL(?, ThisStgePrcssRsultCd ), \n" + + " EAIObstclOccurCausCtnt = NVL(?, EAIObstclOccurCausCtnt ), \n" + + " HdrInfoName = NVL(?, HdrInfoName ), \n" + + " BjobFileHdrCtnt = NVL(?, BjobFileHdrCtnt ), \n" + + " BjobFileTrailCtnt = NVL(?, BjobFileTrailCtnt ) \n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ? \n" + + "AND SndrcvFileName = ?"; + + /** + * 파일 종료시 로그 File 테이블 UPDATE (종료시간, 에러메시지 등...) + */ + public static final String UPDATE_FILE_LOG_FINISH = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + "SET BjobMsgDstcd = NVL(?, BjobMsgDstcd ), \n" + + " BjobTranDstcdName = NVL(?, BjobTranDstcdName ), \n" + + " RqstRecvFileStorgDirName = NVL(?, RqstRecvFileStorgDirName), \n" + + " BkupSndrcvFileName = NVL(?, BkupSndrcvFileName ), \n" + + " SndrcvRecCnt = NVL(?, SndrcvRecCnt ), \n" + + " SndrcvFileSize = NVL(?, SndrcvFileSize ), \n" + + " FileTrsmtEndHMS = NVL(?, FileTrsmtEndHMS ), \n" + + " ThisStgePrcssRsultCd = NVL(?, ThisStgePrcssRsultCd ), \n" + + " EAIObstclOccurCausCtnt = NVL(?, EAIObstclOccurCausCtnt ), \n" + + " HdrInfoName = NVL(?, HdrInfoName ), \n" + + " BjobFileHdrCtnt = NVL(?, BjobFileHdrCtnt ), \n" + + " BjobFileTrailCtnt = NVL(?, BjobFileTrailCtnt ) \n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ? \n" + + "AND SndrcvFileName = ?"; + + /** + * 당일 성공 거래된 로그를 검색 Framework + NDM + AXWAY (2011.03.23 정동한) + */ + public static final String SELECT_FILE_LOG_SUCCESS = + "SELECT BjobBzwkDstcd AS BjobBzwkDstcd ,\n" + + " OsidInstiDstcd AS OsidInstiDstcd ,\n" + + " BjobMsgDstcd AS BjobMsgDstcd ,\n" + + " BjobPtrnDstcd AS BjobPtrnDstcd ,\n" + + " BjobTranDstcdName AS BjobTranDstcdName,\n" + + " FileTrsmtStartHMS AS FileTrsmtStartHMS,\n" + + " FileTrsmtEndHMS AS FileTrsmtEndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + "WHERE FileTrsmtStartHMS > TO_CHAR(SYSDATE,'YYYYMMDD') \n" + + "AND ThisStgePrcssRsultCd = 'T' \n"; +// + "UNION \n" +// + "SELECT BjobBzwkDstcd AS BjobBzwkDstcd ,\n" +// + " OsidInstiDstcd AS OsidInstiDstcd ,\n" +// + " BjobMsgDstcd AS BjobMsgDstcd ,\n" +// + " EAILumpPgmStusDstcd AS BjobPtrnDstcd ,\n" +// + " \' \' AS BjobTranDstcdName,\n" +// + " EAILumpFileTrsmtStartYMS AS FileTrsmtStartHMS,\n" +// + " EAILumpFileTrsmtEndYMS AS FileTrsmtEndHMS \n" +// + "FROM " + Keys.TABLE_OWNER + "TSEAIBU04 \n" +// + "WHERE EAILumpFileTrsmtStartYMS > TO_CHAR(SYSDATE,'YYYYMMDD) \n" +// + "AND EAILumpPgmNomalDstcd = 'TR' \n" +// + "AND EAILumpPgmStusDstcd IN ( 'DR','DS' ) \n"; + + public static final String SELECT_FILE_NAME_SEQ = + "SELECT LTRIM(TO_CHAR(NVL(MAX(TO_NUMBER(SUBSTR(SndrcvFileName, LENGTH(SndrcvFileName)-2))+1),1),'000')) \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + "WHERE BjobBzwkDstcd = ? \n" + + "AND OsidInstiDstcd = ? \n" + + "AND SndrcvFileName LIKE ? || '*____' ESCAPE '*' \n" + + "AND FileTrsmtStartHMS LIKE TO_CHAR( SYSDATE, 'YYYYMMDD' ) || '%' \n" + + "AND BjobPtrnDstcd IN ( 'AR', 'RR' ) \n" + + "AND ThisStgePrcssRsultCd = 'T' \n"; + + public static final String SELECT_RENAMED_FILE_NAME_SEQ = + "SELECT LTRIM(TO_CHAR(NVL(MAX(TO_NUMBER(SUBSTR(BkupSndrcvFileName, LENGTH(BkupSndrcvFileName)-2))+1),1),'000')) \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + "WHERE BjobBzwkDstcd = ? \n" + + "AND OsidInstiDstcd = ? \n" + + "AND BkupSndrcvFileName LIKE '%' || ? || '*____' ESCAPE '*' \n" + + "AND FileTrsmtStartHMS LIKE TO_CHAR( SYSDATE, 'YYYYMMDD' ) || '%' \n" + + "AND BjobPtrnDstcd IN ( 'AR', 'RR' ) \n" + + "AND ThisStgePrcssRsultCd = 'T' \n"; + + public static final String SELECT_FILE_LOG_SUCCESS_COUNT = + "SELECT COUNT(*) LogFileCnt \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ08 \n" + + "WHERE BjobBzwkDstcd = ? \n" + + "AND OsidInstiDstcd = ? \n" + + "AND BjobTranDstcdName = ? \n" + + "AND SndrcvFileName = ? \n" + + "AND FileTrsmtStartHMS LIKE TO_CHAR( SYSDATE, 'YYYYMMDD' ) || '%' \n" + + "AND BjobPtrnDstcd IN ( 'AR', 'RR' ) \n" + + "AND ThisStgePrcssRsultCd = 'T' \n"; +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/message/EAIBatchMsgManager.java b/src/com/eactive/eai/batch/message/EAIBatchMsgManager.java new file mode 100644 index 0000000..651efd5 --- /dev/null +++ b/src/com/eactive/eai/batch/message/EAIBatchMsgManager.java @@ -0,0 +1,182 @@ +package com.eactive.eai.batch.message; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.doc.BatchDoc.BatchMsg; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.UUIDGenerator; + +public class EAIBatchMsgManager +{ + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public static BatchDoc createBatchMsg(boolean isInitailize) + { + BatchDoc batchMsgDoc = new BatchDoc(); + BatchMsg msg = batchMsgDoc.addNewBatchMsg(); + msg.addNewHeader(); + msg.addNewBody(); + msg.addNewPhaseinfo(); + if (isInitailize) initailzeBatchMsg(batchMsgDoc); + batchMsgDoc.getBatchMsg().getBody().setWLIServerName(System.getProperty("weblogic.Name")); + logger.info("[ EAIBatchMsgManager ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + logger.info("[ EAIBatchMsgManager ] ■ BatchMsgDoc 생성됨."); + logger.info("[ EAIBatchMsgManager ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + return batchMsgDoc; + } + + public static BatchDoc createBatchMsg(String layerCode, boolean isInitailize) + { + BatchDoc batchMsgDoc = createBatchMsg(isInitailize); + batchMsgDoc.getBatchMsg().getHeader().setLayerCode(layerCode); + return batchMsgDoc; + } + + public static BatchDoc createBatchMsg(String layerCode, String subLayerCode, boolean isInitailize) + { + BatchDoc batchMsgDoc = createBatchMsg(isInitailize); + return updateBatchMsg(batchMsgDoc, layerCode, subLayerCode); + } + + public static BatchDoc createBatchMsgWithUUID(boolean isInitailize) + { + BatchDoc batchMsgDoc = createBatchMsg(isInitailize); + String uuid = UUIDGenerator.getUUID(); + batchMsgDoc.getBatchMsg().getHeader().setUUID(uuid); + batchMsgDoc.getBatchMsg().getBody().setSubUUID(uuid); + logger.info("[ EAIBatchMsgManager ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + logger.info("[ EAIBatchMsgManager ] ■ UUID 생성됨 (SUB_UUID 동일설정) : ["+ uuid +"]"); + logger.info("[ EAIBatchMsgManager ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + return batchMsgDoc; + } + + public static BatchDoc createBatchMsgWithUUID(String layerCode, boolean isInitailize) + { + BatchDoc batchMsgDoc = createBatchMsgWithUUID(isInitailize); + batchMsgDoc.getBatchMsg().getHeader().setLayerCode(layerCode); + return batchMsgDoc; + } + + public static BatchDoc createBatchMsgWithUUID(String layerCode, String subLayerCode, boolean isInitailize) + { + BatchDoc batchMsgDoc = createBatchMsgWithUUID(isInitailize); + return updateBatchMsg(batchMsgDoc, layerCode, subLayerCode); + } + + public static BatchDoc updateBatchMsg(BatchDoc batchMsgDoc, String layerCode, String subLayerCode) + { + batchMsgDoc.getBatchMsg().getHeader().setLayerCode(layerCode); + batchMsgDoc.getBatchMsg().getBody().setSubLayerCode(subLayerCode); + return batchMsgDoc; + } + + public static BatchDoc updateBatchMsgWithStageTime(BatchDoc batchMsgDoc, String layerCode, String subLayerCode) + { + updateBatchMsg(batchMsgDoc, layerCode, subLayerCode); + String startTime = CalendarUtil.getCurrentTimeNoDash(); + batchMsgDoc.getBatchMsg().getHeader().setBatchStartTime(startTime); // 배치메시지 생성시간 + batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime(startTime); // 단계 시작시간 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(""); // 단계 종료시간 + return batchMsgDoc; + } + + public static BatchDoc initailzeBatchMsg(BatchDoc batchMsgDoc) + { + batchMsgDoc.getBatchMsg().setTelegramBody (""); + batchMsgDoc.getBatchMsg().setTelegramHeader(""); + batchMsgDoc.getBatchMsg().setFileHeader (""); + batchMsgDoc.getBatchMsg().setFileTrailer (""); + + batchMsgDoc.getBatchMsg().getHeader().setUUID (""); + batchMsgDoc.getBatchMsg().getHeader().setTRXID (""); + batchMsgDoc.getBatchMsg().getHeader().setLayerCode (""); + batchMsgDoc.getBatchMsg().getHeader().setProcessType (""); + batchMsgDoc.getBatchMsg().getHeader().setProcessName (""); + batchMsgDoc.getBatchMsg().getHeader().setProcessCode (""); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode (""); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName (""); +// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType (""); + batchMsgDoc.getBatchMsg().getHeader().setJobCode (""); + batchMsgDoc.getBatchMsg().getHeader().setScheduleCode (""); + batchMsgDoc.getBatchMsg().getHeader().setFileName (""); + batchMsgDoc.getBatchMsg().getHeader().setFilePath (""); + batchMsgDoc.getBatchMsg().getHeader().setUserID (""); + batchMsgDoc.getBatchMsg().getHeader().setUserName (""); + batchMsgDoc.getBatchMsg().getHeader().setUserPassword (""); + batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime (""); + batchMsgDoc.getBatchMsg().getHeader().setScheduleETime (""); + batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName (""); + batchMsgDoc.getBatchMsg().getHeader().setFlowCode (""); + batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode (""); + batchMsgDoc.getBatchMsg().getHeader().setTotRecCnt (-1); + batchMsgDoc.getBatchMsg().getHeader().setFileSize (-1); + batchMsgDoc.getBatchMsg().getHeader().setBlockSize ( 0); + batchMsgDoc.getBatchMsg().getHeader().setSequenceSize ( 0); + batchMsgDoc.getBatchMsg().getHeader().setRemoteIP (""); + batchMsgDoc.getBatchMsg().getHeader().setPort (""); + batchMsgDoc.getBatchMsg().getHeader().setBatchStartTime (""); + batchMsgDoc.getBatchMsg().getHeader().setRequestResponse (""); + batchMsgDoc.getBatchMsg().getHeader().setSendRecv (""); + batchMsgDoc.getBatchMsg().getHeader().setRuleCode (""); + batchMsgDoc.getBatchMsg().getHeader().setRuleDesc (""); +// batchMsgDoc.getBatchMsg().getHeader().setProtocol (""); + batchMsgDoc.getBatchMsg().getHeader().setBizCode (""); + batchMsgDoc.getBatchMsg().getHeader().setFileErrorPath (""); + batchMsgDoc.getBatchMsg().getHeader().setPacketSize ( 0); + batchMsgDoc.getBatchMsg().getHeader().setRecLen ( 0); + batchMsgDoc.getBatchMsg().getHeader().setBaseDate (""); + + batchMsgDoc.getBatchMsg().getBody().setSubUUID (""); + batchMsgDoc.getBatchMsg().getBody().setWLIServerName (""); + batchMsgDoc.getBatchMsg().getBody().setPortNo (""); + batchMsgDoc.getBatchMsg().getBody().setNodeCount ( 0); + batchMsgDoc.getBatchMsg().getBody().setSubLayerCode (""); + batchMsgDoc.getBatchMsg().getBody().setFlowPhaseCode (""); + batchMsgDoc.getBatchMsg().getBody().setLastPhaseCode (""); + batchMsgDoc.getBatchMsg().getBody().setNextPhaseCode (""); + batchMsgDoc.getBatchMsg().getBody().setPhaseType (""); + batchMsgDoc.getBatchMsg().getBody().setLastPhaseType (""); + batchMsgDoc.getBatchMsg().getBody().setNextPhaseType (""); + batchMsgDoc.getBatchMsg().getBody().setSndMsgCode (""); + batchMsgDoc.getBatchMsg().getBody().setRcvMsgCode (""); + batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime (""); + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime (""); + batchMsgDoc.getBatchMsg().getBody().setLastPhaseStartTime (""); + batchMsgDoc.getBatchMsg().getBody().setLastPhaseEndTime (""); + batchMsgDoc.getBatchMsg().getBody().setActionTag (""); + batchMsgDoc.getBatchMsg().getBody().setRecallTag (""); + batchMsgDoc.getBatchMsg().getBody().setTimeoutInterval (""); + batchMsgDoc.getBatchMsg().getBody().setRetryCount ( 0); + batchMsgDoc.getBatchMsg().getBody().setBlockNum ( 0); + batchMsgDoc.getBatchMsg().getBody().setSeqNum ( 0); + batchMsgDoc.getBatchMsg().getBody().setMissingNmField (""); + batchMsgDoc.getBatchMsg().getBody().setMissingNmCount ( 0); + batchMsgDoc.getBatchMsg().getBody().setCurFileSize ( 0); + batchMsgDoc.getBatchMsg().getBody().setRecCnt ( 0); + batchMsgDoc.getBatchMsg().getBody().setLastResCode (""); + batchMsgDoc.getBatchMsg().getBody().setErrorCode ( 0); + batchMsgDoc.getBatchMsg().getBody().setErrorMsg (""); + batchMsgDoc.getBatchMsg().getBody().setRecvedMsg (""); + + batchMsgDoc.getBatchMsg().getPhaseinfo().setRuleCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseType (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setFlowClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (-1); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseClassName (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setBizCodeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setControlCodeValue (""); + batchMsgDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue (""); + return batchMsgDoc; + } + + +} diff --git a/src/com/eactive/eai/batch/osd/OutsideDAO.java b/src/com/eactive/eai/batch/osd/OutsideDAO.java new file mode 100644 index 0000000..6b1a056 --- /dev/null +++ b/src/com/eactive/eai/batch/osd/OutsideDAO.java @@ -0,0 +1,249 @@ +package com.eactive.eai.batch.osd; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class OutsideDAO extends BaseDAO implements OutsideQuery +{ + /** + * TSEAIBJ06을 뒤져서 모든 대외기관 정보를 읽어서 HashMap으로 리턴한다. + */ + public HashMap> getAllOutsideInfo() throws DAOException + { + HashMap> all = new HashMap>(); + ResultSet rs = null; + ArrayList al = null; + OutsideVO vo = null; + try + { + this.connect(GET_ALL_OUTSIDE); +// logger.debug(">> 대외기관 정보......\n" + GET_ALL_OUTSIDE); + rs = this.executeQuery(); + + while(rs.next()) + { + vo = new OutsideVO(); + + vo.setBatchCode (rs.getString("BjobBzwkDstcd" ).trim()); + vo.setOsdCode (rs.getString("OsidInstiDstcd" ).trim()); + vo.setOsdName (rs.getString("OsidInstiName" ).trim()); + vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName" ).trim()); + vo.setSendRuleCode(rs.getString("SendPrcssRuleCd" ).trim()); + vo.setRecvRuleCode(rs.getString("RecvPrcssRuleCd" ).trim()); + vo.setOsdSendPrpt (rs.getString("EAIFileSendPtrnDstcd").trim()); + vo.setOsdRecvPrpt (rs.getString("EAIFileRecvPtrnDstcd").trim()); + vo.setBlkSize (rs.getInt ("TelgmBlckSize" )); + vo.setSequenceSize(rs.getInt ("TelgmSernoSize" )); + vo.setBizStartIdx (rs.getInt ("TranStartIndx" )); + vo.setBizEndIdx (rs.getInt ("TranEndIndx" )); + vo.setPacketSize (rs.getInt ("TelgmPcketSize" )); + vo.setBatchName (rs.getString("BjobBzwkName" ).trim()); + +// logger.debug(" - ["+ vo.getBatchCode() +"] ["+ vo.getBatchName() +"] ["+ vo.getOsdCode() +"] ["+ vo.getOsdName() +"] ["+ vo.getSendRuleCode() +"] ["+ vo.getRecvRuleCode() +"]"); + al = all.remove(vo.getBatchCode()); + if (al == null) { + al = new ArrayList(); + } + al.add(vo); + all.put(vo.getBatchCode(), al); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS001")); + } finally { + this.disconnect(); + } + return all; + } + + /** + * TSEAIBJ05를 읽어서 모든 대외기관 링크정보를 읽어서 HashMap으로 리턴한다. + * 각 대외기관에 대해 2개이상의 링크정보가 있을수 있다. + * HashMap에는 대외기관 코드로 ArrayList를 넣고, + * 각 ArrayList에는 개발 대외기관 링크정보(OutsideLinkVO)인스탄스가 들어간다. + */ + public HashMap> getAllOutsideLinkInfo() throws DAOException + { + HashMap> all = new HashMap>(); + ResultSet rs = null; + ArrayList al = null; + OutsideLinkVO vo = null; + try + { + this.connect(GET_ALL_LINKINFO); + rs = this.executeQuery(); + + logger.debug(">> 대외기관별 연결 정보......"); + while(rs.next()) + { + vo = new OutsideLinkVO(); + + vo.setSyslinkCode (rs.getString("SysLnkgDstcd" ).trim()); + vo.setBatchCode (rs.getString("BjobBzwkDstcd" ).trim()); + vo.setOsdCode (rs.getString("OsidInstiDstcd" ).trim()); + vo.setReqResCode (rs.getString("RqstRspnsDstcd" ).trim()); + vo.setLinkIP (rs.getString("LnkgIPInfoName" ).trim()); + vo.setLinkPort (rs.getString("LnkgPortInfoName" ).trim()); + vo.setUserID (rs.getString("LnkgID" ).trim()); + vo.setPwd (rs.getString("LnkgPwd" ).trim()); + vo.setToVal (rs.getInt ("ToutVal" )); + vo.setLinkStatus (rs.getString("TCirtLnkgStusCd" ).trim()); + vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName").trim()); + vo.setAdpName (rs.getString("AdptrBzwkName" ).trim()); + + logger.debug(" - ["+ vo.getBatchCode() +"] ["+ vo.getOsdCode() +"] ["+ vo.getReqResCode() +"] ["+ vo.getLinkPort() +"] ["+ vo.getLinkIP() +"]"); + al = all.remove(vo.getOsdCode()); + if (al == null) { + al = new ArrayList(); + } + al.add(vo); + all.put(vo.getOsdCode(), al); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS002")); + } finally { + this.disconnect(); + } + return all; + } + + public int updateOutsideLinkInfo(OutsideLinkVO vo) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + this.connect(UPDATE_LINKINFO_ID_PASSWORD); + + index = 1; + this.preparedStatement.setString(index++, vo.getUserID() ); + this.preparedStatement.setString(index++, vo.getPwd() ); + this.preparedStatement.setString(index++, vo.getSyslinkCode() ); + + retValue = this.executeUpdate(); + + if (retValue == 0) { + String errMsg = "";//ExceptionUtil.getErrorCode("BECEAICLG012", new String[] {uuid, subUuid}); //배치로그 Master 테이블 종료 update 건수가 0 건입니다.(UUID: ?, subUUID: ?) + throw new DAOException(errMsg); + } + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = "";//ExceptionUtil.getErrorCode(ex, "BECEAICLG013", new String[] {uuid, subUuid}); //배치로그 Master 테이블 종료 update 시 오류가 발생하였습니다.(UUID: ?, subUUID: ?) + throw new DAOException(errMsg); + } finally { + disconnect(); + } + return retValue; + } + + /** + * TSEAIBJ06을 KEY로 검색하여 해당 대외기관 정보를 읽어서 OutsideVO을 리턴한다. + */ + public OutsideVO getOutsideInfoByKey( String bjobBzwkDstcd, String osidInstiDstcd) throws DAOException + { + ResultSet rs = null; + OutsideVO vo = null; + int index = 0; + + try + { + this.connect(GET_OUTSIDE_BY_KEY); +// logger.debug("OutsideDAO.getOutsideInfoByKey() >>> 수행 SQL 문 : \n"+ GET_OUTSIDE_BY_KEY); + + index = 1; + this.preparedStatement.setString(index++, bjobBzwkDstcd); +// logger.debug("OutsideDAO.getOutsideInfoByKey() >>> 바인드("+(index-1)+") : ["+ bjobBzwkDstcd +"]"); + this.preparedStatement.setString(index++, osidInstiDstcd.trim() ); +// logger.debug("OutsideDAO.getOutsideInfoByKey() >>> 바인드("+(index-1)+") : ["+ osidInstiDstcd.trim() +"]"); + + rs = this.executeQuery(); + + if (rs.next()){ + vo = new OutsideVO(); + + vo.setBatchCode (rs.getString("BjobBzwkDstcd" ).trim()); + vo.setOsdCode (rs.getString("OsidInstiDstcd" ).trim()); + vo.setOsdName (rs.getString("OsidInstiName" ).trim()); + vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName" ).trim()); + vo.setSendRuleCode(rs.getString("SendPrcssRuleCd" ).trim()); + vo.setRecvRuleCode(rs.getString("RecvPrcssRuleCd" ).trim()); + vo.setOsdSendPrpt (rs.getString("EAIFileSendPtrnDstcd").trim()); + vo.setOsdRecvPrpt (rs.getString("EAIFileRecvPtrnDstcd").trim()); + vo.setBlkSize (rs.getInt ("TelgmBlckSize" )); + vo.setSequenceSize(rs.getInt ("TelgmSernoSize" )); + vo.setBizStartIdx (rs.getInt ("TranStartIndx" )); + vo.setBizEndIdx (rs.getInt ("TranEndIndx" )); + vo.setPacketSize (rs.getInt ("TelgmPcketSize" )); + vo.setBatchName (rs.getString("BjobBzwkName" ).trim()); + +// logger.debug(" - ["+ vo.getBatchCode() +"] ["+ vo.getBatchName() +"] ["+ vo.getOsdCode() +"] ["+ vo.getOsdName() +"] ["+ vo.getSendRuleCode() +"] ["+ vo.getRecvRuleCode() +"]"); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS001")); + } finally { + this.disconnect(); + } + return vo; + } + + /** + * TSEAIBJ05를 읽어서 모든 특정 대외 기관 링크정보를 읽어서 HashMap으로 리턴한다. + * 각 대외기관에 대해 2개이상의 링크정보가 있을수 있다. + * HashMap에는 대외기관 코드로 ArrayList를 넣고, + * 각 ArrayList에는 개발 대외기관 링크정보(OutsideLinkVO)인스탄스가 들어간다. + */ + public ArrayList getOutsideLinkInfoByOsdCode(String bjobBzwkDstcd, String osidInstiDstcd) throws DAOException + { + ResultSet rs = null; + ArrayList al = new ArrayList(); + OutsideLinkVO vo = null; + int index = 0; + try + { + this.connect(GET_ALL_LINKINFO_BY_OUTSIDE_KEY); +// logger.debug("OutsideDAO.getOutsideLinkInfoByOsdCode() >>> 수행 SQL 문 : \n"+ GET_ALL_LINKINFO_BY_OUTSIDE_KEY); + + + index = 1; + this.preparedStatement.setString(index++, bjobBzwkDstcd); +// logger.debug("OutsideDAO.getOutsideLinkInfoByOsdCode() >>> 바인드("+(index-1)+") : ["+ bjobBzwkDstcd +"]"); + this.preparedStatement.setString(index++, osidInstiDstcd.trim() ); +// logger.debug("OutsideDAO.getOutsideLinkInfoByOsdCode() >>> 바인드("+(index-1)+") : ["+ osidInstiDstcd.trim() +"]"); + + rs = this.executeQuery(); + + while(rs.next()) + { + vo = new OutsideLinkVO(); + + vo.setSyslinkCode (rs.getString("SysLnkgDstcd" ).trim()); + vo.setBatchCode (rs.getString("BjobBzwkDstcd" ).trim()); + vo.setOsdCode (rs.getString("OsidInstiDstcd" ).trim()); + vo.setReqResCode (rs.getString("RqstRspnsDstcd" ).trim()); + vo.setLinkIP (rs.getString("LnkgIPInfoName" ).trim()); + vo.setLinkPort (rs.getString("LnkgPortInfoName" ).trim()); + vo.setUserID (rs.getString("LnkgID" ).trim()); + vo.setPwd (rs.getString("LnkgPwd" ).trim()); + vo.setToVal (rs.getInt ("ToutVal" )); + vo.setLinkStatus (rs.getString("TCirtLnkgStusCd" ).trim()); + vo.setAdpGroupName(rs.getString("AdptrBzwkGroupName").trim()); + vo.setAdpName (rs.getString("AdptrBzwkName" ).trim()); + +// logger.debug(" - ["+ vo.getBatchCode() +"] ["+ vo.getOsdCode() +"] ["+ vo.getReqResCode() +"] ["+ vo.getLinkPort() +"] ["+ vo.getLinkIP() +"]"); + al.add(vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMOS002")); + } finally { + this.disconnect(); + } + return al; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/osd/OutsideLinkVO.java b/src/com/eactive/eai/batch/osd/OutsideLinkVO.java new file mode 100644 index 0000000..7943029 --- /dev/null +++ b/src/com/eactive/eai/batch/osd/OutsideLinkVO.java @@ -0,0 +1,96 @@ +package com.eactive.eai.batch.osd; + +import java.io.Serializable; + +/** + * TSEAIBJ05 테이블 내용 + */ +public class OutsideLinkVO implements Serializable +{ + private static final long serialVersionUID = 1L; + String sysLinkCode; //SysLnkgDstcd + String batchCode; //BjobBzwkDstcd + String osdCode; //OsidInstiDstcd + String reqResCode; //RqstRspnsDstcd 송수신구분코드 + String linkIP; //LnkgIPInfoName + String linkPort; //LnkgPortInfoName + String userID; //LnkgID + String pwd; //LnkgPwd + int toVal; //ToutVal //Timeout + String linkStatus; //TCirtLnkgStusCd + String adpGroupName; //AdptrBzwkGroupName 어댑터 그룹이름 + String adpName; //AdptrBzwkName 어댑터 이름 + + public String getSyslinkCode() { + return this.sysLinkCode; + } + public void setSyslinkCode(String sysLinkCode) { + this.sysLinkCode = sysLinkCode; + } + public String getBatchCode() { + return this.batchCode; + } + public void setBatchCode(String batchCode) { + this.batchCode = batchCode; + } + public String getOsdCode() { + return this.osdCode; + } + public void setOsdCode(String osdCode) { + this.osdCode = osdCode.trim(); + } + public String getReqResCode() { + return this.reqResCode; + } + public void setReqResCode(String reqResCode) { + this.reqResCode = reqResCode; + } + public String getLinkIP() { + return this.linkIP; + } + public void setLinkIP(String linkIP) { + this.linkIP = linkIP; + } + public String getLinkPort() { + return this.linkPort; + } + public void setLinkPort(String linkPort) { + this.linkPort = linkPort; + } + public String getUserID() { + return this.userID; + } + public void setUserID(String userID) { + this.userID = userID; + } + public String getPwd() { + return this.pwd; + } + public void setPwd(String pwd) { + this.pwd = pwd; + } + public int getToVal() { + return this.toVal; + } + public void setToVal(int toVal) { + this.toVal = toVal; + } + public String getLinkStatus() { + return this.linkStatus; + } + public void setLinkStatus(String linkStatus) { + this.linkStatus = linkStatus; + } + public String getAdpGroupName() { + return this.adpGroupName; + } + public void setAdpGroupName(String adpGroupName) { + this.adpGroupName = adpGroupName; + } + public String getAdpName() { + return this.adpName; + } + public void setAdpName(String adpName) { + this.adpName = adpName; + } +} diff --git a/src/com/eactive/eai/batch/osd/OutsideManager.java b/src/com/eactive/eai/batch/osd/OutsideManager.java new file mode 100644 index 0000000..5f2994f --- /dev/null +++ b/src/com/eactive/eai/batch/osd/OutsideManager.java @@ -0,0 +1,455 @@ +package com.eactive.eai.batch.osd; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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 java.util.HashMap; +import java.util.ArrayList; + +public class OutsideManager implements Lifecycle +{ + /** + * TelegramInfoManager Single Instance + */ + private static OutsideManager instance = new OutsideManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private HashMap> osdInfos; + private HashMap> osdLnkInfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private OutsideManager() { + osdInfos = new HashMap>(); + osdLnkInfos = new HashMap>(); + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static OutsideManager getInstance() { + + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 삭제한다. + * 구현 : by kscheon at 20080506 + */ + public void removeOutsideInfo(String bCode, String outCode) throws Exception + { + + ArrayList oinfo = osdInfos.get(bCode); + + if (oinfo == null){ + throw new RuntimeException("OutsideManager ] removeOutsideInfo - 삭제 OutsideVO가 존재하지 않습니다. - "+bCode +" , "+outCode); + + } else { + OutsideVO ovo = null; + for (int i=0;oinfo.size()>0 && i < oinfo.size(); i++){ + ovo = (OutsideVO)oinfo.get(i); + if(outCode.equals(ovo.getOsdCode())){ + oinfo.remove(i--); + } + } + } + + osdInfos.put(bCode, oinfo); + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + * 구현 : by kscheon at 20080506 + */ + /* + public void updateOutsideInfo(OutsideVO vo) throws Exception + { + String bCode = vo.getBatchCode(); + String outCode = vo.getOsdCode(); + + ArrayList oinfo = osdInfos.get(bCode.trim()); + + if (oinfo == null){ + throw new RuntimeException("OutsideManager ] updateOutsideInfo - 수정될 OutsideVO가 존재하지 않습니다. - "+bCode); + + } else { + OutsideVO ovo = null; + for (int i=0; i < oinfo.size(); i++){ + ovo = (OutsideVO)oinfo.get(i); + if(outCode.equals(ovo.getOsdCode())){ + oinfo.remove(i); + oinfo.add(i, vo); + } + } + } + + osdInfos.put(bCode, oinfo); + } + */ + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + * 구현 : by dhjeong at 20091124 + */ + public void updateOutsideInfo(String bCode, String outCode) throws Exception + { + + ArrayList oinfo = osdInfos.get(bCode); + + if (oinfo == null){ + oinfo = new ArrayList(); + } + OutsideVO ovo = null; + for (int i=0; i < oinfo.size(); i++){ + ovo = (OutsideVO)oinfo.get(i); + if(outCode.equals(ovo.getOsdCode())){ + oinfo.remove(i); + } + } + + DAOFactory daoFactory = DAOFactory.newInstance(); + OutsideDAO dao = (OutsideDAO)daoFactory.create(OutsideDAO.class); + OutsideVO vo = dao.getOutsideInfoByKey(bCode, outCode); + oinfo.add(vo); + + + osdInfos.put(bCode, oinfo); + } + + +/** + * 1.기능: 전문 Key에 해당하는 전문 객체를 삭제한다. + * 구현 : by kscheon at 20080506 + */ + public void removeOutsideLinkInfo(String bCode, String outCode) throws Exception + { + + ArrayList linfo = osdLnkInfos.get(outCode); + + if (linfo == null){ + throw new RuntimeException("[ OutsideManager ] removeOutsideLinkInfo - 삭제 OutsideLinkvoVO가 존재하지 않습니다. - "+bCode +" , "+outCode); + + } else { + OutsideLinkVO lvo = null; + for (int i=0; linfo.size() > 0 && i < linfo.size(); i++){ + lvo = (OutsideLinkVO)linfo.get(i); + if(bCode.equals(lvo.getBatchCode())){ + linfo.remove(i--); + } + } + } + + osdLnkInfos.put(outCode, linfo); + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + * 구현 : by kscheon at 20080506 + */ + public void updateOutsideLinkInfo(OutsideLinkVO vo) throws Exception + { + String outCode = vo.getOsdCode(); + String linkCode = vo.getSyslinkCode().trim(); + + ArrayList linfo = osdLnkInfos.get(outCode.trim()); + + if (linfo == null){ + throw new RuntimeException("[ OutsideManager ] updateOutsideLinkInfo - 수정될 OutsideLinkVO가 존재하지 않습니다. - "+linkCode); + + } else { + OutsideLinkVO lvo = null; + for (int i=0; i < linfo.size(); i++){ + lvo = (OutsideLinkVO)linfo.get(i); + if(linkCode.equals(lvo.getSyslinkCode().trim())){ + linfo.remove(i); + linfo.add(i, vo); + } + } + } + osdLnkInfos.put(outCode, linfo); + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + * 구현 : by dhjeong at 20091124 + */ + public void updateOutsideLinkInfo(String bCode, String outCode ) throws Exception + { + + ArrayList linfo = osdLnkInfos.get(outCode.trim()); + + if (linfo == null){ + linfo = new ArrayList(); + } + OutsideLinkVO lvo = null; + for (int i=0; i < linfo.size(); i++){ + lvo = (OutsideLinkVO)linfo.get(i); + if(bCode.equals(lvo.getBatchCode())){ + linfo.remove(i); + } + } + DAOFactory daoFactory = DAOFactory.newInstance(); + OutsideDAO dao = (OutsideDAO)daoFactory.create(OutsideDAO.class); + ArrayList voList = dao.getOutsideLinkInfoByOsdCode(bCode, outCode); + + for ( int inx= 0; inx < voList.size(); inx++){ + OutsideLinkVO vo = voList.get(inx); + linfo.add(linfo.size(), vo); + } + osdLnkInfos.put(outCode, linfo); + } + + private void updateOutsideLinkIdPassword(OutsideLinkVO vo) throws Exception + { + DAOFactory daoFactory = DAOFactory.newInstance(); + OutsideDAO dao = (OutsideDAO)daoFactory.create(OutsideDAO.class); + dao.updateOutsideLinkInfo(vo); + updateOutsideLinkInfo(vo); + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 전체 HashMap에 추가한다. + */ + /* + public void addOutsideLinkInfo(OutsideLinkVO vo) throws Exception + { + + String oCode = vo.getOsdCode(); + + ArrayList linfo = osdLnkInfos.get(oCode); + + if (linfo == null){ + linfo = new ArrayList(); + linfo.add(linfo.size(), vo); + + } else { + linfo.add(linfo.size(), vo); + } + + osdLnkInfos.put(oCode, linfo); + } + */ + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 전체 HashMap에 추가한다. + */ + public void addOutsideLinkInfo(String bCode, String outCode) throws Exception + { + + + ArrayList linfo = osdLnkInfos.get(outCode); + + if (linfo == null){ + linfo = new ArrayList(); + } + + DAOFactory daoFactory = DAOFactory.newInstance(); + OutsideDAO dao = (OutsideDAO)daoFactory.create(OutsideDAO.class); + ArrayList voList = dao.getOutsideLinkInfoByOsdCode(bCode, outCode); + + for ( int inx= 0; inx < voList.size(); inx++){ + OutsideLinkVO vo = voList.get(inx); + linfo.add(linfo.size(), vo); + } + + osdLnkInfos.put(outCode, linfo); + } + + /** + * Telegram Mapping 정보 조회 : --> 텔레그램 클래스, 메시지 메타코드 + */ + public Object[] getBatchCodeArray() { + return this.osdInfos.keySet().toArray(); + } + + public ArrayList getOutsideInfo(String strBatchCode) + { + if (this.osdInfos == null || this.osdInfos.size() == 0) return null; + return this.osdInfos.get(strBatchCode); + } + + public OutsideVO getOutsideInfo(String processCode, String organCode) + { + ArrayList alist = this.getOutsideInfo(processCode); + if (alist == null || alist.size() == 0) return null; + + for (int i=0; i getOutsideLinkInfo(String strOsdCode) + { + return this.osdLnkInfos.get(strOsdCode); + } + + private ArrayList getOutsideLinkInfo(String strProcCode, String strOsdCode) + { + ArrayList all = getOutsideLinkInfo(strOsdCode); + ArrayList newall = new ArrayList(); + for ( int inx = 0; inx < all.size(); inx++){ + OutsideLinkVO vo = (OutsideLinkVO)all.get( inx ); + if ( vo.getBatchCode().equals(strProcCode)){ + newall.add(vo); + } + } + return newall; + } + + public void updateOsdIdPassword( String strProcCode, String strOsdCode, String userId, String userPassword ) + { + try { + ArrayList alLink = getOutsideLinkInfo(strProcCode, strOsdCode); + for ( int inx = 0; inx < alLink.size(); inx++){ + OutsideLinkVO vo = alLink.get(inx); + vo.setUserID(userId); + vo.setPwd(userPassword); + updateOutsideLinkIdPassword(vo); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) + throw new LifecycleException("BECEAIMOS003"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + DAOFactory daoFactory = DAOFactory.newInstance(); + OutsideDAO dao = null; + try { + dao = (OutsideDAO)daoFactory.create(OutsideDAO.class); + this.osdInfos = dao.getAllOutsideInfo(); + this.osdLnkInfos = dao.getAllOutsideLinkInfo(); + //Object[] keys = this.osdInfos.keySet().toArray() ; + + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMOS004")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMOS005"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + this.osdInfos.clear(); + this.osdLnkInfos.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + +} + diff --git a/src/com/eactive/eai/batch/osd/OutsideQuery.java b/src/com/eactive/eai/batch/osd/OutsideQuery.java new file mode 100644 index 0000000..e3dbd9a --- /dev/null +++ b/src/com/eactive/eai/batch/osd/OutsideQuery.java @@ -0,0 +1,53 @@ +package com.eactive.eai.batch.osd; + +import com.eactive.eai.common.dao.Keys; + +public interface OutsideQuery +{ + public static final String GET_ALL_OUTSIDE = + " SELECT " + + " A.BjobBzwkDstcd, LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, A.OsidInstiName, \n" + + " A.AdptrBzwkGroupName, A.SendPrcssRuleCd, A.RecvPrcssRuleCd, \n" + + " A.EAIFileSendPtrnDstcd, A.EAIFileRecvPtrnDstcd, A.TelgmBlckSize, A.TelgmSernoSize, \n" + + " A.TranStartIndx, A.TranEndIndx, A.TelgmPcketSize, B.BjobBzwkName \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ06 A \n" + + " LEFT OUTER JOIN " + Keys.TABLE_OWNER + "TSEAIBJ02 B \n" +"on A.BjobBzwkDstcd = B.BjobBzwkDstcd" + + " where A.ThisMsgUseYn = '1' "; + + public static final String GET_ALL_LINKINFO = + " SELECT " + + " SysLnkgDstcd, BjobBzwkDstcd, LTRIM(RTRIM(OsidInstiDstcd)) AS OsidInstiDstcd, " + + " RqstRspnsDstcd, LnkgIPInfoName, LnkgPortInfoName, " + + " LnkgID, LnkgPwd, ToutVal, TCirtLnkgStusCd, " + + " AdptrBzwkGroupName, AdptrBzwkName " + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ05 " ; + + public static final String UPDATE_LINKINFO_ID_PASSWORD = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ05 \n" + + "SET LnkgID = ? , \n" + + " LnkgPwd = ? \n" + + " WHERE SysLnkgDstcd = ? \n"; + + public static final String GET_OUTSIDE_BY_KEY = + " SELECT " + + " A.BjobBzwkDstcd, LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, A.OsidInstiName, \n" + + " A.AdptrBzwkGroupName, A.SendPrcssRuleCd, A.RecvPrcssRuleCd, \n" + + " A.EAIFileSendPtrnDstcd, A.EAIFileRecvPtrnDstcd, A.TelgmBlckSize, A.TelgmSernoSize, \n" + + " A.TranStartIndx, A.TranEndIndx, A.TelgmPcketSize, B.BjobBzwkName \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ06 A \n" + + " LEFT OUTER JOIN " + Keys.TABLE_OWNER + "TSEAIBJ02 B \n" +"on A.BjobBzwkDstcd = B.BjobBzwkDstcd \n" + + "WHERE A.BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ?"; + + + public static final String GET_ALL_LINKINFO_BY_OUTSIDE_KEY = + " SELECT " + + " SysLnkgDstcd, BjobBzwkDstcd, LTRIM(RTRIM(OsidInstiDstcd)) AS OsidInstiDstcd, " + + " RqstRspnsDstcd, LnkgIPInfoName, LnkgPortInfoName, " + + " LnkgID, LnkgPwd, ToutVal, TCirtLnkgStusCd, " + + " AdptrBzwkGroupName, AdptrBzwkName " + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ05 \n" + + "WHERE BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(OsidInstiDstcd)) = ?"; + +} diff --git a/src/com/eactive/eai/batch/osd/OutsideVO.java b/src/com/eactive/eai/batch/osd/OutsideVO.java new file mode 100644 index 0000000..e1cf9b9 --- /dev/null +++ b/src/com/eactive/eai/batch/osd/OutsideVO.java @@ -0,0 +1,135 @@ +package com.eactive.eai.batch.osd; + +import java.io.Serializable; + +public class OutsideVO implements Serializable +{ + private static final long serialVersionUID = 1L; + String BatchCode; + String BatchName; + String OsdCode; + String OsdName; + String AdpGroupName; + String SendRuleCode; + String RecvRuleCode; + String OsdSendPrpt; // 대외기관 파일송신 특성치 : R 요구송신, A 응답송신 + String OsdRecvPrpt; // 대외기관 파일수신 특성치 : R 요구수신, A 응답수신 + int BlkSize; + int SequenceSize; + int BizCdStartIdx; + int BizCdEndIdx; + int PacketSize ; + + public int getPacketSize() { + return this.PacketSize; + } + + public void setPacketSize(int packetsize) { + this.PacketSize = packetsize; + } + + public int getBizCdStartIdx() { + return this.BizCdStartIdx; + } + + public void setBizStartIdx(int startIdx) { + this.BizCdStartIdx = startIdx; + } + + public int getBizCdEndIdx() { + return this.BizCdEndIdx; + } + + public void setBizEndIdx(int endIdx) { + this.BizCdEndIdx = endIdx; + } + + public String getBatchCode() { + return this.BatchCode; + } + public void setBatchCode(String BatchCode) { + this.BatchCode = BatchCode; + } + + public String getBatchName() { + return this.BatchName; + } + public void setBatchName(String BatchName) { + this.BatchName = BatchName; + } + + public String getOsdCode() { + return this.OsdCode; + } + public void setOsdCode(String OsdCode) { + this.OsdCode = OsdCode; + } + public String getOsdName() { + return this.OsdName; + } + public void setOsdName(String OsdName) { + this.OsdName = OsdName; + } + public String getAdpGroupName() { + return this.AdpGroupName; + } + public void setAdpGroupName(String AdpGroupName) { + this.AdpGroupName = AdpGroupName; + } + public String getSendRuleCode() { + return this.SendRuleCode; + } + public void setSendRuleCode(String SendRuleCode) { + this.SendRuleCode = SendRuleCode; + } + public String getRecvRuleCode() { + return this.RecvRuleCode; + } + public void setRecvRuleCode(String RecvRuleCode) { + this.RecvRuleCode = RecvRuleCode; + } + public String getOsdSendPrpt() { + return this.OsdSendPrpt; + } + public void setOsdSendPrpt(String OsdSendPrpt) { + this.OsdSendPrpt = OsdSendPrpt; + } + public String getOsdRecvPrpt() { + return this.OsdRecvPrpt; + } + public void setOsdRecvPrpt(String OsdRecvPrpt) { + this.OsdRecvPrpt = OsdRecvPrpt; + } + public int getBlkSize() { + return this.BlkSize; + } + public void setBlkSize(int blksize) { + this.BlkSize = blksize; + } + public int getSequenceSize() { + return this.SequenceSize; + } + public void setSequenceSize(int sequencesize) { + this.SequenceSize = sequencesize; + } + + public String toString(){ + StringBuffer sb = new StringBuffer(); + sb.append("[BatchCode -->" + BatchCode + "]\n" ); + sb.append("[BatchName -->" + BatchName + "]\n" ); + sb.append("[OsdCode -->" + OsdCode + "]\n" ); + sb.append("[OsdName -->" + OsdName + "]\n" ); + sb.append("[AdpGroupName -->" + AdpGroupName + "]\n" ); + sb.append("[SendRuleCode -->" + SendRuleCode + "]\n" ); + sb.append("[RecvRuleCode -->" + RecvRuleCode + "]\n" ); + sb.append("[OsdSendPrpt -->" + OsdSendPrpt + "]\n" ); + sb.append("[OsdRecvPrpt -->" + OsdRecvPrpt + "]\n" ); + sb.append("[BlkSize -->" + BlkSize + "]\n" ); + sb.append("[SequenceSize -->" + SequenceSize + "]\n" ); + sb.append("[BizCdStartIdx -->" + BizCdStartIdx + "]\n" ); + sb.append("[BizCdEndIdx -->" + BizCdEndIdx + "]\n" ); + sb.append("[PacketSize -->" + PacketSize + "]\n" ); + return sb.toString(); + } + +} diff --git a/src/com/eactive/eai/batch/rule/dirInfo/BatchJobInfoVO.java b/src/com/eactive/eai/batch/rule/dirInfo/BatchJobInfoVO.java new file mode 100644 index 0000000..c74e8d5 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/dirInfo/BatchJobInfoVO.java @@ -0,0 +1,121 @@ +package com.eactive.eai.batch.rule.dirInfo; + +import java.io.Serializable; + +public class BatchJobInfoVO implements Serializable +{ + private static final long serialVersionUID = 1L; + private String batchCode; + private String msgDstCode; + private String msgDstName; + private String sndrcvFileName; + private String jobTranDstcd; + private String sendUseYN; + private String recvUseYN; + private long fileHeaderLogSize; + private long fileRecSize; + private long fileTrailerLogSize; + private int priority = 999; + private String uapplCd = ""; + private String[] chrgIDs = {""}; + private String recvNotiUseYn = ""; + private String intfID = ""; + private String sysCd = ""; + public String getBatchCode() { + return batchCode; + } + public void setBatchCode(String batchCode) { + this.batchCode = batchCode; + } + public String getMsgDstCode() { + return msgDstCode; + } + public void setMsgDstCode(String msgDstCode) { + this.msgDstCode = msgDstCode; + } + public String getMsgDstName() { + return msgDstName; + } + public void setMsgDstName(String msgDstName) { + this.msgDstName = msgDstName; + } + public String getSndrcvFileName() { + return sndrcvFileName; + } + public void setSndrcvFileName(String sndrcvFileName) { + this.sndrcvFileName = sndrcvFileName; + } + public String getJobTranDstcd() { + return jobTranDstcd; + } + public void setJobTranDstcd(String jobTranDstcd) { + this.jobTranDstcd = jobTranDstcd; + } + public String getSendUseYN() { + return sendUseYN; + } + public void setSendUseYN(String sendUseYN) { + this.sendUseYN = sendUseYN; + } + public String getRecvUseYN() { + return recvUseYN; + } + public void setRecvUseYN(String recvUseYN) { + this.recvUseYN = recvUseYN; + } + public long getFileHeaderLogSize() { + return fileHeaderLogSize; + } + public void setFileHeaderLogSize(long fileHeaderLogSize) { + this.fileHeaderLogSize = fileHeaderLogSize; + } + public long getFileRecSize() { + return fileRecSize; + } + public void setFileRecSize(long fileRecSize) { + this.fileRecSize = fileRecSize; + } + public long getFileTrailerLogSize() { + return fileTrailerLogSize; + } + public void setFileTrailerLogSize(long fileTrailerLogSize) { + this.fileTrailerLogSize = fileTrailerLogSize; + } + public int getPriority() { + return priority; + } + public void setPriority(int priority) { + this.priority = priority; + } + public String getUapplCd() { + return uapplCd; + } + public void setUapplCd(String uapplCd) { + this.uapplCd = uapplCd; + } + public String[] getChrgIDs() { + return chrgIDs; + } + public void setChrgIDs(String[] chrgIDs) { + this.chrgIDs = chrgIDs; + } + public String getRecvNotiUseYn() { + return recvNotiUseYn; + } + public void setRecvNotiUseYn(String recvNotiUseYn) { + this.recvNotiUseYn = recvNotiUseYn; + } + public String getIntfID() { + return intfID; + } + public void setIntfID(String intfID) { + this.intfID = intfID; + } + public String getSysCd() { + return sysCd; + } + public void setSysCd(String sysCd) { + this.sysCd = sysCd; + } + +} diff --git a/src/com/eactive/eai/batch/rule/dirInfo/BatchJobPriorityManager.java b/src/com/eactive/eai/batch/rule/dirInfo/BatchJobPriorityManager.java new file mode 100644 index 0000000..54fded2 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/dirInfo/BatchJobPriorityManager.java @@ -0,0 +1,179 @@ +package com.eactive.eai.batch.rule.dirInfo; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; + + +import com.eactive.eai.common.util.Logger; + +public class BatchJobPriorityManager implements Serializable +{ + + private static final long serialVersionUID = 1L; + // 파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + private static BatchJobPriorityManager instance = new BatchJobPriorityManager(); + + private HashMap> hmPrioritys; + private HashMap hmDelays; + + private BatchJobPriorityManager() { + hmPrioritys = new HashMap>(); + hmDelays = new HashMap(); + } + + public static BatchJobPriorityManager getInstance() { + return instance; + } + + + public synchronized void addJobPriorityData(String key, ArrayList list) + { + Object obj = hmPrioritys.get(key); + if (obj != null) { + logger.warn("[ BatchJobPriorityManager ] addJobPriorityData >> UUID["+key+"] 에 이미 데이터가 있습니다." + obj); + hmPrioritys.remove(key); + } + hmPrioritys.put(key, list); + } + + public synchronized ArrayList getPriorityData(String key) + { + return hmPrioritys.get(key); + } + + public synchronized void setPriorityData(String key, ArrayList hm) + { + hmPrioritys.remove(key); + hmPrioritys.put(key, hm); + } + + public synchronized void delPriorityData(String key) + { + this.hmPrioritys.remove(key); + } + + public synchronized int getPriorityDataCount() { + return hmPrioritys.size(); + } + + + public synchronized boolean isExecutePrePriority (String key, String bizCode) throws Exception{ + + try { + ArrayList list = getPriorityData(key); + + if (list != null && list.size() > 0){ + for (int i=0; i < list.size(); i++){ + BatchJobPriorityVO bjpvo = (BatchJobPriorityVO)list.get(i); + if (bizCode.equals(bjpvo.getBizCode())){ + if (i == 0){//첫번째 우선순위 목록에 있으면 무조건 선순위 작업 실행 여부는 true. + return true; + }else { + BatchJobPriorityVO pjpvo = (BatchJobPriorityVO)list.get(i-1); + if (pjpvo !=null){ + return pjpvo.isExecuted(); + } + } + } + } + }else { + return false; + } + }catch (Exception e){ + logger.error("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage()); + throw new Exception ("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage()); + } + return false; + } + + public synchronized void updateExecuteJobList(String key, String bizCode, String uuid, String fileName)throws Exception{ + + try{ + ArrayList list = getPriorityData(key); + + if (list != null && list.size() > 0){ + for (int i=0; i < list.size(); i++){ + BatchJobPriorityVO bjpvo = (BatchJobPriorityVO)list.get(i); + if (bizCode.equals(bjpvo.getBizCode())){ + + bjpvo.setUUID(uuid); + bjpvo.setFileName(fileName); + bjpvo.setExecutedFlag(true); + } + } + } + }catch (Exception e){ + logger.error("[ BatchJobPriorityManager] 배치우선작업 처리 결과 변경시 에러가 발생했습니다. - "+e.getMessage()); + throw new Exception ("[ BatchJobPriorityManager] 배치우선작업 처리처리 결과 변경시 에러가 발생했습니다. - "+e.getMessage()); + } + + } + + public synchronized BatchJobPriorityVO getPriorityDatabyBizCode(String key, String bizCode)throws Exception{ + + try { + ArrayList list = getPriorityData(key); + BatchJobPriorityVO bjpvo = null; + if (list != null && list.size() > 0){ + for (int i=0; i < list.size(); i++){ + bjpvo = (BatchJobPriorityVO)list.get(i); + if (bizCode.equals(bjpvo.getBizCode())){ + break; + } + } + } + return bjpvo; + }catch (Exception e){ + logger.error("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage()); + throw new Exception ("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage()); + } + } + + public synchronized HashMap> getPriorityDatas() { + return hmPrioritys; + } + + public String[] getPriorityKeys() { + Iterator it = this.hmPrioritys.keySet().iterator(); + String[] key = new String[this.hmPrioritys.size()]; + for(int i=0;it.hasNext();i++) { + key[i] = (String)it.next(); + } + + Arrays.sort(key); + return key; + } + + public synchronized void setDelaySec(String uuid, long sec){ + hmDelays.put(uuid, new Long(sec)); + } + + public synchronized boolean hasDelaySec(String uuid){ + return hmDelays.containsKey(uuid); + } + + public synchronized long getDelaySec(String uuid){ + long delay = 0; + try { + delay = (hmDelays.get(uuid)).longValue(); + }catch (Exception e){ + logger.error("[ BatchJobPriorityManager ] Delay seconds 를 가져오는데 실패했습니다.- " + e.getMessage()); + delay = -1; + //값변환시 에러이면 -1을 반환.. + } + return delay; + } + + public synchronized void removeDelaySec(String uuid){ + + try{ + hmDelays.remove(uuid); + }catch (Exception e){ + logger.error("[ BatchJobPriorityManager ] removeDelaySec - Delay seconds 를 초기화 하는데 실패했습니다.- "+e.getMessage()); + } + } +} diff --git a/src/com/eactive/eai/batch/rule/dirInfo/BatchJobPriorityVO.java b/src/com/eactive/eai/batch/rule/dirInfo/BatchJobPriorityVO.java new file mode 100644 index 0000000..5053d02 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/dirInfo/BatchJobPriorityVO.java @@ -0,0 +1,116 @@ +package com.eactive.eai.batch.rule.dirInfo; + +import java.io.Serializable; + + + +public class BatchJobPriorityVO implements Serializable +{ + + private static final long serialVersionUID = 1L; + + private String uuid = ""; + private String bizCode = ""; + private String processCd = ""; + private String processName = ""; + private String osdCd = ""; + private String osdName = ""; + private String fileName = ""; + private long firstCallForDelayTime= 0; //마지막 우선순위 작업의 시작시각 + private int dataCount = 0; + private int dataCountInfo = 1; //기본값 1 + private boolean isexe = false; + + public String getBizCode() { + return this.bizCode; + } + + public void setBizCode(String bizCode) { + this.bizCode = bizCode; + } + + public String getProcessCd() { + return this.processCd; + } + + public void setProcessCd(String processCd) { + this.processCd = processCd; + } + + public String getProcessName() { + return this.processName; + } + + public void setProcessName(String processName) { + this.processName = processName; + } + + public String getOsdCd() { + return this.osdCd; + } + + public void setOsdCd(String osdCd) { + this.osdCd = osdCd; + } + + public String getOsdName() { + return this.osdName; + } + + public void setOsdName(String osdName) { + this.osdName = osdName; + } + + public String getFileName() { + return this.fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getUUID(){ + return uuid; + } + + public void setUUID(String id){ + uuid = id; + } + + public long getFirstCallForDelayTime(){ + return firstCallForDelayTime; + } + + public void setFirstCallForDelayTime(long ms){ + firstCallForDelayTime = ms; + } + + public boolean isExecuted(){ + return isexe; + } + + public void setExecutedFlag(boolean flag){ + isexe = flag; + } + + public void setDataCountInfo(int count){ + this.dataCountInfo = count; + } + + public int getDataCountInfo(){ + return dataCountInfo; + + } + + public void setDataCount(int count){ + this.dataCount = count; + } + + public int getDataCount(){ + return dataCount; + + } + +} + + diff --git a/src/com/eactive/eai/batch/rule/dirInfo/DirInfoDAO.java b/src/com/eactive/eai/batch/rule/dirInfo/DirInfoDAO.java new file mode 100644 index 0000000..42920ba --- /dev/null +++ b/src/com/eactive/eai/batch/rule/dirInfo/DirInfoDAO.java @@ -0,0 +1,55 @@ +package com.eactive.eai.batch.rule.dirInfo; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.ArrayList; + +public class DirInfoDAO extends BaseDAO implements DirInfoQuery +{ + + public ArrayList getAllFileInfo() throws DAOException + { + ArrayList al = new ArrayList(); + ResultSet rs = null; + BatchJobInfoVO vo = null; + try + { + this.connect(GET_BIZ_CODE_INFO); + rs = this.executeQuery(); + while(rs.next()) { + vo = new BatchJobInfoVO(); + + vo.setMsgDstCode (rs.getString("BjobMsgDstcd" )); + vo.setMsgDstName (rs.getString("BjobMsgDsticName" )); + vo.setBatchCode (rs.getString("BjobBzwkDstcd" )); + vo.setJobTranDstcd (rs.getString("BjobTranDstcdName" )); + vo.setSendUseYN (rs.getString("EAIFileSendUseYn" )); + vo.setRecvUseYN (rs.getString("EAIFileRecvUseYn" )); + vo.setFileHeaderLogSize (rs.getLong ("BjobTelgmHdrSize" )); + vo.setFileRecSize (rs.getLong ("BjobTelgmRecSize" )); + vo.setFileTrailerLogSize(rs.getLong ("BjobTelgmTrailSize" )); + vo.setPriority (rs.getInt ("MsgPrcssPrity" )); + vo.setSysCd (rs.getString("SysCd" )); + vo.setUapplCd (rs.getString("UapplCd" )); + vo.setSndrcvFileName (rs.getString("SndrcvFileName" )); + vo.setIntfID (rs.getString("IntfID" )); + String chrgIDs = rs.getString("ThisMsgChrgIDs"); + if ( chrgIDs != null ){ + String[] arr = chrgIDs.split(","); + vo.setChrgIDs(arr); + } + vo.setRecvNotiUseYn (rs.getString("RecvNotiUseYn" )); + al.add(vo); + } + + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR012")); + } finally { + this.disconnect(); + } + return al; + } +} diff --git a/src/com/eactive/eai/batch/rule/dirInfo/DirInfoManager.java b/src/com/eactive/eai/batch/rule/dirInfo/DirInfoManager.java new file mode 100644 index 0000000..6536c20 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/dirInfo/DirInfoManager.java @@ -0,0 +1,229 @@ +package com.eactive.eai.batch.rule.dirInfo; + +import java.util.ArrayList; + +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +public class DirInfoManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * TelegramInfoManager Single Instance + */ + private static DirInfoManager instance = new DirInfoManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private ArrayList fileinfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private DirInfoManager() { + fileinfos = new ArrayList(); + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static DirInfoManager getInstance() { + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + +// /** +// * 1.기능: 전문 Key에 해당하는 전문 객체를 삭제한다. +// */ +// public boolean removeDirInfo(DirInfoVO vo) throws Exception +// { +// return false; +// } +// +// /** +// * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. +// */ +// public boolean updateDirInfo(DirInfoVO vo) throws Exception +// { +// return false; +// } +// +// /** +// * 1.기능: 전문 Key에 해당하는 전문 객체를 전체 HashMap에 추가한다. +// */ +// public boolean addDirInfo(DirInfoVO vo) throws Exception +// { +// return false; +// } + + /** + * Telegram Mapping 정보 조회 : --> 텔레그램 클래스, 메시지 메타코드 + */ + + public BatchJobInfoVO getFileInfoByDstcd(String strBatchCode, String strJobTranDstcd) + { + if (this.fileinfos.size() == 0) return null; + + for (int i=0; i> " + this.fileinfos.size()); + } + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) throw new LifecycleException("BECEAIMFR013"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + try { + loadAllFileInfo(); + + } catch (Exception e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMFR014")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) throw new LifecycleException("BECEAIMFR015"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + this.fileinfos.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } +} diff --git a/src/com/eactive/eai/batch/rule/dirInfo/DirInfoQuery.java b/src/com/eactive/eai/batch/rule/dirInfo/DirInfoQuery.java new file mode 100644 index 0000000..62f57ad --- /dev/null +++ b/src/com/eactive/eai/batch/rule/dirInfo/DirInfoQuery.java @@ -0,0 +1,28 @@ +package com.eactive.eai.batch.rule.dirInfo; + +import com.eactive.eai.common.dao.Keys; + +public interface DirInfoQuery +{ + + public static final String GET_BIZ_CODE_INFO = + "SELECT \n" + + "BjobMsgDstcd , \n" + + "BjobMsgDsticName , \n" + + "BjobBzwkDstcd , \n" + + "BjobTranDstcdName , \n" + + "EAIFileSendUseYn , \n" + + "EAIFileRecvUseYn , \n" + + "BjobTelgmHdrSize , \n" + + "BjobTelgmRecSize , \n" + + "BjobTelgmTrailSize, \n" + + "MsgPrcssPrity , \n" + + "SysCd , \n" + + "UapplCd , \n" + + "SndrcvFileName , \n" + + "ThisMsgChrgIDs , \n" + + "RecvNotiUseYn , \n" + + "IntfID \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 \n" + + "WHERE ThisMsgUseYn = '1'"; +} diff --git a/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoDAO.java b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoDAO.java new file mode 100644 index 0000000..886737e --- /dev/null +++ b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoDAO.java @@ -0,0 +1,68 @@ +package com.eactive.eai.batch.rule.kikwanInfo; + +import java.sql.ResultSet; +import java.util.HashMap; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class KikwanInfoDAO extends BaseDAO implements KikwanInfoQuery +{ + + public HashMap getAllKikwanInfos() throws DAOException + { + HashMap map = new HashMap(); + ResultSet rs = null; + KikwanInfoVO vo = null; + try + { + this.connect(GET_ALL_KIKWANCODES); + rs = this.executeQuery(); + + while(rs.next()) + { + vo = new KikwanInfoVO(); + + vo.setKikwanCd ( rs.getString("KikwanCd").trim()); + vo.setKikwanName( rs.getString("KikwanName").trim()); + vo.setSysIp ( rs.getString("SysIp").trim()); + vo.setEncIp ( rs.getString("EncIp").trim()); + + map.put(vo.getKikwanCd(), vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR016")); + } finally { + this.disconnect(); + } + return map; + } + + /** + * 지정된 RuleCode와 PhaseCode에 해당 NodeInfo 리스트를 리턴한다. + */ + public KikwanInfoVO getKikwanInfo(String kikwanCd ) throws DAOException + { + KikwanInfoVO vo = null; + ResultSet rs = null; + try { + this.connect(GET_KIKWANCODE); + this.preparedStatement.setString(1, kikwanCd); + rs = executeQuery(); + vo = new KikwanInfoVO(); + if (rs.next()) + { + vo.setKikwanCd ( rs.getString("KikwanCd").trim()); + vo.setKikwanName( rs.getString("KikwanName").trim()); + vo.setSysIp ( rs.getString("SysIp").trim()); + vo.setEncIp ( rs.getString("EncIp").trim()); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR017", new String[] {kikwanCd, kikwanCd})); + } finally { + this.disconnect(); + } + return vo; + } +} diff --git a/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoManager.java b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoManager.java new file mode 100644 index 0000000..165fba4 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoManager.java @@ -0,0 +1,210 @@ +package com.eactive.eai.batch.rule.kikwanInfo; + +import java.util.HashMap; +import java.util.Iterator; + + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +public class KikwanInfoManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * TelegramInfoManager Single Instance + */ + private static KikwanInfoManager instance = new KikwanInfoManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private HashMap kikwanInfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private KikwanInfoManager() { + kikwanInfos = new HashMap(); + + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static KikwanInfoManager getInstance() { + + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + + + public synchronized void setKikwanInfo(String kikwanCd) + { + try { + DAOFactory daoFactory = DAOFactory.newInstance(); + KikwanInfoDAO dao = (KikwanInfoDAO)daoFactory.create(KikwanInfoDAO.class); + KikwanInfoVO vo = dao.getKikwanInfo(kikwanCd); + this.kikwanInfos.put(kikwanCd, vo); + } catch(DAOException e) { + logger.warn(e.getMessage(), e); + } + } + + public synchronized void removeKikwanInfo(String kikwanCd) + { + this.kikwanInfos.remove(kikwanCd); + } + + public KikwanInfoVO getKikwanInfo(String kikwanCd) + { + return this.kikwanInfos.get(kikwanCd); + } + + public HashMap getAllKikwanInfos(){ + return this.kikwanInfos; + } + + public String[] getAllKikwanCodes() { + String[] kikwancodes = new String[kikwanInfos.size()]; + Iterator it = kikwanInfos.keySet().iterator(); + for(int i=0;it.hasNext();i++) { + kikwancodes[i] = it.next(); + } + return kikwancodes; + } + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) + throw new LifecycleException("BECEAIMFR019"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + DAOFactory daoFactory = DAOFactory.newInstance(); + KikwanInfoDAO dao = null; + try { + dao = (KikwanInfoDAO)daoFactory.create(KikwanInfoDAO.class); + this.kikwanInfos = dao.getAllKikwanInfos(); + logger.info("[kikwanInfoManager]: FTManager 기관 information loaded >> " + this.kikwanInfos.size()); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMFR020")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMFR021"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + this.kikwanInfos.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoQuery.java b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoQuery.java new file mode 100644 index 0000000..e0c6d05 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoQuery.java @@ -0,0 +1,24 @@ +package com.eactive.eai.batch.rule.kikwanInfo; + +import com.eactive.eai.common.dao.Keys; + +public interface KikwanInfoQuery +{ + + public static final String GET_ALL_KIKWANCODES = + " SELECT KikwanCd , \n" + + " KikwanName , \n" + + " SysIp , \n" + + " EncIp \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ21 \n" + + " WHERE ThisMsgUseYn = '1' " ; + + public static final String GET_KIKWANCODE = + " SELECT KikwanCd , \n" + + " KikwanName , \n" + + " SysIp , \n" + + " EncIp \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ21 \n" + + " WHERE KikwanCd = ? " ; + +} diff --git a/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoVO.java b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoVO.java new file mode 100644 index 0000000..dd0f9e5 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/kikwanInfo/KikwanInfoVO.java @@ -0,0 +1,41 @@ +package com.eactive.eai.batch.rule.kikwanInfo; + +import java.io.Serializable; + +public class KikwanInfoVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String kikwanCd = ""; + private String kikwanName = ""; + private String sysIp = ""; + private String encIp = ""; + + public String getKikwanCd() { + return kikwanCd; + } + public void setKikwanCd(String kikwanCd) { + this.kikwanCd = kikwanCd; + } + public String getKikwanName() { + return kikwanName; + } + public void setKikwanName(String kikwanName) { + this.kikwanName = kikwanName; + } + public String getSysIp() { + return sysIp; + } + public void setSysIp(String sysIp) { + this.sysIp = sysIp; + } + public String getEncIp() { + return encIp; + } + public void setEncIp(String encIp) { + this.encIp = encIp; + } + +} diff --git a/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoDAO.java b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoDAO.java new file mode 100644 index 0000000..d0ea8b9 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoDAO.java @@ -0,0 +1,121 @@ +package com.eactive.eai.batch.rule.nodeinfo; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; + +public class NodeInfoDAO extends BaseDAO implements NodeInfoQuery +{ + + public HashMap> getAllNodeInfo() throws DAOException + { + HashMap> all = new HashMap>(); + ResultSet rs = null; + NodeInfoVO vo = null; + try + { + this.connect(GET_ALL_NODES); + rs = this.executeQuery(); + + while(rs.next()) + { + vo = new NodeInfoVO(); + + vo.setRuleCode(rs.getString(1).trim()); + vo.setPhaseCode(rs.getString(2).trim()); + vo.setPhaseType(rs.getString(3).trim()); + vo.setFlowComp(rs.getString(4).trim()); + vo.setTelegramID(rs.getString(5).trim()); + vo.setLengthField(rs.getInt(6)); + vo.setDesc(rs.getString(7).trim()); + + + ArrayList al = all.get(rs.getString(1).trim()); + if (al == null) { + al = new ArrayList(); + al.add(vo); + all.put(rs.getString(1).trim(), al); + } else { + all.remove(rs.getString(1).trim()); + al.add(vo); + all.put(rs.getString(1).trim(), al); + } + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR016")); + } finally { + this.disconnect(); + } + return all; + } + + /** + * 지정된 RuleCode와 PhaseCode에 해당 NodeInfo 리스트를 리턴한다. + */ + public NodeInfoVO getNodeInfo(String strRuleCode, String strPhaseCode) throws DAOException + { + NodeInfoVO vo = null; + ResultSet rs = null; + try { + this.connect(GET_PHASE_NODEINFO); + this.preparedStatement.setString(1, strRuleCode); + this.preparedStatement.setString(2, strPhaseCode); + rs = executeQuery(); + vo = new NodeInfoVO(); + while (rs.next()) + { + vo.setRuleCode(rs.getString(1).trim()); + vo.setPhaseCode(rs.getString(2).trim()); + vo.setPhaseType(rs.getString(3).trim()); + vo.setFlowComp(rs.getString(4).trim()); + vo.setTelegramID(rs.getString(5).trim()); + vo.setLengthField(rs.getInt(6)); + vo.setDesc(rs.getString(7).trim()); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR017", new String[] {strRuleCode, strPhaseCode})); + } finally { + this.disconnect(); + } + return vo; + } + + /** + * 지정된 노드 인포를 읽어 들이는 함수 + */ + public ArrayList getRuleNodeList(String strRuleCode) throws DAOException + { + ArrayList al = new ArrayList(); + ResultSet rs = null; + try + { + this.connect(GET_NODEINFO_LIST); + this.preparedStatement.setString(1, strRuleCode); + rs = executeQuery(); + NodeInfoVO vo = null; + while(rs.next()) + { + vo = new NodeInfoVO(); + + vo.setRuleCode(rs.getString(1).trim()); + vo.setPhaseCode(rs.getString(2).trim()); + vo.setPhaseType(rs.getString(3).trim()); + vo.setFlowComp(rs.getString(4).trim()); + vo.setTelegramID(rs.getString(5).trim()); + vo.setLengthField(rs.getInt(6)); + vo.setDesc(rs.getString(7).trim()); + + al.add(vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR018", new String[] {strRuleCode})); + } finally { + this.disconnect(); + } + return al; + } +} diff --git a/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoManager.java b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoManager.java new file mode 100644 index 0000000..9f8bdcf --- /dev/null +++ b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoManager.java @@ -0,0 +1,247 @@ +package com.eactive.eai.batch.rule.nodeinfo; + +import java.util.ArrayList; +import java.util.HashMap; + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +public class NodeInfoManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * TelegramInfoManager Single Instance + */ + private static NodeInfoManager instance = new NodeInfoManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private HashMap> nodeInfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private NodeInfoManager() { + nodeInfos = new HashMap>(); + + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static NodeInfoManager getInstance() { + + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 삭제한다. + */ + public boolean removeTelegramInfo(NodeInfoVO telegramInfoVO) throws Exception + { + return false; + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + */ + public boolean updateTelegramInfo(NodeInfoVO telegramInfoVO) throws Exception + { + return false; + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 전체 HashMap에 추가한다. + */ + public boolean addTelegramInfo(NodeInfoVO telegramInfoVO) throws Exception + { + return false; + } + + /** + * Telegram Mapping 정보 조회 : --> 텔레그램 클래스, 메시지 메타코드 + */ + + public HashMap> getAllData() throws Exception + { + return this.nodeInfos; + } + + public synchronized void setRuleCodeArray(String strRuleCode, ArrayList al) + { + this.nodeInfos.put(strRuleCode, al); + } + + public synchronized void removeRuleCodeArray(String strRuleCode) + { + this.nodeInfos.remove(strRuleCode); + } + + public NodeInfoVO getNodeInfo(String strRuleCode, String strPhaseCode) + { + ArrayList al = (ArrayList) this.nodeInfos.get(strRuleCode); + if (al == null) { + return null; + } else { + for (int i=0; i getRuleNodeList(String strRuleCode) throws Exception + { + ArrayList al = this.nodeInfos.get(strRuleCode); + ArrayList al_target = new ArrayList(); + + if (al != null) { + for (int i=0; i> " + this.nodeInfos.size()); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMFR020")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMFR021"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + this.nodeInfos.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoQuery.java b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoQuery.java new file mode 100644 index 0000000..745a83c --- /dev/null +++ b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoQuery.java @@ -0,0 +1,64 @@ +package com.eactive.eai.batch.rule.nodeinfo; + +import com.eactive.eai.common.dao.Keys; + +public interface NodeInfoQuery +{ + /* DB컬럼명 변경으로 인한 수정 - by kscheon + public static final String GET_ALL_NODES = + " select " + + " RuleCode, PhaseCode, " + + " PhaseType, FlowComp, " + + " TelegramID, LengthField, Desc " + + " from " + Keys.TABLE_OWNER + "tseaibr03 " ; + */ + public static final String GET_ALL_NODES = + " select " + + " BjobBzwkPrcssDstcd, BjobStgeDstcd, " + + " BjobStgePtrnName, BjobFlowCmpoName, " + + " TelgmClsID, UnitTelgmLen, BjobNodeDesc " + + " from " + Keys.TABLE_OWNER + "tseaibr03 " ; + + /** + * 지정된 RuleCode에 해당 하는 노드를 리턴해 준다. + */ + /* DB컬럼명 변경으로 인한 수정 - by kscheon + public static final String GET_PHASE_NODEINFO = + " select " + + " RuleCode, PhaseCode, " + + " PhaseType, FlowComp, " + + " TelegramID, LengthField, Desc " + + " from " + Keys.TABLE_OWNER + "tseaibr03 " + + " where RuleCode = ? " + + " and UPPER(PhaseCode) = ? "; + */ + public static final String GET_PHASE_NODEINFO = + " select " + + " BjobBzwkPrcssDstcd, BjobStgeDstcd, " + + " BjobStgePtrnName, BjobFlowCmpoName, " + + " TelgmClsID, UnitTelgmLen, BjobNodeDesc " + + " from " + Keys.TABLE_OWNER + "tseaibr03 " + + " where BjobBzwkPrcssDstcd = ? " + + " and UPPER(BjobStgeDstcd) = ? "; + + /** + * 지정된 RuleCode 를 가지고 NodeInfo 리스트를 리턴해준다. + */ + /* DB컬럼명 변경으로 인한 수정 - by kscheon + public static final String GET_NODEINFO_LIST = + " select " + + " RuleCode, PhaseCode, " + + " PhaseType, FlowComp, " + + " TelegramID, LengthField, Desc " + + " from " + Keys.TABLE_OWNER + "tseaibr03 " + + " where UPPER(RuleCode) = ? " ; + */ + public static final String GET_NODEINFO_LIST = + " select " + + " BjobBzwkPrcssDstcd, BjobStgeDstcd, " + + " BjobStgePtrnName, BjobFlowCmpoName, " + + " TelgmClsID, UnitTelgmLen, BjobNodeDesc " + + " from " + Keys.TABLE_OWNER + "tseaibr03 " + + " where UPPER(BjobBzwkPrcssDstcd) = ? " ; + +} diff --git a/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoVO.java b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoVO.java new file mode 100644 index 0000000..748e254 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/nodeinfo/NodeInfoVO.java @@ -0,0 +1,61 @@ +package com.eactive.eai.batch.rule.nodeinfo; + +import java.io.Serializable; + +public class NodeInfoVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String RuleCode = ""; //CHAR(20) + private String PhaseCode ; //CHAR(10) + private String PhaseType ; //VARCHAR2(10) + private String FlowComp ; //VARCHAR2(100) + private String TelegramID; //VARCHAR2(100) + private int LengthField; //Number + private String Desc ; //VARCHAR2(100) + + public String getDesc() { + return Desc; + } + public void setDesc(String desc) { + Desc = desc; + } + public String getFlowComp() { + return FlowComp; + } + public void setFlowComp(String flowComp) { + FlowComp = flowComp; + } + public String getPhaseCode() { + return PhaseCode; + } + public void setPhaseCode(String phaseCode) { + PhaseCode = phaseCode; + } + public String getPhaseType() { + return PhaseType; + } + public void setPhaseType(String phaseType) { + PhaseType = phaseType; + } + public String getRuleCode() { + return RuleCode; + } + public void setRuleCode(String ruleCode) { + RuleCode = ruleCode; + } + public String getTelegramID() { + return TelegramID; + } + public void setTelegramID(String telegramID) { + TelegramID = telegramID; + } + public int getLengthField() { + return LengthField; + } + public void setLengthField(int lengthField) { + LengthField = lengthField; + } +} diff --git a/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoDAO.java b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoDAO.java new file mode 100644 index 0000000..4716111 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoDAO.java @@ -0,0 +1,68 @@ +package com.eactive.eai.batch.rule.phaseinfo; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; + +public class PhaseInfoDAO extends BaseDAO implements PhaseInfoQuery +{ + /** + * 각 흐름규칙의 첫번째 노드를 읽어들인다. + */ + + public HashMap> getAllPhaseInfos() throws DAOException + { + HashMap> all = new HashMap>(); + ResultSet rs = null; + PhaseInfoVO vo = null; + try + { + this.connect(GET_ALL_PHASES); + rs = this.executeQuery(); + + while(rs.next()) + { + vo = new PhaseInfoVO(); + vo.setRuleCode(rs.getString(1).trim()); + vo.setPhaseSeq(rs.getString(2).trim()); + vo.setPhaseCode(rs.getString(3).trim()); + vo.setPhaseType(rs.getString(4).trim()); + vo.setDesc(rs.getString(5).trim()); + vo.setTelegramType(rs.getString(6).trim()); + vo.setOpCode(rs.getString(7).trim()); + vo.setTrClass(rs.getString(8).trim()); + vo.setTOVal(rs.getInt(9)); + vo.setRepeat(rs.getInt(10)); + vo.setConditionTxt(rs.getString(11).trim()); + vo.setPriority(rs.getInt(12)); + vo.setCTelegramType(rs.getString(13).trim()); + vo.setCOpCode(rs.getString(14).trim()); + vo.setCTrClass(rs.getString(15).trim()); + vo.setCResCode(rs.getString(16).trim()); + vo.setTelegramID(rs.getString(17).trim()); + vo.setNextPhaseCode(rs.getString(18).trim()); + + + ArrayList al = all.get(vo.getRuleCode()); + if (al == null) { + al = new ArrayList(); + al.add(vo); + all.put(vo.getRuleCode(), al); + } else { + all.remove(vo.getRuleCode()); + al.add(vo); + all.put(vo.getRuleCode(), al); + } + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR024")); + } finally { + this.disconnect(); + } + return all; + } +} diff --git a/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoManager.java b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoManager.java new file mode 100644 index 0000000..ec4e2e3 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoManager.java @@ -0,0 +1,224 @@ +package com.eactive.eai.batch.rule.phaseinfo; + +import java.util.ArrayList; +import java.util.HashMap; + + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +/** + * PhaseInfo 관련한 DB Table " + Keys.TABLE_OWNER + "tseaibr02 조회를 위한 모든 함수를 정의하는 클래스 + */ +public class PhaseInfoManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * TelegramInfoManager Single Instance + */ + private static PhaseInfoManager instance = new PhaseInfoManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private HashMap> phaseInfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private PhaseInfoManager() { + phaseInfos = new HashMap>(); + + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static PhaseInfoManager getInstance() { + + return instance; + } + + public synchronized void setRuleCodeArray(String strRuleCode, ArrayList al) throws Exception + { + this.phaseInfos.put(strRuleCode, al); + } + + public synchronized void removeRuleCodeArray(String strRuleCode) throws Exception + { + this.phaseInfos.remove(strRuleCode); + } + + /** + * Telegram Mapping 정보 조회 : --> 텔레그램 클래스, 메시지 메타코드 + */ + public ArrayList getPhaseInfo(String strRuleCode, String strCurrPhaseCode) throws Exception + { + ArrayList al = new ArrayList(); + ArrayList al_target = new ArrayList(); + + al = this.phaseInfos.get(strRuleCode); + if (al != null) { + for (int i=0; i> getAllData() throws Exception + { + return this.phaseInfos; + } + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) + throw new LifecycleException("BECEAIMFR025"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + DAOFactory daoFactory = DAOFactory.newInstance(); + PhaseInfoDAO dao = null; + try { + dao = (PhaseInfoDAO)daoFactory.create(PhaseInfoDAO.class); + this.phaseInfos = dao.getAllPhaseInfos(); + logger.info("[PhaseInfoManager] : phase information loaded >> " + this.phaseInfos.size()); + + Object[] objs = this.phaseInfos.keySet().toArray(); + for(int i=0; i arr = this.phaseInfos.get((String)objs[i]); + if (arr!=null) { + for (int z=0; z> phase changing rule : " + vo.getRuleCode()); + } + logger.debug(" - ["+vo.getRuleCode()+"] ["+vo.getPhaseCode()+"] ["+vo.getTelegramType()+"] ["+vo.getConditionTxt()+"] ["+vo.getCTelegramType()+"] ["+vo.getNextPhaseCode()+"]"); + } + } + } + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMFR026")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMFR027"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + this.phaseInfos.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoQuery.java b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoQuery.java new file mode 100644 index 0000000..326f011 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoQuery.java @@ -0,0 +1,31 @@ +package com.eactive.eai.batch.rule.phaseinfo; + +import com.eactive.eai.common.dao.Keys; + +public interface PhaseInfoQuery +{ + + public static final String GET_ALL_PHASES = + "SELECT BjobBzwkPrcssDstcd ," + + " BjobStgeSerno ," + + " BjobStgeDstcd ," + + " BjobStgePtrnName ," + + " BjobStgeFlxblCndnDesc ," + + " TelgmPtrnDstcd ," + + " TelgmDtalsOperCd ," + + " BjobCmnTelgmTranCd ," + + " ToutVal ," + + " BjobIterNotms ," + + " CndnItemDcsnCtnt ," + + " TranPrcssPrity ," + + " CndnTelgmPtrnCd ," + + " CndnTelgmMgtCd ," + + " CndnTranClsfiCd ," + + " CndnRspnsCd ," + + " TelgmClsID ," + + " NextStgeDstcdName " + + "FROM " + Keys.TABLE_OWNER + "TSEAIBR02 " + + "ORDER BY BjobBzwkPrcssDstcd," + + " BjobStgeSerno "; + +} diff --git a/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoVO.java b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoVO.java new file mode 100644 index 0000000..fd6c83d --- /dev/null +++ b/src/com/eactive/eai/batch/rule/phaseinfo/PhaseInfoVO.java @@ -0,0 +1,150 @@ +package com.eactive.eai.batch.rule.phaseinfo; + +import java.io.Serializable; + +public class PhaseInfoVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String RuleCode = ""; //CHAR(20) + private String PhaseSeq ; //CHAR(3) + private String PhaseCode ; //CHAR(10) + private String PhaseType ; //VARCHAR2(10) + private String Desc ; //VARCHAR2(100) + private String TelegramType ; //CHAR(4) + private String OpCode ; //CHAR(3) + private String TrClass ; //VARCHAR2(10) + private int TOVal ; //NUMBER(15) + private int Repeat ; //NUMBER(3) + private String ConditionTxt ; //VARCHAR2(10) + private int Priority ; //NUMBER(3) + private String CTelegramType ; //CHAR(4) + private String COpCode ; //CHAR(3) + private String CTrClass ; //VARCHAR2(10) + private String CResCode ; //CHAR(3) + private String TelegramID; + private String NextPhaseCode ; //CHAR(10) + + public String getConditionTxt() { + return ConditionTxt; + } + public void setConditionTxt(String conditionTxt) { + ConditionTxt = conditionTxt; + } + public String getCOpCode() { + return COpCode; + } + public void setCOpCode(String opCode) { + COpCode = opCode; + } + public String getCResCode() { + return CResCode; + } + public void setCResCode(String resCode) { + CResCode = resCode; + } + public String getCTelegramType() { + return CTelegramType; + } + public void setCTelegramType(String telegramType) { + CTelegramType = telegramType; + } + public String getCTrClass() { + return CTrClass; + } + public void setCTrClass(String trClass) { + CTrClass = trClass; + } + public String getDesc() { + return Desc; + } + public void setDesc(String desc) { + Desc = desc; + } + public String getNextPhaseCode() { + return NextPhaseCode; + } + public void setNextPhaseCode(String nextPhaseCode) { + NextPhaseCode = nextPhaseCode; + } + public String getOpCode() { + return OpCode; + } + public void setOpCode(String opCode) { + OpCode = opCode; + } + public String getPhaseCode() { + return PhaseCode; + } + public void setPhaseCode(String phaseCode) { + PhaseCode = phaseCode; + } + public String getPhaseSeq() { + return PhaseSeq; + } + public void setPhaseSeq(String phaseSeq) { + PhaseSeq = phaseSeq; + } + public String getPhaseType() { + return PhaseType; + } + public void setPhaseType(String phaseType) { + PhaseType = phaseType; + } + public int getPriority() { + return Priority; + } + public void setPriority(int priority) { + Priority = priority; + } + public int getRepeat() { + return Repeat; + } + public void setRepeat(int repeat) { + Repeat = repeat; + } + public String getRuleCode() { + return RuleCode; + } + public void setRuleCode(String ruleCode) { + RuleCode = ruleCode; + } + public String getTelegramType() { + return TelegramType; + } + public void setTelegramType(String telegramType) { + TelegramType = telegramType; + } + public int getTOVal() { + return TOVal; + } + public void setTOVal(int val) { + TOVal = val; + } + public String getTrClass() { + return TrClass; + } + public void setTrClass(String trClass) { + TrClass = trClass; + } + public String getTelegramID() { + return TelegramID; + } + public void setTelegramID(String telegramID) { + TelegramID = telegramID; + } + @Override + public String toString() { + return "PhaseInfoVO [RuleCode=" + RuleCode + ", PhaseSeq=" + PhaseSeq + + ", PhaseCode=" + PhaseCode + ", PhaseType=" + PhaseType + + ", Desc=" + Desc + ", TelegramType=" + TelegramType + + ", OpCode=" + OpCode + ", TrClass=" + TrClass + ", TOVal=" + + TOVal + ", Repeat=" + Repeat + ", ConditionTxt=" + + ConditionTxt + ", Priority=" + Priority + ", CTelegramType=" + + CTelegramType + ", COpCode=" + COpCode + ", CTrClass=" + + CTrClass + ", CResCode=" + CResCode + ", TelegramID=" + + TelegramID + ", NextPhaseCode=" + NextPhaseCode + "]"; + } +} diff --git a/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoDAO.java b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoDAO.java new file mode 100644 index 0000000..2394459 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoDAO.java @@ -0,0 +1,61 @@ +package com.eactive.eai.batch.rule.ruleinfo; + +import java.sql.ResultSet; +import java.util.HashMap; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RuleInfoDAO extends BaseDAO implements RuleInfoQuery +{ + public HashMap getAllRuleInfo() throws DAOException + { + HashMap all = new HashMap(); + ResultSet rs = null; + RuleInfoVO vo = null; + try + { + this.connect(GET_ALL_RULEINFO); + rs = this.executeQuery(); + + while(rs.next()) + { + vo = new RuleInfoVO(); + vo.setRuleCode(rs.getString(1).trim()); + vo.setDesc(rs.getString(2).trim()); + + all.put(vo.getRuleCode(), vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR028")); + } finally { + this.disconnect(); + } + return all; + } + /** + * Rule 정보를 읽어 낸다. + */ + public RuleInfoVO getRuleInfo(String strRuleCode) throws DAOException + { + RuleInfoVO vo = new RuleInfoVO(); + ResultSet rs = null; + try { + this.connect(GET_RULEINFO_BYCODE); + this.preparedStatement.setString(1, strRuleCode); + rs = executeQuery(); + vo = new RuleInfoVO(); + while (rs.next()) + { + vo.setRuleCode(rs.getString(1)); + vo.setDesc(rs.getString(2)); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR029", new String[] {strRuleCode})); + } finally { + this.disconnect(); + } + return vo; + } +} diff --git a/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoManager.java b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoManager.java new file mode 100644 index 0000000..43a0d37 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoManager.java @@ -0,0 +1,226 @@ +package com.eactive.eai.batch.rule.ruleinfo; + +import java.util.HashMap; + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +public class RuleInfoManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * TelegramInfoManager Single Instance + */ + private static RuleInfoManager instance = new RuleInfoManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private HashMap ruleInfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private RuleInfoManager() { + ruleInfos = new HashMap(); + + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static RuleInfoManager getInstance() { + + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 삭제한다. + */ + public boolean removeRuleInfo(RuleInfoVO telegramInfoVO) throws Exception + { + return false; + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + */ + public boolean updateRuleInfo(RuleInfoVO telegramInfoVO) throws Exception + { + return false; + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 전체 HashMap에 추가한다. + */ + public boolean addRuleInfo(RuleInfoVO telegramInfoVO) throws Exception + { + return false; + } + + public synchronized void setRuleCodeArray(String strRuleCode, RuleInfoVO vo) throws Exception + { + this.ruleInfos.put(strRuleCode, vo); + } + + public synchronized void removeRuleCodeArray(String strRuleCode) throws Exception + { + this.ruleInfos.remove(strRuleCode); + } + + /** + * Telegram Mapping 정보 조회 : --> 텔레그램 클래스, 메시지 메타코드 + */ + + public RuleInfoVO getRuleInfo(String strRuleCode) + { + RuleInfoVO vo = this.ruleInfos.get(strRuleCode); + if (vo != null) { + return vo; + } + return new RuleInfoVO(); + } + + public HashMap getAllData() throws Exception + { + return this.ruleInfos; + } + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) + throw new LifecycleException("BECEAIMFR030"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + DAOFactory daoFactory = DAOFactory.newInstance(); + RuleInfoDAO dao = null; + try { + dao = (RuleInfoDAO)daoFactory.create(RuleInfoDAO.class); + this.ruleInfos = dao.getAllRuleInfo(); + logger.info("RuleInfoManager: phase information loaded >> " + this.ruleInfos.size()); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMFR031")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMFR032"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + this.ruleInfos.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + +} diff --git a/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoQuery.java b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoQuery.java new file mode 100644 index 0000000..270e41d --- /dev/null +++ b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoQuery.java @@ -0,0 +1,34 @@ +package com.eactive.eai.batch.rule.ruleinfo; + +import com.eactive.eai.common.dao.Keys; + +public interface RuleInfoQuery +{ + /* DB컬럼명 변경으로 인한 수정 - by kscheon + public static final String GET_ALL_RULEINFO = + " select " + + " RuleCode, Desc " + + " from " + Keys.TABLE_OWNER + "tseaibr04 "; + */ + public static final String GET_ALL_RULEINFO = + " select " + + " BjobBzwkPrcssDstcd, FlowRulePtrnDesc " + + " from " + Keys.TABLE_OWNER + "tseaibr04 "; + + /** + * 주어진 RULE CODE를 가지고 RuleInfo DB (" + Keys.TABLE_OWNER + "TSEAIBR04)에서 해당 RULE정보를 읽어낸다. + */ + /* DB컬럼명 변경으로 인한 수정 - by kscheon + public static final String GET_RULEINFO_BYCODE = + " select " + + " RuleCode, Desc " + + " from " + Keys.TABLE_OWNER + "tseaibr04 " + + " where RuleCode = ? " ; + */ + public static final String GET_RULEINFO_BYCODE = + " select " + + " BjobBzwkPrcssDstcd, FlowRulePtrnDesc " + + " from " + Keys.TABLE_OWNER + "tseaibr04 " + + " where BjobBzwkPrcssDstcd = ? " ; + +} diff --git a/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoVO.java b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoVO.java new file mode 100644 index 0000000..05e7444 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/ruleinfo/RuleInfoVO.java @@ -0,0 +1,26 @@ +package com.eactive.eai.batch.rule.ruleinfo; + +import java.io.Serializable; + +public class RuleInfoVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String RuleCode = "" ; //CHAR(20) + private String Desc = ""; //VARCHAR2(100) + + public String getDesc() { + return Desc; + } + public void setDesc(String desc) { + Desc = desc; + } + public String getRuleCode() { + return RuleCode; + } + public void setRuleCode(String ruleCode) { + RuleCode = ruleCode; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/rule/sysInfo/SysInfoDAO.java b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoDAO.java new file mode 100644 index 0000000..09b21b5 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoDAO.java @@ -0,0 +1,80 @@ +package com.eactive.eai.batch.rule.sysInfo; + +import java.sql.ResultSet; +import java.util.HashMap; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Seed; + +public class SysInfoDAO extends BaseDAO implements SysInfoQuery +{ + + public HashMap getAllSysInfos() throws DAOException + { + HashMap map = new HashMap(); + ResultSet rs = null; + SysInfoVO vo = null; + try + { + this.connect(GET_ALL_SYSCODES); + rs = this.executeQuery(); + + while(rs.next()) + { + vo = new SysInfoVO(); + + vo.setSysCd ( rs.getString("sysCd").trim()); + vo.setSysName ( rs.getString("sysName").trim()); + vo.setSysIp ( rs.getString("sysIp").trim()); + vo.setSysPort ( rs.getShort("sysPort")); + vo.setUserId ( rs.getString("userId").trim()); + vo.setUserPassword( Seed.decrypt(rs.getString("userPassword"))); + vo.setSendDir ( rs.getString("sendDir").trim()); + vo.setRecvDir ( rs.getString("recvDir").trim()); + vo.setSftpYn ( rs.getString("sftpYn").trim()); + + + map.put(vo.getSysCd(), vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR016")); + } finally { + this.disconnect(); + } + return map; + } + + /** + * 지정된 RuleCode와 PhaseCode에 해당 NodeInfo 리스트를 리턴한다. + */ + public SysInfoVO getSysInfo(String sysCd ) throws DAOException + { + SysInfoVO vo = null; + ResultSet rs = null; + try { + this.connect(GET_SYSCODE); + this.preparedStatement.setString(1, sysCd); + rs = executeQuery(); + vo = new SysInfoVO(); + if (rs.next()) + { + vo.setSysCd ( rs.getString("sysCd").trim()); + vo.setSysName ( rs.getString("sysName").trim()); + vo.setSysIp ( rs.getString("sysIp").trim()); + vo.setSysPort ( rs.getShort("sysPort")); + vo.setUserId ( rs.getString("userId").trim()); + vo.setUserPassword( Seed.decrypt(rs.getString("userPassword"))); + vo.setSendDir ( rs.getString("sendDir").trim()); + vo.setRecvDir ( rs.getString("recvDir").trim()); + vo.setSftpYn ( rs.getString("sftpYn").trim()); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR017", new String[] {sysCd, sysCd})); + } finally { + this.disconnect(); + } + return vo; + } +} diff --git a/src/com/eactive/eai/batch/rule/sysInfo/SysInfoManager.java b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoManager.java new file mode 100644 index 0000000..228a5b5 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoManager.java @@ -0,0 +1,209 @@ +package com.eactive.eai.batch.rule.sysInfo; + +import java.util.HashMap; +import java.util.Iterator; + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +public class SysInfoManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * TelegramInfoManager Single Instance + */ + private static SysInfoManager instance = new SysInfoManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private HashMap sysInfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private SysInfoManager() { + sysInfos = new HashMap(); + + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static SysInfoManager getInstance() { + + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + + + public synchronized void setSysInfo(String sysCd) + { + try { + DAOFactory daoFactory = DAOFactory.newInstance(); + SysInfoDAO dao = (SysInfoDAO)daoFactory.create(SysInfoDAO.class); + SysInfoVO vo = dao.getSysInfo(sysCd); + this.sysInfos.put(sysCd, vo); + } catch(DAOException e) { + logger.warn(e.getMessage(), e); + } + } + + public synchronized void removeSysInfo(String sysCd) + { + this.sysInfos.remove(sysCd); + } + + public SysInfoVO getSysInfo(String sysCd) + { + return this.sysInfos.get(sysCd); + } + + public HashMap getAllSysInfos(){ + return this.sysInfos; + } + + public String[] getAllSysCodes() { + String[] syscodes = new String[sysInfos.size()]; + Iterator it = sysInfos.keySet().iterator(); + for(int i=0;it.hasNext();i++) { + syscodes[i] = it.next(); + } + return syscodes; + } + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) + throw new LifecycleException("BECEAIMFR019"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + DAOFactory daoFactory = DAOFactory.newInstance(); + SysInfoDAO dao = null; + try { + dao = (SysInfoDAO)daoFactory.create(SysInfoDAO.class); + this.sysInfos = dao.getAllSysInfos(); + logger.info("[SysInfoManager]: system information loaded >> " + this.sysInfos.size()); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMFR020")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMFR021"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + this.sysInfos.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/rule/sysInfo/SysInfoQuery.java b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoQuery.java new file mode 100644 index 0000000..3852387 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoQuery.java @@ -0,0 +1,34 @@ +package com.eactive.eai.batch.rule.sysInfo; + +import com.eactive.eai.common.dao.Keys; + +public interface SysInfoQuery +{ + + public static final String GET_ALL_SYSCODES = + " SELECT SysCd , \n" + + " SysName , \n" + + " SysIp , \n" + + " SysPort , \n" + + " UserId , \n" + + " UserPassword, \n" + + " SendDir , \n" + + " RecvDir , \n" + + " SftpYn \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ11 \n" + + " WHERE ThisMsgUseYn = '1' " ; + + public static final String GET_SYSCODE = + " SELECT SysCd , \n" + + " SysName , \n" + + " SysIp , \n" + + " SysPort , \n" + + " UserId , \n" + + " UserPassword, \n" + + " SendDir , \n" + + " RecvDir , \n" + + " SftpYn \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ11 \n" + + " WHERE SysCd = ? " ; + +} diff --git a/src/com/eactive/eai/batch/rule/sysInfo/SysInfoVO.java b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoVO.java new file mode 100644 index 0000000..88eb24c --- /dev/null +++ b/src/com/eactive/eai/batch/rule/sysInfo/SysInfoVO.java @@ -0,0 +1,75 @@ +package com.eactive.eai.batch.rule.sysInfo; + +import java.io.Serializable; + +public class SysInfoVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String sysCd = ""; + private String sysName = ""; + private String sysIp = ""; + private short sysPort = -1; + private String userId = ""; + private String userPassword= ""; + private String sendDir = ""; + private String recvDir = ""; + private String sftpYn = ""; + + public String getSysCd() { + return sysCd; + } + public void setSysCd(String sysCd) { + this.sysCd = sysCd; + } + public String getSysName() { + return sysName; + } + public void setSysName(String sysName) { + this.sysName = sysName; + } + public String getSysIp() { + return sysIp; + } + public void setSysIp(String sysIp) { + this.sysIp = sysIp; + } + public short getSysPort() { + return sysPort; + } + public void setSysPort(short sysPort) { + this.sysPort = sysPort; + } + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + public String getUserPassword() { + return userPassword; + } + public void setUserPassword(String userPassword) { + this.userPassword = userPassword; + } + public String getSendDir() { + return sendDir; + } + public void setSendDir(String sendDir) { + this.sendDir = sendDir; + } + public String getRecvDir() { + return recvDir; + } + public void setRecvDir(String recvDir) { + this.recvDir = recvDir; + } + public String getSftpYn() { + return sftpYn; + } + public void setSftpYn(String sftpYn) { + this.sftpYn = sftpYn; + } +} diff --git a/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoDAO.java b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoDAO.java new file mode 100644 index 0000000..b636c8e --- /dev/null +++ b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoDAO.java @@ -0,0 +1,41 @@ +package com.eactive.eai.batch.rule.telegraminfo; + +import java.sql.ResultSet; +import java.util.HashMap; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class TelegramInfoDAO extends BaseDAO implements TelegramInfoQuery +{ + /** + * HashMap getAllTelegramInfos() + * 모든 텔레그램 정보를 구해서 해쉬맵으로 리턴해준다. + */ + public HashMap getAllTelegramInfos() throws DAOException + { + HashMap all = new HashMap(); + ResultSet rs = null; + TelegramInfoVO pvo = null; + try + { + this.connect(GET_ALL_TELEGRAM_INFO); + rs = this.executeQuery(); + + while(rs.next()) + { + pvo = new TelegramInfoVO(); + pvo.setTelegramID(rs.getString(1).trim()); + pvo.setMsgMetaDstcd(rs.getString(2).trim()); + pvo.setTelegramClsName(rs.getString(3).trim()); + all.put(pvo.getTelegramID(), pvo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR033")); + } finally { + this.disconnect(); + } + return all; + } +} diff --git a/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoManager.java b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoManager.java new file mode 100644 index 0000000..85f6861 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoManager.java @@ -0,0 +1,222 @@ +package com.eactive.eai.batch.rule.telegraminfo; + +import java.util.HashMap; + + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +public class TelegramInfoManager implements Lifecycle +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * TelegramInfoManager Single Instance + */ + private static TelegramInfoManager instance = new TelegramInfoManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 전문 정보를 저장하는 collection + */ + private HashMap telegramInfos; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private TelegramInfoManager() { + telegramInfos = new HashMap(); + + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static TelegramInfoManager getInstance() { + + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 삭제한다. + */ + public boolean removeTelegramInfo(TelegramInfoVO telegramInfoVO) throws Exception + { + return false; + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + */ + public boolean updateTelegramInfo(TelegramInfoVO telegramInfoVO) throws Exception + { + return false; + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 전체 HashMap에 추가한다. + */ + public boolean addTelegramInfo(TelegramInfoVO telegramInfoVO) throws Exception + { + return false; + } + + public synchronized void setRuleCodeArray(String strRuleCode, TelegramInfoVO vo) throws Exception + { + this.telegramInfos.put(strRuleCode, vo); + } + + public synchronized void removeRuleCodeArray(String strRuleCode) throws Exception + { + this.telegramInfos.remove(strRuleCode); + } + + /** + * Telegram Mapping 정보 조회 : --> 텔레그램 클래스, 메시지 메타코드 + */ + public TelegramInfoVO getTelegramInfo(String telegramID) throws Exception + { + TelegramInfoVO vo = null; + vo = (TelegramInfoVO) this.telegramInfos.get(telegramID); + return vo; + } + + public HashMap getAllData() throws Exception + { + return this.telegramInfos; + } + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) + throw new LifecycleException("BECEAIMFR035"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + DAOFactory daoFactory = DAOFactory.newInstance(); + TelegramInfoDAO dao = null; + try { + dao = (TelegramInfoDAO)daoFactory.create(TelegramInfoDAO.class); + this.telegramInfos = dao.getAllTelegramInfos(); + logger.info("TelegramInfoManager: phase information loaded >> " + this.telegramInfos.size()); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMFR036")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMFR037"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } +} diff --git a/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoQuery.java b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoQuery.java new file mode 100644 index 0000000..354ed90 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoQuery.java @@ -0,0 +1,16 @@ +package com.eactive.eai.batch.rule.telegraminfo; + +import com.eactive.eai.common.dao.Keys; + +public interface TelegramInfoQuery +{ + + /** + * 모든 Telegram 정보를 구한다. + */ + public static final String GET_ALL_TELEGRAM_INFO = + "SELECT TelgmClsID ,\n" + + " MsgMetaDstcd,\n" + + " TelgmClsName \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBR05\n"; +} diff --git a/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoVO.java b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoVO.java new file mode 100644 index 0000000..fca3c04 --- /dev/null +++ b/src/com/eactive/eai/batch/rule/telegraminfo/TelegramInfoVO.java @@ -0,0 +1,33 @@ +package com.eactive.eai.batch.rule.telegraminfo; + +import java.io.Serializable; + +public class TelegramInfoVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String telegramID = ""; + private String telegramClsName = ""; + private String MsgMetaDstcd = ""; + + public String getTelegramID() { + return telegramID; + } + public void setTelegramID(String pTelegramID) { + this.telegramID = pTelegramID; + } + public String getTelegramClsName() { + return telegramClsName; + } + public void setTelegramClsName(String pTelegramClsName) { + this.telegramClsName = pTelegramClsName; + } + public String getMsgMetaDstcd() { + return this.MsgMetaDstcd; + } + public void setMsgMetaDstcd(String pMsgMetaDstcd) { + this.MsgMetaDstcd = pMsgMetaDstcd; + } +} diff --git a/src/com/eactive/eai/batch/running/BatchOpenFileManager.java b/src/com/eactive/eai/batch/running/BatchOpenFileManager.java new file mode 100644 index 0000000..75fd96b --- /dev/null +++ b/src/com/eactive/eai/batch/running/BatchOpenFileManager.java @@ -0,0 +1,65 @@ +package com.eactive.eai.batch.running; + +import java.util.HashMap; +import java.io.FileInputStream; +import java.io.BufferedReader; +import java.io.BufferedInputStream; + +public class BatchOpenFileManager { + + private static BatchOpenFileManager instance = new BatchOpenFileManager(); + + public static BatchOpenFileManager getInstance() { + return instance; + } + private HashMap mapFileName; //File 이름 ( full path ) + private HashMap mapFin; //FileInputStream 객체 + private HashMap mapFbr; //BufferedReader 객체 + private HashMap mapBis; + + private BatchOpenFileManager(){ + mapFileName = new HashMap(); + mapFin = new HashMap(); + mapFbr = new HashMap(); + mapBis = new HashMap(); + } + + public void addFile(String strUUID, String fileName, FileInputStream fin) { + mapFileName.put( strUUID, fileName ); + mapFin.put( strUUID, fin ); + } + + public void addFbr(String strUUID, String fileName, BufferedReader fbr) { + mapFileName.put( strUUID, fileName ); + mapFbr.put( strUUID, fbr ); + } + + public void removeFile(String strUUID) { + mapFileName.remove( strUUID ); + mapFin.remove( strUUID ); + mapFbr.remove( strUUID ); + mapBis.remove( strUUID ); + } + + public FileInputStream getFile(String strUUID) { + return mapFin.get(strUUID); + } + + public BufferedReader getFbr(String strUUID) { + return mapFbr.get(strUUID); + } + + public void addBis(String strUUID, String fileName, BufferedInputStream fbr) { + mapFileName.put( strUUID, fileName ); + mapBis.put( strUUID, fbr ); + } + + public void removeBis(String strUUID) { + mapFileName.remove( strUUID ); + mapBis.remove( strUUID ); + } + + public BufferedInputStream getBis(String strUUID) { + return mapBis.get(strUUID); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/running/BatchRunningJobManager.java b/src/com/eactive/eai/batch/running/BatchRunningJobManager.java new file mode 100644 index 0000000..7e38f9d --- /dev/null +++ b/src/com/eactive/eai/batch/running/BatchRunningJobManager.java @@ -0,0 +1,146 @@ +package com.eactive.eai.batch.running; + +import java.net.Socket; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; + + +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class BatchRunningJobManager +{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + private static BatchRunningJobManager instance = new BatchRunningJobManager(); + + public static BatchRunningJobManager getInstance() { + return instance; + } + + private HashMap mapSocketService; //실시간 연결소켓 객체 (요구송수신,응답송수신 통합) + private HashMap mapBatchDoc; //실시간 BatchDoc 객체 (요구송수신,응답송수신 통합) + + private BatchRunningJobManager() { + mapSocketService = new HashMap(); + mapBatchDoc = new HashMap(); + } + + public synchronized void addRunningJobInfo(String strUUID, SocketService service, BatchDoc batchDoc) { + mapSocketService.put(strUUID, service); + mapBatchDoc .put(strUUID, batchDoc); + printAllRunningJob(); + } + + public synchronized void removeRunningJobInfo(String strUUID) { + mapSocketService.remove(strUUID); + mapBatchDoc .remove(strUUID); + printAllRunningJob(); + } + + public synchronized void updateRunningDocument(String strUUID, BatchDoc batchDoc) { + mapBatchDoc .put(strUUID, batchDoc); + } + + public synchronized SocketService getRunningSocketService(String strUUID) { + return mapSocketService.get(strUUID); + } + + public synchronized Socket getRunningSocket(String strUUID) { + try { + SocketService service = (SocketService) mapSocketService.get(strUUID); + if (service == null) return null; + + return service.getCurrentSocket(); + + } catch (Exception ex) { + logger.error("", ex); + return null; + } + } + + public synchronized BatchDoc getRunningDocument(String strUUID) { + return mapBatchDoc.get(strUUID); + } + + public synchronized HashMap getAllRunningDocuments() { + return mapBatchDoc; + } + + public synchronized int getRunningJobCount() { + return mapSocketService.size(); + } + + public synchronized boolean isJobRunning(String strUUID) { + return (mapSocketService.get(strUUID) == null)? false : true; + } + + public synchronized boolean isSocketClosed(String strUUID) { + SocketService service = (SocketService) mapSocketService.get(strUUID); + if (service == null) return true; + if (service.getCurrentSocket() == null) return true; + return service.getCurrentSocket().isClosed(); + } + + public synchronized void closeRunningSocket(String strUUID) { + SocketService service = (SocketService) mapSocketService.get(strUUID); + if (service == null) return; + service.disconnect(); + } + + private synchronized static void printAllRunningJob() { + + try { + int jobCount = instance.getRunningJobCount(); + logger.info("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"); + logger.info("■■■■■ 진행중인 일괄전송 작업 건수 : "+ jobCount +" ■■■■■"); + + //소켓 생성 시간으로 정렬 + Object[] arrKey = instance.getAllRunningDocuments().keySet().toArray(); + for (int i=0; i al1 = SchedulerMessageManager.getInstance().getProcessinbgJobList(); + HashMap hm = BatchRunningJobManager.getInstance().getAllRunningDocuments(); + ArrayList al2 = SchedulerMessageManager.getInstance().getProcessinbgJobList(); + for (int inx = 0; inx < al2.size(); inx++) { + String uuid = al2.get(inx).getBjobDmndMsgID(); + BatchDoc doc = hm.get(uuid); + if ( doc == null ){ + for (int jnx = 0; jnx < al1.size(); jnx++) { + if ( al1.get(jnx).getBjobDmndMsgID().equals(uuid) ){ + String message = "[RunningJobChecker]비정상적인 Processing Data 발견--->\n" + al2.get(inx); + logger.warn( message ); + try { + UCMsgSenderUtil.sendUCMsg( message ); + } catch (Exception e) { + } + } + } + } + } + logger.debug( "[RunningJobChecker]비정상적인 Processing Data 검사 종료" ); + } catch (Exception e) { + logger.warn( "[RunningJobChecker]비정상적인 Processing Data 검사 중 ..." + e.getMessage(), e); + } + } +} diff --git a/src/com/eactive/eai/batch/running/management/RunningJobMonitor.java b/src/com/eactive/eai/batch/running/management/RunningJobMonitor.java new file mode 100644 index 0000000..6f7636f --- /dev/null +++ b/src/com/eactive/eai/batch/running/management/RunningJobMonitor.java @@ -0,0 +1,205 @@ +package com.eactive.eai.batch.running.management; + +import java.util.Timer; + + +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.property.PropManager; +import com.eactive.eai.common.util.Logger; + +public class RunningJobMonitor implements Lifecycle{ + + /** + * EAI FRAMEWORK DEFAULT FILE LOGGER + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + /** + * EAIServiceMonitor의 Singleton object + */ + private static RunningJobMonitor instance = new RunningJobMonitor(); + + /** + * EAIServiceMonitor의 Lifecycle Event 처리를 위한 LifecycleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * EAIServiceMonitor에서 사용하는 Poprties Group의 Key + */ + public static final String PROP_GROUP = "RunningJobMonitor"; + + /** + * EAIServiceMonitor에서 사용하는 Property Key : MonitorChecker의 동작 주기 + */ + public static final String PROP_PERIOD = "monitor.checker.period"; + + /** + * 일일, 최근시간별 데이터 저장을 위해 주기적으로 실행 Monitor check를 하는 TimerTask object + */ + private RunningJobChecker checker; + + /** + * MonitorChecker를 실제 실행하는 Timer object - add 20080618 by kscheon + */ + private Timer timer; + + + /** + * EAIServiceMonitor starting 여부를 체크하는 flag 변수 + */ + private boolean started; + + + + /** + * 1. 기능 : Default 생성자 + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + private RunningJobMonitor() { + + } + + /** + * 1. 기능 : EAIServiceMonitor Singleton object를 반환하는 메서드 + * 2. 처리 개요 : + * - EAIServiceMonitor Singleton object의 reference 반환 + * 3. 주의사항 + * + *@return EAIServiceMonitor Singleton object + **/ + public static RunningJobMonitor getInstance() { + if(instance==null) { + synchronized(RunningJobMonitor.class) { + if(instance==null) { + instance = new RunningJobMonitor(); + } + } + } + + return instance; + } + + + /** + * 1. 기능 : EAIServiceMonitor의 초기화 작업을 실행하는 메서드 + * 2. 처리 개요 : + * - MonitorChecker객체를 생성해 Timer에 등록 실행한다. + * 3. 주의사항 + * + *@exception LifecycleException EAIServiceMonitor 초기화 실패 시 발생 + **/ + public void start() throws LifecycleException { + if (started) { + throw new LifecycleException("BECEAIMEH201"); + } + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + PropManager pmanager = PropManager.getInstance(); + long period = 1000*60*10; //10분은 1000*60*10 + + try { + period = Long.parseLong(pmanager.getProperty(PROP_GROUP, PROP_PERIOD)); + + } catch(Exception e) {} + + + this.checker = new RunningJobChecker(); + + this.timer = new Timer(); + this.timer.schedule(this.checker, period, period); + + + started = true; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : EAIServiceMonitor의 종료시 undo 작업을 실행하는 메서드 + * 2. 처리 개요 : + * - 초기화 작업 시 생성한 MonitorChecker객체를 종료한다. + * 3. 주의사항 + * + *@exception LifecycleException EAIServiceMonitor undo 작업 실패 시 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if(!started){ + throw new LifecycleException("BECEAIMEH203"); + } else { + lifecycle.fireLifecycleEvent("stoping", this); + + started = false; + this.timer.cancel(); + this.timer = null; + this.checker = null; + + lifecycle.fireLifecycleEvent("stopped", this); + + return; + } + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : + * - LifecycleListener를 등록한다. + * 3. 주의사항 + * + *@param listener Lifecycle Evnet를 받을 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 반환하는 메서드 + * 2. 처리 개요 : + * - 등록된 LifecycleListener를 반환한다. + * 3. 주의사항 + * + *@return 등록된 LifecycleListner들 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 중 특정 LifecyleListener를 삭제하는 메서드 + * 2. 처리 개요 : + * - 등록된 특정 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + *@param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : EAIServiceMonitor의 start 여부를 반환하는 getter method + * 2. 처리 개요 : + * - EAIServiceMonitor의 start 여부를 반환한다. + * 3. 주의사항 + * + *@return EAIServiceMonitor의 start 여부 + **/ + public boolean isStarted() { + return this.started; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/scheduler/JobFileTransferVO.java b/src/com/eactive/eai/batch/scheduler/JobFileTransferVO.java new file mode 100644 index 0000000..e10d000 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/JobFileTransferVO.java @@ -0,0 +1,165 @@ +package com.eactive.eai.batch.scheduler; + +import java.io.Serializable; + +public class JobFileTransferVO implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + private String subUuid = ""; + private String bjobMsgScheID = ""; + private String bjobBzwkDstcd = ""; + private String bjobBzwkName = ""; + private String osidInstiDstcd = ""; + private String osidInstiName = ""; + private String bjobTranDstcdName = ""; + private String bjobMsgDstcd = ""; + private String sendRecvYn = ""; + private String sndrcvCyclTypName = ""; + private String uapplCd = ""; + private String thisMsgChrgIDs = ""; + private String sndrcvStartHMS = ""; + private String sndrcvEndHMS = ""; + private String filePath = ""; + private String fileName = ""; + private String hdrInfoName = ""; + private String renamedFileName = ""; + + private String uuid = ""; + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getSubUuid() { + return subUuid; + } + public void setSubUuid(String subUuid) { + this.subUuid = subUuid; + } + public String getRenamedFileName() { + return renamedFileName; + } + public void setRenamedFileName(String renamedFileName) { + this.renamedFileName = renamedFileName; + } + public String getFilePath() { + return filePath; + } + public void setFilePath(String filePath) { + this.filePath = filePath; + } + public String getFileName() { + return fileName; + } + public void setFileName(String fileName) { + this.fileName = fileName; + } + public String getHdrInfoName() { + return hdrInfoName; + } + public void setHdrInfoName(String hdrInfoName) { + this.hdrInfoName = hdrInfoName; + } + public String getBjobBzwkDstcd() { + return bjobBzwkDstcd; + } + public void setBjobBzwkDstcd(String bjobBzwkDstcd) { + this.bjobBzwkDstcd = bjobBzwkDstcd; + } + public String getBjobMsgDstcd() { + return bjobMsgDstcd; + } + public void setBjobMsgDstcd(String bjobMsgDstcd) { + this.bjobMsgDstcd = bjobMsgDstcd; + } + public String getBjobMsgScheID() { + return bjobMsgScheID; + } + public void setBjobMsgScheID(String bjobMsgScheID) { + this.bjobMsgScheID = bjobMsgScheID; + } + public String getBjobTranDstcdName() { + return bjobTranDstcdName; + } + public void setBjobTranDstcdName(String bjobTranDstcdName) { + this.bjobTranDstcdName = bjobTranDstcdName; + } + public String getOsidInstiDstcd() { + return osidInstiDstcd; + } + public void setOsidInstiDstcd(String osidInstiDstcd) { + this.osidInstiDstcd = osidInstiDstcd; + } + public String getSendRecvYn() { + return sendRecvYn; + } + public void setSendRecvYn(String sendRecvYn) { + this.sendRecvYn = sendRecvYn; + } + public String getSndrcvCyclTypName() { + return sndrcvCyclTypName; + } + public void setSndrcvCyclTypName(String sndrcvCyclTypName) { + this.sndrcvCyclTypName = sndrcvCyclTypName; + } + public String getSndrcvEndHMS() { + return sndrcvEndHMS; + } + public void setSndrcvEndHMS(String sndrcvEndHMS) { + this.sndrcvEndHMS = sndrcvEndHMS; + } + public String getSndrcvStartHMS() { + return sndrcvStartHMS; + } + public void setSndrcvStartHMS(String sndrcvStartHMS) { + this.sndrcvStartHMS = sndrcvStartHMS; + } + public String getUapplCd() { + return uapplCd; + } + public void setUapplCd(String uapplCd) { + this.uapplCd = uapplCd; + } + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("bjobMsgScheID = [" + bjobMsgScheID + "]\n"); + sb.append("bjobBzwkDstcd = [" + bjobBzwkDstcd + "]\n"); + sb.append("bjobBzwkName = [" + bjobBzwkName + "]\n"); + sb.append("osidInstiDstcd = [" + osidInstiDstcd + "]\n"); + sb.append("osidInstiName = [" + osidInstiName + "]\n"); + sb.append("bjobTranDstcdName = [" + bjobTranDstcdName + "]\n"); + sb.append("bjobMsgDstcd = [" + bjobMsgDstcd + "]\n"); + sb.append("sendRecvYn = [" + sendRecvYn + "]\n"); + sb.append("sndrcvCyclTypName = [" + sndrcvCyclTypName + "]\n"); + sb.append("uapplCd = [" + uapplCd + "]\n"); + sb.append("ThisMsgChrgIDs = [" + thisMsgChrgIDs + "]\n"); + sb.append("sndrcvStartHMS = [" + sndrcvStartHMS + "]\n"); + sb.append("sndrcvEndHMS = [" + sndrcvEndHMS + "]\n"); + return new String(sb); + + } + public String getBjobBzwkName() { + return bjobBzwkName; + } + public void setBjobBzwkName(String bjobBzwkName) { + this.bjobBzwkName = bjobBzwkName; + } + public String getOsidInstiName() { + return osidInstiName; + } + public void setOsidInstiName(String osidInstiName) { + this.osidInstiName = osidInstiName; + } + public String getThisMsgChrgIDs() { + return thisMsgChrgIDs; + } + public void setThisMsgChrgIDs(String thisMsgChrgIDs) { + this.thisMsgChrgIDs = thisMsgChrgIDs; + } + + +} + \ No newline at end of file diff --git a/src/com/eactive/eai/batch/scheduler/JobMasterLogVO.java b/src/com/eactive/eai/batch/scheduler/JobMasterLogVO.java new file mode 100644 index 0000000..a28fa1f --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/JobMasterLogVO.java @@ -0,0 +1,91 @@ +package com.eactive.eai.batch.scheduler; + +import java.io.Serializable; + +public class JobMasterLogVO implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + private int totalCount = 0; + private String uuid = ""; // 작업요청메시지ID (UUID) + private String subUuid = ""; // 작업요청부메시지ID (subUUID) + private int retryCount = 0; // 재시도회수 + private String scheduleCode = ""; // 스케쥴코드 + private String msgCreateTime = ""; // 메시지생성시간 + private String processCode = ""; // 업무구분코드 + private String processName = ""; // 업무구분명 + private String organCode = ""; // 대외기관코드 + private String organName = ""; // 대외기관명 + private String processType = ""; // 작업유형구분코드 + private String msgSenderId = ""; // 메시지송신자ID + private String msgSenderName = ""; // 메시지송신자명 + private String systemConnCode = ""; // 시스템연결구분코드 + private String remoteServerIp = ""; // 시스템연결IP + private String ruleCode = ""; // 수신처리규칙코드 + private String weblogicName = ""; // 웹로직서버명 + private String startTime = ""; // 거래시작시간 + private String endTime = ""; // 거래종료시간 + private String status = ""; // 거래처리결과코드 + private String errMsg = ""; // 장애발생원인 + private String errHandleMsg = ""; // 처리내용 + private String errHandleId = ""; // 처리자ID + private String errHandleTime = ""; // 처리시간 +// private ArrayList jobFileLogList = new ArrayList(); // 파일로그VO 리스트 +// private ArrayList jobStageLogList = new ArrayList(); // 단계로그VO 리스트 + + public void setTotalCount (int arg) { totalCount = arg; } + public void setUuid (String arg) { uuid = arg; } + public void setSubUuid (String arg) { subUuid = arg; } + public void setRetryCount (int arg) { retryCount = arg; } + public void setScheduleCode (String arg) { scheduleCode = arg; } + public void setMsgCreateTime (String arg) { msgCreateTime = arg; } + public void setProcessCode (String arg) { processCode = arg; } + public void setProcessName (String arg) { processName = arg; } + public void setOrganCode (String arg) { organCode = arg; } + public void setOrganName (String arg) { organName = arg; } + public void setProcessType (String arg) { processType = arg; } + public void setMsgSenderId (String arg) { msgSenderId = arg; } + public void setMsgSenderName (String arg) { msgSenderName = arg; } + public void setSystemConnCode (String arg) { systemConnCode = arg; } + public void setRemoteServerIp (String arg) { remoteServerIp = arg; } + public void setRuleCode (String arg) { ruleCode = arg; } + public void setWeblogicName (String arg) { weblogicName = arg; } + public void setStartTime (String arg) { startTime = arg; } + public void setEndTime (String arg) { endTime = arg; } + public void setStatus (String arg) { status = arg; } + public void setErrMsg (String arg) { errMsg = arg; } + public void setErrHandleMsg (String arg) { errHandleMsg = arg; } + public void setErrHandleId (String arg) { errHandleId = arg; } + public void setErrHandleTime (String arg) { errHandleTime = arg; } +// public void setJobFileLogList (ArrayList arg) { jobFileLogList = arg; } +// public void setJobStageLogList (ArrayList arg) { jobStageLogList = arg; } + + public int getTotalCount () { return totalCount ; } + public String getUuid () { return uuid ; } + public String getSubUuid () { return subUuid ; } + public int getRetryCount () { return retryCount ; } + public String getScheduleCode () { return scheduleCode ; } + public String getMsgCreateTime () { return msgCreateTime ; } + public String getProcessCode () { return processCode ; } + public String getProcessName () { return processName ; } + public String getOrganCode () { return organCode ; } + public String getOrganName () { return organName ; } + public String getProcessType () { return processType ; } + public String getMsgSenderId () { return msgSenderId ; } + public String getMsgSenderName () { return msgSenderName ; } + public String getSystemConnCode () { return systemConnCode; } + public String getRemoteServerIp () { return remoteServerIp; } + public String getRuleCode () { return ruleCode ; } + public String getWeblogicName () { return weblogicName ; } + public String getStartTime () { return startTime ; } + public String getEndTime () { return endTime ; } + public String getStatus () { return status ; } + public String getErrMsg () { return errMsg ; } + public String getErrHandleMsg () { return errHandleMsg ; } + public String getErrHandleId () { return errHandleId ; } + public String getErrHandleTime () { return errHandleTime ; } +// public ArrayList getJobFileLogList () { return jobFileLogList ; } +// public ArrayList getJobStageLogList () { return jobStageLogList; } + +} diff --git a/src/com/eactive/eai/batch/scheduler/JobProcessingVO.java b/src/com/eactive/eai/batch/scheduler/JobProcessingVO.java new file mode 100644 index 0000000..4f087e2 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/JobProcessingVO.java @@ -0,0 +1,160 @@ +package com.eactive.eai.batch.scheduler; + +import java.io.Serializable; + +public class JobProcessingVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private String bjobDmndMsgID; + private String bjobDmndSubMsgID; + private int telgmReTralCnt; + private String sysLnkgDstcd; + private String bjobDmndMsgCretnHMS; + private String bjobMsgScheID; + private String bjobBzwkDstcd; + private String osidInstiDstcd; + private String bjobPtrnDstcd; + private String sndrcvStartHMS; + private String sndrcvEndHMS; + private String sndrcvFileDirName; + private String sndrcvFileName; + private String bkupSndrcvFileName; + private int msgPrcssPrity; + private String thisMsgAmndrID; + private String thisMsgAmndHMS; + private String msgQueEtractDmndHMS; + private String msgPrcssStusCd; + public String getBjobDmndMsgID() { + return bjobDmndMsgID; + } + public void setBjobDmndMsgID(String bjobDmndMsgID) { + this.bjobDmndMsgID = bjobDmndMsgID; + } + public String getBjobDmndSubMsgID() { + return bjobDmndSubMsgID; + } + public void setBjobDmndSubMsgID(String bjobDmndSubMsgID) { + this.bjobDmndSubMsgID = bjobDmndSubMsgID; + } + public int getTelgmReTralCnt() { + return telgmReTralCnt; + } + public void setTelgmReTralCnt(int telgmReTralCnt) { + this.telgmReTralCnt = telgmReTralCnt; + } + public String getSysLnkgDstcd() { + return sysLnkgDstcd; + } + public void setSysLnkgDstcd(String sysLnkgDstcd) { + this.sysLnkgDstcd = sysLnkgDstcd; + } + public String getBjobDmndMsgCretnHMS() { + return bjobDmndMsgCretnHMS; + } + public void setBjobDmndMsgCretnHMS(String bjobDmndMsgCretnHMS) { + this.bjobDmndMsgCretnHMS = bjobDmndMsgCretnHMS; + } + public String getBjobMsgScheID() { + return bjobMsgScheID; + } + public void setBjobMsgScheID(String bjobMsgScheID) { + this.bjobMsgScheID = bjobMsgScheID; + } + public String getBjobBzwkDstcd() { + return bjobBzwkDstcd; + } + public void setBjobBzwkDstcd(String bjobBzwkDstcd) { + this.bjobBzwkDstcd = bjobBzwkDstcd; + } + public String getOsidInstiDstcd() { + return osidInstiDstcd; + } + public void setOsidInstiDstcd(String osidInstiDstcd) { + this.osidInstiDstcd = osidInstiDstcd; + } + public String getBjobPtrnDstcd() { + return bjobPtrnDstcd; + } + public void setBjobPtrnDstcd(String bjobPtrnDstcd) { + this.bjobPtrnDstcd = bjobPtrnDstcd; + } + public String getSndrcvStartHMS() { + return sndrcvStartHMS; + } + public void setSndrcvStartHMS(String sndrcvStartHMS) { + this.sndrcvStartHMS = sndrcvStartHMS; + } + public String getSndrcvEndHMS() { + return sndrcvEndHMS; + } + public void setSndrcvEndHMS(String sndrcvEndHMS) { + this.sndrcvEndHMS = sndrcvEndHMS; + } + public String getSndrcvFileDirName() { + return sndrcvFileDirName; + } + public void setSndrcvFileDirName(String sndrcvFileDirName) { + this.sndrcvFileDirName = sndrcvFileDirName; + } + public String getSndrcvFileName() { + return sndrcvFileName; + } + public void setSndrcvFileName(String sndrcvFileName) { + this.sndrcvFileName = sndrcvFileName; + } + public String getBkupSndrcvFileName() { + return bkupSndrcvFileName; + } + public void setBkupSndrcvFileName(String bkupSndrcvFileName) { + this.bkupSndrcvFileName = bkupSndrcvFileName; + } + public int getMsgPrcssPrity() { + return msgPrcssPrity; + } + public void setMsgPrcssPrity(int msgPrcssPrity) { + this.msgPrcssPrity = msgPrcssPrity; + } + public String getThisMsgAmndrID() { + return thisMsgAmndrID; + } + public void setThisMsgAmndrID(String thisMsgAmndrID) { + this.thisMsgAmndrID = thisMsgAmndrID; + } + public String getThisMsgAmndHMS() { + return thisMsgAmndHMS; + } + public void setThisMsgAmndHMS(String thisMsgAmndHMS) { + this.thisMsgAmndHMS = thisMsgAmndHMS; + } + public String getMsgQueEtractDmndHMS() { + return msgQueEtractDmndHMS; + } + public void setMsgQueEtractDmndHMS(String msgQueEtractDmndHMS) { + this.msgQueEtractDmndHMS = msgQueEtractDmndHMS; + } + public String getMsgPrcssStusCd() { + return msgPrcssStusCd; + } + public void setMsgPrcssStusCd(String msgPrcssStusCd) { + this.msgPrcssStusCd = msgPrcssStusCd; + } + @Override + public String toString() { + return "JobProcessingVO [bjobDmndMsgID=" + bjobDmndMsgID + + ", bjobDmndSubMsgID=" + bjobDmndSubMsgID + + ", telgmReTralCnt=" + telgmReTralCnt + ", sysLnkgDstcd=" + + sysLnkgDstcd + ", bjobDmndMsgCretnHMS=" + bjobDmndMsgCretnHMS + + ", bjobMsgScheID=" + bjobMsgScheID + ", bjobBzwkDstcd=" + + bjobBzwkDstcd + ", osidInstiDstcd=" + osidInstiDstcd + + ", bjobPtrnDstcd=" + bjobPtrnDstcd + ", sndrcvStartHMS=" + + sndrcvStartHMS + ", sndrcvEndHMS=" + sndrcvEndHMS + + ", sndrcvFileDirName=" + sndrcvFileDirName + + ", sndrcvFileName=" + sndrcvFileName + + ", bkupSndrcvFileName=" + bkupSndrcvFileName + + ", msgPrcssPrity=" + msgPrcssPrity + ", thisMsgAmndrID=" + + thisMsgAmndrID + ", thisMsgAmndHMS=" + thisMsgAmndHMS + + ", msgQueEtractDmndHMS=" + msgQueEtractDmndHMS + + ", msgPrcssStusCd=" + msgPrcssStusCd + "]"; + } +} diff --git a/src/com/eactive/eai/batch/scheduler/JobStageLogVO.java b/src/com/eactive/eai/batch/scheduler/JobStageLogVO.java new file mode 100644 index 0000000..86d3a3b --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/JobStageLogVO.java @@ -0,0 +1,124 @@ +package com.eactive.eai.batch.scheduler; + +import java.io.Serializable; + +public class JobStageLogVO implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + private int totalCount = 0; + private String uuid = ""; // 작업요청메시지ID (UUID) + private String subUuid = ""; // 작업요청부메시지ID (subUUID) + private String layerCode = ""; // Layer코드 (FE,SC,FC) + private String subLayerCode = ""; // Layer별단계코드 (FE,SQ,SP,FC) + private String ruleCode = ""; // 룰코드 + private String ruleDesc = ""; // 룰설명 + private String phaseCode = ""; // 단계코드 + private String phaseDesc = ""; // 단계설명 + private String phaseSeq = ""; // 단계순번 + private String phaseType = ""; // 단계유형 (SEND/RECV/END/EEND) + private String flowClassName = ""; // Flow클래스명 + private String lengthTelegramId = ""; // 전문결정 TelegramID + private String lengthClassName = ""; // 전문결정 수행 클래스명 + private String lengthMsgCode = ""; // 전문결정 전문메시지코드 + private String phaseTelegramId = ""; // 단계 TelegramID + private String phaseClassName = ""; // 단계 수행 클래스명 + private String phaseMsgCode = ""; // 단계 전문메시지코드 + private String telegramTypeValue = ""; // 전문종별코드 필드값 + private String bizCodeValue = ""; // 거래구분코드 필드값 + private String controlCodeValue = ""; // 업무관리코드 필드값 + private String responseCodeValue = ""; // 응답코드 필드값 + private String nodeCount = ""; // 노드카운트 + private String jobCode = ""; // 작업메시지구분코드 + private String jobName = ""; // 작업메시지구분명 + private String bizCode = ""; // 거래구분코드 +// private String bizGroupCode = ""; // 거래구분그룹코드 +// private String bizGroupName = ""; // 거래구분그룹명 + private String filePath = ""; // 송수신디렉토리 + private String fileName = ""; // 실제파일명 + private String renamedFileName = ""; // 변경된파일명 + private String startTime = ""; // 단계시작시간 + private String endTime = ""; // 단계종료시간 + private String status = ""; // 단계처리결과코드 + private String errMsg = ""; // 장애발생원인 + private String telegramHeader = ""; // 전문헤더 + private String telegramBody = ""; // 전문바디 + + public void setTotalCount (int arg) { totalCount = arg; } + public void setUuid (String arg) { uuid = arg; } + public void setSubUuid (String arg) { subUuid = arg; } + public void setLayerCode (String arg) { layerCode = arg; } + public void setSubLayerCode (String arg) { subLayerCode = arg; } + public void setRuleCode (String arg) { ruleCode = arg; } + public void setRuleDesc (String arg) { ruleDesc = arg; } + public void setPhaseCode (String arg) { phaseCode = arg; } + public void setPhaseDesc (String arg) { phaseDesc = arg; } + public void setPhaseSeq (String arg) { phaseSeq = arg; } + public void setPhaseType (String arg) { phaseType = arg; } + public void setFlowClassName (String arg) { flowClassName = arg; } + public void setLengthTelegramId (String arg) { lengthTelegramId = arg; } + public void setLengthClassName (String arg) { lengthClassName = arg; } + public void setLengthMsgCode (String arg) { lengthMsgCode = arg; } + public void setPhaseTelegramId (String arg) { phaseTelegramId = arg; } + public void setPhaseClassName (String arg) { phaseClassName = arg; } + public void setPhaseMsgCode (String arg) { phaseMsgCode = arg; } + public void setTelegramTypeValue (String arg) { telegramTypeValue = arg; } + public void setBizCodeValue (String arg) { bizCodeValue = arg; } + public void setControlCodeValue (String arg) { controlCodeValue = arg; } + public void setResponseCodeValue (String arg) { responseCodeValue = arg; } + public void setNodeCount (String arg) { nodeCount = arg; } + public void setJobCode (String arg) { jobCode = arg; } + public void setJobName (String arg) { jobName = arg; } + public void setBizCode (String arg) { bizCode = arg; } +// public void setBizGroupCode (String arg) { bizGroupCode = arg; } +// public void setBizGroupName (String arg) { bizGroupName = arg; } + public void setFilePath (String arg) { filePath = arg; } + public void setFileName (String arg) { fileName = arg; } + public void setRenamedFileName (String arg) { renamedFileName = arg; } + public void setStartTime (String arg) { startTime = arg; } + public void setEndTime (String arg) { endTime = arg; } + public void setStatus (String arg) { status = arg; } + public void setErrMsg (String arg) { errMsg = arg; } + public void setTelegramHeader (String arg) { telegramHeader = arg; } + public void setTelegramBody (String arg) { telegramBody = arg; } + + public int getTotalCount () { return totalCount ; } + public String getUuid () { return uuid ; } + public String getSubUuid () { return subUuid ; } + public String getLayerCode () { return layerCode ; } + public String getSubLayerCode () { return subLayerCode ; } + public String getRuleCode () { return ruleCode ; } + public String getRuleDesc () { return ruleDesc ; } + public String getPhaseCode () { return phaseCode ; } + public String getPhaseDesc () { return phaseDesc ; } + public String getPhaseSeq () { return phaseSeq ; } + public String getPhaseType () { return phaseType ; } + public String getFlowClassName () { return flowClassName ; } + public String getLengthTelegramId () { return lengthTelegramId ; } + public String getLengthClassName () { return lengthClassName ; } + public String getLengthMsgCode () { return lengthMsgCode ; } + public String getPhaseTelegramId () { return phaseTelegramId ; } + public String getPhaseClassName () { return phaseClassName ; } + public String getPhaseMsgCode () { return phaseMsgCode ; } + public String getTelegramTypeValue () { return telegramTypeValue; } + public String getBizCodeValue () { return bizCodeValue ; } + public String getControlCodeValue () { return controlCodeValue ; } + public String getResponseCodeValue () { return responseCodeValue; } + public String getNodeCount () { return nodeCount ; } + public String getJobCode () { return jobCode ; } + public String getJobName () { return jobName ; } + public String getBizCode () { return bizCode ; } +// public String getBizGroupCode () { return bizGroupCode ; } +// public String getBizGroupName () { return bizGroupName ; } + public String getFilePath () { return filePath ; } + public String getFileName () { return fileName ; } + public String getRenamedFileName () { return renamedFileName ; } + public String getStartTime () { return startTime ; } + public String getEndTime () { return endTime ; } + public String getStatus () { return status ; } + public String getErrMsg () { return errMsg ; } + public String getTelegramHeader () { return telegramHeader ; } + public String getTelegramBody () { return telegramBody ; } + +} diff --git a/src/com/eactive/eai/batch/scheduler/ScheduleBasisManager.java b/src/com/eactive/eai/batch/scheduler/ScheduleBasisManager.java new file mode 100644 index 0000000..ae239aa --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/ScheduleBasisManager.java @@ -0,0 +1,255 @@ +package com.eactive.eai.batch.scheduler; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.GregorianCalendar; + +import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager; +import com.eactive.eai.common.util.Logger; + +public class ScheduleBasisManager { + + + //singleton 객체 생성 + private static ScheduleBasisManager instance = new ScheduleBasisManager(); + //singleton 객체 리턴 + public static ScheduleBasisManager getInstance() { + return instance; + } + + //생성자 (다른 클래스에서 new 불가) + private ScheduleBasisManager() {} + + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public ArrayList getIntervalTypes( String days ){ + ArrayList al = new ArrayList(); + Calendar cal = null; + int i_year, i_month, i_day; + try{ + i_year = Integer.parseInt(days.substring(0, 4)); + i_month = Integer.parseInt(days.substring(4,6)); + i_day = Integer.parseInt(days.substring(6,8)); + cal = new GregorianCalendar(i_year, i_month-1, i_day); + } catch (Exception e){ + logger.error("[ScheduleBasisManager] getIntervalTypes - createCalendar failed - "+e.getMessage()); + return al; + } + + if ( ! checkDate(days) ) + return al; + + // 1. 매일 처리하는 경우 추가 + //(D) + al.add( "D" ); + + HolidayManager hm = HolidayManager.getInstance(); + // 2. 매 영업일에 처리 하는 경우 추가 + //(Y) + boolean isHoliday = true; + if ( !hm.isAllHoliday(days) ){ + al.add( "Y" ); + isHoliday = false; + } + // 3. 매 영업 익일에 처리 하는 경우 추가 + //(Y+) + String yesterday = getDaysOfDay( cal, -1); + if ( !hm.isAllHoliday(yesterday) ) + al.add( "Y+" ); + + // 4. 매 영업일 + 순수 토요일에 처리 하는 경우 추가 + //(S) + if ( !hm.isHoliday(days) ) + al.add( "S" ); + + String sMonth = days.substring( 4,6 ); + String sDay = days.substring( 6,8 ); + + // 5. 특정 또는 매월(00) 특정일에 처리 하는 경우 + // 5-1. 휴일 포함 + al.add( "00" + sDay ); + al.add( sMonth + sDay ); + + // 특정 또는 매월(00) 특정일에 처리 하는 경우(휴일 포함) + if ( isLastDay(cal) ){ + al.add( "00-1" ); + al.add( sMonth + "-1" ); + } + + int inx = 1; + if ( !isHoliday ){ + // 5-2. 전 영업일 + // 내일부터 휴일인 동안 추가 + while( hm.isAllHoliday(getDaysOfDay( cal, inx )) ){ + String tmpDay = getDaysOfDay( cal, inx ); + //날짜를 뒤로 돌리다 보면 다음달로 넘어 가는 경우가 있어 별도의 변수를 사용한다. + String tMonth = tmpDay.substring( 4,6 ); + sDay = tmpDay.substring( 6,8 ); + al.add( "00" + sDay + "-" ); + al.add( tMonth + sDay + "-" ); + inx++; + } + // 5-3. 후 영업일 + inx = 1; + while( hm.isAllHoliday(getDaysOfDay( cal, 0 - inx )) ){ + String tmpDay = getDaysOfDay( cal, 0 - inx ); + sMonth = tmpDay.substring( 4,6 ); + sDay = tmpDay.substring( 6,8 ); + al.add( "00" + sDay + "+" ); + al.add( sMonth + sDay + "+" ); + inx++; + } + } + + // 6. 특정 또는 매월(00) n 번째 영업일 + if ( !isHoliday ){ + // 영업일 수 + int yCnt = 1; + for ( inx = 1; inx < i_day; inx++){ + if ( !hm.isAllHoliday(getDaysOfDay( cal, 0 - inx ))) + yCnt++; + } + String s_holiCnt; + if ( yCnt < 10 ){ + s_holiCnt = "0" + yCnt; + }else{ + s_holiCnt = "" + yCnt; + } + al.add( "Y00" + s_holiCnt ); + al.add( "Y" + sMonth + s_holiCnt ); + + // 마지막 영업일인지 여부 체크 - 휴일이 아닌경우에만 체크 + // 일단 마지막 영업일이라고 가정하고 + boolean isLastYday = true; + Calendar tmpCal = new GregorianCalendar(cal.get ( Calendar.YEAR ), cal.get ( Calendar.MONTH ), cal.get ( Calendar.DAY_OF_MONTH )); + tmpCal.add( Calendar.DAY_OF_MONTH, 1); + while ((i_month -1) == tmpCal.get(Calendar.MONTH)){ + if ( !hm.isAllHoliday(getDaysOfDay( tmpCal, 1)) ){ + isLastYday = false; + break; + } + tmpCal.add( Calendar.DAY_OF_MONTH, 1); + } + if ( isLastYday ){ + al.add( "Y00-1" ); + al.add( "Y" + sMonth + "-1" ); + } + } + + // 7. 특정 요일( W1 ) + + // 요일을 추출( 원래는 일요일 - 1 .. 토요일 7이지만 일괄전송에서는 일요일 0 .. 토요일 6으로 함. + // 그렇게 하는 이유는 TANDEM에서 그렇게 했었기 때문에 + int i_date = cal.get(Calendar.DAY_OF_WEEK) - 1; + al.add( "D" + ( i_date )); + + // 몇번째 주인가를 확인 + int i_week = cal.get( Calendar.WEEK_OF_MONTH ); + + int yCnt = 0; + + boolean isLastYdayOfWeek = false; + // 오늘이 영업일이면 이번주의 몇 번째 영업일인지를 찾아 낸다. + if ( !isHoliday ){ + for ( inx=i_date -1; inx>=0; inx-- ){ + if ( !hm.isAllHoliday(getDaysOfDay( cal, 0 - inx)) ){ + yCnt++; + } + } + // 이번주의 마지막 영업일인지 여부 체크 - 휴일이 아닌경우에만 체크 + // 일단 마지막 영업일이라고 가정하고 + isLastYdayOfWeek = true; + Calendar tmpCal = new GregorianCalendar(cal.get ( Calendar.YEAR ), cal.get ( Calendar.MONTH ), cal.get ( Calendar.DAY_OF_MONTH )); + // 금요일까지만 체크 + while (tmpCal.get(Calendar.DAY_OF_WEEK) < 7 ){ + if ( !hm.isAllHoliday(getDaysOfDay( tmpCal, 1)) ){ + isLastYdayOfWeek = false; + break; + } + tmpCal.add( Calendar.DAY_OF_MONTH, 1); + } + + } + // 8. 매주 n번째 영업일 + if ( yCnt > 0 ){ + al.add( "DY" + yCnt ); + } + // 9. n 주 특정 요일 + al.add( "W" + i_week + "D" + i_date ); + + // 10. n 주 m 번째 영업일 + if ( yCnt > 0 ){ + al.add( "W" + i_week + "Y" + yCnt ); + } + // + if ( isLastYdayOfWeek ){ + al.add( "DY-1" ); + al.add( "W" + i_week + "Y-1" ); + } + Collections.sort( al ); + + return al; + } + + private String getDaysOfDay( Calendar cal, int days ) + { + StringBuffer sbDate = new StringBuffer ( ); + Calendar tmpCal = new GregorianCalendar(cal.get ( Calendar.YEAR ), cal.get ( Calendar.MONTH ), cal.get ( Calendar.DAY_OF_MONTH )); + tmpCal.add ( Calendar.DAY_OF_MONTH, days ); + int nYear = tmpCal.get ( Calendar.YEAR ); + int nMonth = tmpCal.get ( Calendar.MONTH ) + 1; + int nDay = tmpCal.get ( Calendar.DAY_OF_MONTH ); + + sbDate.append ( nYear ); + if ( nMonth < 10 ) + sbDate.append ( "0" ); + sbDate.append ( nMonth ); + if ( nDay < 10 ) + sbDate.append ( "0" ); + sbDate.append ( nDay ); + + return sbDate.toString ( ); + } + + private boolean isLastDay( Calendar cal ){ + Calendar tmpCal = new GregorianCalendar(cal.get ( Calendar.YEAR ), cal.get ( Calendar.MONTH ), cal.get ( Calendar.DAY_OF_MONTH )); + tmpCal.add ( Calendar.DAY_OF_MONTH, 1 ); + return ( cal.get ( Calendar.MONTH ) != tmpCal.get ( Calendar.MONTH ) ); + } + + private boolean checkDate(String sDate) { + int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + if ( sDate.length() != 8 ) + return false; + try { + int year = new Integer(sDate.substring(0, 4)).intValue(); + int month = new Integer(sDate.substring(4, 6)).intValue(); + int day = new Integer(sDate.substring(6, 8)).intValue(); + + + if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { + days[2] = 29; + } // end of if + else { + days[2] = 28; + } // end of else + + if(month < 1 || month > 12) { + return false; + } + + if(day < 1 || day > days[month]) { + return false; + } + } + catch(Exception e) { + return false; + } + + return true; + } + + +} diff --git a/src/com/eactive/eai/batch/scheduler/ScheduleHandlerProcess.java b/src/com/eactive/eai/batch/scheduler/ScheduleHandlerProcess.java new file mode 100644 index 0000000..210d4e7 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/ScheduleHandlerProcess.java @@ -0,0 +1,176 @@ +package com.eactive.eai.batch.scheduler; + +import java.util.ArrayList; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager; +import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.dao.Keys; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.routing.JMSQueueSender; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.JMSSender; + +public class ScheduleHandlerProcess{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public BatchDoc clientRequestwithReturn( + BatchDoc batchDoc) throws Exception { + return null; + } + + public void clientRequest() throws Exception { + try { + logger.debug("[스케쥴 핸들러] ■■■■■ 진행중인 일괄전송 작업 건수 : " + BatchRunningJobManager.getInstance().getRunningJobCount() +" ■■■■■"); + logger.info("[스케쥴 핸들러] ============================================================================================"); + logger.info("[스케쥴 핸들러] ■ Job_Queue 테이블에서 진행할 Job을 Job_Processing 테이블로 이동..."); + + //Job_Queue 테이블 에서 현재시간에 걸리는 수행 할 작업을 Job_Processing 테이블로 이동 + //망관리에 의하여 해당 망이 사용중인 작업은 걸러짐 + ArrayList executeJobList = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(); + logger.info("[스케쥴 핸들러] ※ 요구송수신 진행 작업 건수: "+ ((executeJobList == null)? 0 : executeJobList.size() )); + logger.info("[스케쥴 핸들러] ============================================================================================"); + for (SchedulerMessageVO info : executeJobList) { + try{ + BatchDoc batchDoc = moveJobToProcessing(info); + String instName = System.getProperty(Keys.SERVER_KEY); + String jobQueue = instName.equals("fepBapSvr11") ? Keys.BAP01_JOB_QUEUE : Keys.BAP02_JOB_QUEUE; + JMSSender.sendToQueue(batchDoc, Keys.CONNECT_FACTORY, jobQueue); + //JMSQueueSender sender = new JMSQueueSender(); + // logger.debug("[ScheduleHandlerProcess][clientRequest]batchDoc-->" + batchDoc.getBatchMsg().getHeader().getUUID()); + // sender.sendObject(Keys.CONNECT_FACTORY, Keys.JOB_QUEUE, batchDoc, batchDoc.getBatchMsg().getHeader().getUUID()); + loggingToDB(batchDoc); + } catch (Exception e){ + catchException(e); + } + } + + } catch (Exception e) { + catchException(e); + } + + } + + private BatchDoc moveJobToProcessing(SchedulerMessageVO info) throws Exception + { + //해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동 + SchedulerMessageManager.getInstance().moveJobQueueToHandle(info); + //<------------ 에러시 예외처리 후 다음 작업 수행 + logger.debug("UUID추적:[ScheduleHandlerProcess]:uuid["+info.getUUID() +"]"); + logger.debug("UUID추적:[ScheduleHandlerProcess]:subuuid["+info.getSubUUID() +"]"); + + //BatchMsgDoc 생성 + BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsg(true); //true:초기화함 + + //BatchMsgDoc Layer, SubLayer, StartTime 설정 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING); + + //BatchMsgDoc 값 설정 + batchMsgDoc.getBatchMsg().getHeader().setUUID(info.getUUID()); + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode()); + batchMsgDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName()); + batchMsgDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchMsgDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath()); + batchMsgDoc.getBatchMsg().getHeader().setFileName(info.getFileName()); + batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName()); + batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName()); + batchMsgDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchMsgDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + batchMsgDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName()); +// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(info.getInstitutionType()); + batchMsgDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize()); + batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize()); + batchMsgDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize()); + batchMsgDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID()); + batchMsgDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW()); + batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(info.getRempoteIP()); + batchMsgDoc.getBatchMsg().getHeader().setPort(info.getRemotePort()); + batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode()); +// batchMsgDoc.getEAIBatchMessage().getHeader().setProtocol("TCP/IP"); +// batchMsgDoc.getBatchMsg().getHeader().setProtocol(info.getProtocol()); + + // 레코드 크기 추가 2009.02.03 + String jobCode = batchMsgDoc.getBatchMsg().getHeader().getJobCode(); + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode ); + batchMsgDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize()); + + // 20120601 추가 -- 시작 + if ( info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) || + info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND ) ){ + String hdrInfoName = info.getHdrInfoName(); + batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName); + batchMsgDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName)); + batchMsgDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName)); + batchMsgDoc.getBatchMsg().getHeader().setFileSize(batchMsgDoc.getBatchMsg().getHeader().getRecLen() * batchMsgDoc.getBatchMsg().getHeader().getTotRecCnt()); + } + // 20120601 추가 -- 여기까지 + + RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(info.getFlowRuleCode()); + batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo != null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02"); + + batchMsgDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID()); + + //재처리 플래그 설정.. + if (info.getRecvRetryFlag().equals("1")){ + batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(true); + logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 true로 설정합니다." ); + + }else { + batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(false); + logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 false로 설정합니다." ); + } + + logger.info("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName()); + return batchMsgDoc; + } + + private void loggingToDB(BatchDoc batchMsgDoc) throws Exception + { + //요구송수신에 대한 스케쥴핸들러 단계 DB로그 생성 + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLog(batchMsgDoc); + + //요구송수신 작업 시작정보를 Master 로그에 Update. + LogUtil.updateLogMaster(batchMsgDoc); + } + + /* 예외 처리 */ + private void catchException(Exception ex) + { + //Exception ex = this.context.getExceptionInfo().getException(); + logger.error("[스케쥴 핸들러] ★★★★★ 예외 발생 !! ★★★★★", ex); + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC018"); + logger.error(errMsg, ex); //Scheduler Handle Processor JPD 에서 에서 오류가 발생하였습니다. + + // DB로그 처리 + //batchMsgDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); + //batchMsgDoc.getEAIBatchMessage().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash16()); + //LogUtil.setErrorLog(batchMsgDoc, errMsg); + + } catch (Exception e) { + logger.error("[스케쥴 핸들러] ★★★★★ 스케쥴 핸들러 예외 처리 중 에러 !! ★★★★★", e); + } + } + +} diff --git a/src/com/eactive/eai/batch/scheduler/ScheduleRecvProcess.java b/src/com/eactive/eai/batch/scheduler/ScheduleRecvProcess.java new file mode 100644 index 0000000..c527c57 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/ScheduleRecvProcess.java @@ -0,0 +1,172 @@ +package com.eactive.eai.batch.scheduler; + +import java.util.ArrayList; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.flowController.BatchTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class ScheduleRecvProcess{ + + //파일로거 + private static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public BatchDoc clientRequestwithReturn( + BatchDoc batchDoc) throws Exception { + return null; + } + + public void clientRequest() throws Exception { + try { + logger.info("[요구수신 스케쥴러] ============================================================================================"); + logger.info("[요구수신 스케쥴러] ■ Schedule 테이블에서 현재시간에 진행할 요구수신 스케쥴 정보를 조회......"); + + //Schedule 테이블 에서 현재시간에 걸리는 요구수신 작업을 조회 + //대기 및 진행목록에 존재하거나 재시도 회수가 초과된 작업은 걸러짐 + ArrayList executeJobList = SchedulerMessageManager.getInstance().getExecutableRecvScheduleList(); + logger.info("[요구수신 스케쥴러] ※ 요구수신 진행 작업 건수: "+ ((executeJobList == null)? 0 : executeJobList.size())); + logger.info("[요구수신 스케쥴러] ============================================================================================"); + + for (SchedulerMessageVO info : executeJobList) { + BatchDoc batchDoc = regJobQueue(info); + loggingToDB(batchDoc); + } + + + } catch (Exception e) { + catchException(e); + } + + } + + private BatchDoc regJobQueue(SchedulerMessageVO info) throws Exception + { + //1. 요구수신 스케쥴러 단계 DB로그를 위한 BatchMsg 객체 생성 + BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(false); //UUID 생성, false:초기화안함 + try { + + logger.info("[요구수신 스케쥴러] ========================================================================="); + logger.info("[요구수신 스케쥴러] ■ 요구수신 스케쥴 정보."); + logger.info("[요구수신 스케쥴러] - 스케쥴코드 : " + info.getScheduleCode()); + logger.info("[요구수신 스케쥴러] - 시작시간(시분): " + info.getStartTime()); + logger.info("[요구수신 스케쥴러] - 종료시간(시분): " + info.getEndTime()); + logger.info("[요구수신 스케쥴러] ========================================================================="); + + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); // layer, flowPahse, 시작시간 설정 + + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode()); + batchMsgDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType()); + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode()); + batchMsgDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode()); + batchMsgDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime()); + batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime()); + batchMsgDoc.getBatchMsg().getBody().setRetryCount(info.getRecvFailCnt()); //요구수신 재시도회수 + + //2. 요구수신 디렉토리 설정 (수신_Real/업무구분/대외기관/..) + //요구수신 기준 디렉토리 --> 배치업무유형코드(ProcessCode) 와 대외기관코드 (InstitutionCode) 로 계산. + String strPathName = BatchDirUtil.getResponseRealDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + + //해당 업무구분코드의 대외가관 목록 조회 + ArrayList osd_array = OutsideManager.getInstance().getOutsideInfo(info.getProcessCode()); + logger.debug("배치유형코드 [" + info.getInstitutionCode() + "] 대외기관 코드 개수 ["+ osd_array.size() + "]"); + int i=0; + for (i=0; i 배치 Job_Queue 테이블 INSERT 건수: "+ resultCnt); + logger.info("[요구수신 스케쥴러] ========================================================================="); + + //logger.debug("========================================================================="); + //logger.debug("[요구수신 스케쥴러] 생성된 EAIBatchMsgDoc 디버깅용 Printing......\n"+ batchMsgDoc); + //logger.debug("========================================================================="); + return batchMsgDoc; + + }catch(Exception e){ + logger.error("[요구수신 스케쥴러 큐] ★★★★★ 큐 스케쥴러 예외 처리 중 에러 !! ★★★★★", e); + return batchMsgDoc; + } + } + + private void loggingToDB(BatchDoc batchMsgDoc) throws Exception + { + //요구수신에 대한 최초 DB로그. StartLog 호출. + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setStartLog(batchMsgDoc); + } + + private void catchException(Exception ex) + { + logger.error("[요구수신 스케쥴러] ★★★★★ 예외 발생 !! ★★★★★", ex); + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC027"); + logger.error(errMsg, ex); //요구수신 Scheduler JPD 에서 에서 오류가 발생하였습니다. + + // DB로그 처리 + //batchMsgDoc.getEAIBatchMessage().getBody().setErrorMsg(errMsg); + //batchMsgDoc.getEAIBatchMessage().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash16()); + //LogUtil.setErrorLog(batchMsgDoc, errMsg); + + } catch (Exception e) { + logger.error("[요구수신 스케쥴러] ★★★★★ 요구수신 스케쥴러 예외 처리 중 에러 !! ★★★★★", e); + } + + } + + +} diff --git a/src/com/eactive/eai/batch/scheduler/ScheduleSendProcess.java b/src/com/eactive/eai/batch/scheduler/ScheduleSendProcess.java new file mode 100644 index 0000000..3e35bca --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/ScheduleSendProcess.java @@ -0,0 +1,165 @@ +package com.eactive.eai.batch.scheduler; + +import java.io.File; + +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class ScheduleSendProcess { + + // FileLoger + private static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + private BatchDoc batchMsgDoc; + + public void proc(BatchDoc recvDoc){ + batchMsgDoc = recvDoc; + startLog(); + try { + String hdrInfoName = batchMsgDoc.getBatchMsg().getHeader().getHdrInfoName(); + SchedulerMessageVO vo = getScheduleInfo(); + if ( vo != null ){ + vo.setHdrInfoName(hdrInfoName); + regJobQueue(vo); + } else { + discardJob(); + } + closeLog(); + } catch (Exception e) { + catchException(e); + } + } + private void startLog(){ + batchMsgDoc.getBatchMsg().getHeader().setLayerCode(CommonKeys.LAYER_SCHEDULER); + batchMsgDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); + batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(""); + } + + private SchedulerMessageVO getScheduleInfo() throws Exception + { + // 1. inputDoc에서 필요한 값들을 추출한다. + String bizCode = batchMsgDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchMsgDoc.getBatchMsg().getHeader().getProcessCode(); + String osidinstidstCode = batchMsgDoc.getBatchMsg().getHeader().getInstitutionCode(); + String renamedFileName = batchMsgDoc.getBatchMsg().getHeader().getRenamedFileName(); + String renamedDir = batchMsgDoc.getBatchMsg().getHeader().getFilePath(); + String orgFileName = batchMsgDoc.getBatchMsg().getHeader().getFileName(); + logger.info("[요구송신 스케쥴러] - UUID : " + batchMsgDoc.getBatchMsg().getHeader().getUUID()); + logger.info("[요구송신 스케쥴러] - 거래구분코드 : " + bizCode); + logger.info("[요구송신 스케쥴러] - 업무구분코드 : " + processCode); + logger.info("[요구송신 스케쥴러] - 대외기관코드 : " + osidinstidstCode); + logger.info("[요구송신 스케쥴러] - 저장된 디렉토리 : " + renamedDir); + logger.info("[요구송신 스케쥴러] - 저장된 파일명 : " + renamedFileName); + logger.info("[요구송신 스케쥴러] - 원 파일명 : " + orgFileName); + + // 2. 전달된 파일명으로 등록된 스케쥴정보를 조회 + return SchedulerMessageManager.getInstance().getScheduleInfo(bizCode, processCode, osidinstidstCode); + + } + + private void regJobQueue(SchedulerMessageVO scheduleInfo ) throws Exception + { + logger.info("[요구송신 스케쥴러] - 스케쥴코드 : " + scheduleInfo.getScheduleCode() + + "(" + scheduleInfo.getStartTime() + "~" + scheduleInfo.getEndTime()); + + // 3.BATCH작업 요청메시지ID 및 스케쥴 송수신 시각 설정 + // - 요구송신의 경우 UUID는 FileEventListener로부터 전달된다. + scheduleInfo.setUUID (batchMsgDoc.getBatchMsg().getHeader().getUUID()); + scheduleInfo.setSubUUID (batchMsgDoc.getBatchMsg().getBody().getSubUUID()); + scheduleInfo.setFilePath (batchMsgDoc.getBatchMsg().getHeader().getFilePath()); + scheduleInfo.setFileName (batchMsgDoc.getBatchMsg().getHeader().getFileName()); + scheduleInfo.setRenamedFileName(batchMsgDoc.getBatchMsg().getHeader().getRenamedFileName()); + + //int startDelay = scheduleInfo.getStartDelayDays(); + int endDelay = scheduleInfo.getEndDelayDays(); + if (!scheduleInfo.getStartTime().equals("")) scheduleInfo.setStartTime(DatetimeUtil.getCurrentDate() + scheduleInfo.getStartTime() +"00" + "000"); + // 송신 시작 지연 일수 --> 기능 삭제 + //if (!scheduleInfo.getStartTime().equals("")) scheduleInfo.setStartTime(DatetimeUtil.getDayAddedDate( DatetimeUtil.getCurrentDate(), startDelay ) + scheduleInfo.getStartTime() +"00" + "00"); + if (!scheduleInfo.getEndTime() .equals("")) scheduleInfo.setEndTime (DatetimeUtil.getDayAddedDate( DatetimeUtil.getCurrentDate(), endDelay ) + scheduleInfo.getEndTime() +"00" + "000"); + + + // 4.JOB QUEUE 테이블에 등록 + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(scheduleInfo); + logger.info("[요구송신 스케쥴러] ==> 배치 JOB QUEUE 테이블 INSERT 건수: "+ resultCnt); + + // 5. DB로그를 위해서 조회정보를 batchMsgDoc에 세팅 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(scheduleInfo.getProcessType()); //업무유형코드 + batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(scheduleInfo.getScheduleCode()); //스케쥴등록ID + batchMsgDoc.getBatchMsg().getHeader().setJobCode(scheduleInfo.getJobCode()); //Job 코드 + batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(scheduleInfo.getStartTime()); //전송 시작 시각 + batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(scheduleInfo.getEndTime()); //전송 종료 시각 + + } + + private void discardJob() throws Exception + { + /* 1.스케쥴 등록이 되어 있지 않은 파일에 대한 처리 + * - FileEvent로부터 전달된 파일 중 스케쥴이 등록되어 있지 않은 파일은 Error 디렉토리로 옮긴다. + * - 에러 디렉토리로 전송 중 발생하는 에러는 더 이상 상위로 전파하지 않고 내부 처리한다. + * - 즉, 에러 디렉토리 전송 중 에러는 전체 Flow에 영향을 미치치 않는다. + */ + String bizCode = batchMsgDoc.getBatchMsg().getHeader().getBizCode(); + String processCode = batchMsgDoc.getBatchMsg().getHeader().getProcessCode(); + String osidinstidstCode = batchMsgDoc.getBatchMsg().getHeader().getInstitutionCode(); + String renamedFileName = batchMsgDoc.getBatchMsg().getHeader().getRenamedFileName(); + try { + String archDir = batchMsgDoc.getBatchMsg().getHeader().getFilePath(); + String errorDir = batchMsgDoc.getBatchMsg().getHeader().getFileErrorPath(); + File archFile = new File(archDir +"/"+ renamedFileName); + File errorFile = new File(errorDir +"/"+ renamedFileName); + + //Arch 디렉토리에서 Error 디렉토리로 파일 이동 + logger.info("[요구송신 스케쥴러] ★ 스케쥴 미등록 파일 이동 (송신_Arch -> 송신_Error)"); + logger.info("[요구송신 스케쥴러] - Arch 디렉토리: ["+ archDir +"/"+ renamedFileName +"] (exists: "+ archFile.exists() +")"); + logger.info("[요구송신 스케쥴러] - Error 디렉토리: ["+ errorDir +"/"+ renamedFileName +"] (exists: "+ errorFile.exists() +")"); + + boolean isSuccessMoveFile = archFile.renameTo(errorFile); + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC026", new String[] {archFile.getAbsolutePath(), errorFile.getAbsolutePath()}); + throw new Exception(errMsg); //요구송신 데이터파일을 송신_Arch 디렉토리({1})에서 송신_Error 디렉토리({2})로 이동시 실패하였습니다. + } + + } catch (Exception e) { + logger.error("[요구송신 스케쥴러] ★★★★★ 스케쥴 미등록 파일 이동 중 에러 !! ★★★★★", e); + } + + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC016", new String[] {processCode, osidinstidstCode, bizCode, batchMsgDoc.getBatchMsg().getHeader().getHdrInfoName().substring(27, 37)}); + throw new Exception(errMsg); //해당 정보에 대한 스케쥴 정보가 존재하지 않습니다. (업무코드: {1}, 대외기관코드: {2}, 거래구분코드: {3}) + } + + private void closeLog() throws Exception + { + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLog(batchMsgDoc); + + //요구송신 스케쥴러에 의해 설정된 값을 Master 로그에 Update. + LogUtil.updateLogMaster(batchMsgDoc); + } + + /* 예외 처리를 위한 노드 */ + private void catchException(Exception ex) + { + logger.error("[요구송신 스케쥴러] ★★★★★ 예외 발생 !! ★★★★★", ex); + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC017"); + logger.error(errMsg, ex); //Scheduler Processor JPD 에서 에서 오류가 발생하였습니다. + + // DB로그 처리 + batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchMsgDoc, errMsg); + + } catch (Exception e) { + logger.error("[요구송신 스케쥴러] ★★★★★ 예외 처리 중 에러 !! ★★★★★", e); + } + } + +} diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageDAO.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageDAO.java new file mode 100644 index 0000000..33cc7b8 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageDAO.java @@ -0,0 +1,1279 @@ +package com.eactive.eai.batch.scheduler; + +import java.sql.ResultSet; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; + +import org.slf4j.LoggerFactory; + +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + + +/** +* 1. 기능 : Data Access Object 클래스 +* 2. 처리 개요 : 스케줄러 부분은 특성상 메모리에 로딩하지 않는다. +* * - +* 3. 주의사항 +* +* @author :송영국 +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : 2006.01.10 +*/ +public class SchedulerMessageDAO extends BaseDAO implements SchedulerMessageQuery +{ + + public SchedulerMessageDAO() { + super(); + super.logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + } + + //File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회하여 + //가장 우선순위(우선순위 > 스케줄시작시간 > 스케쥴종료시간)가 높은 스케쥴 정보 리턴 + public SchedulerMessageVO getScheduleInfo(String bizCode, String processCode, String osidinstidstCode) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + this.connect(SELECT_SEND_SCHEDULE_BY_BIZCODE); + //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 수행 SQL 문 : \n"+ SELECT_SEND_SCHEDULE_BY_BIZCODE); + + index = 1; + this.preparedStatement.setString(index++, processCode ); //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 바인드("+(index-1)+") : ["+ processCode +"]"); + this.preparedStatement.setString(index++, osidinstidstCode); //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 바인드("+(index-1)+") : ["+ osidinstidstCode +"]"); + this.preparedStatement.setString(index++, bizCode ); //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 바인드("+(index-1)+") : ["+ bizCode +"]"); + + rs = executeQuery(); + + SchedulerMessageVO info = null; + if (rs.next()) { + info = new SchedulerMessageVO(); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); // 스케쥴 아이디 + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); // Job 구분 코드 + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName"))); // 거래구분코드 + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); // 송수신 시작 시간 + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); // 송수신 종료 시간 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분 코드 + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); // 업무유형 구분 + info.setInstitutionCode(StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); // 대외기관 코드 + info.setPriority ( rs.getInt ("MsgPrcssPrity" )); // 메시지 처리 우선 순위 + info.setHolyProcessGb (StringUtil.nvlTrim(rs.getString("HoldyPrcssDstcd" ))); // 공휴일처리구분 + info.setStartDelayDays ( rs.getInt ("StartDlayNoday" )); + info.setEndDelayDays ( rs.getInt ("EndDlayNoday" )); + } + return info; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAISSC001", new String[] {processCode, osidinstidstCode, bizCode}); + throw new DAOException(errMsg); //해당 스케쥴 정보를 찾을 수 없습니다. (업무구분: %1, 대외기관: %2, 거래구분: %3) + } finally { + disconnect(); + } + } + + //File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회하여 + //가장 우선순위(우선순위 > 스케줄시작시간 > 스케쥴종료시간)가 높은 스케쥴 정보 리턴 + public SchedulerMessageVO getRecvScheduleInfo(String bizCode, String processCode, String osidinstidstCode) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + this.connect(SELECT_RECV_SCHEDULE_BY_BIZCODE); + //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 수행 SQL 문 : \n"+ SELECT_SEND_SCHEDULE_BY_BIZCODE); + + index = 1; + this.preparedStatement.setString(index++, processCode ); logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 바인드("+(index-1)+") : ["+ processCode +"]"); + this.preparedStatement.setString(index++, osidinstidstCode); logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 바인드("+(index-1)+") : ["+ osidinstidstCode +"]"); + this.preparedStatement.setString(index++, bizCode ); logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 바인드("+(index-1)+") : ["+ bizCode +"]"); + + rs = executeQuery(); + + SchedulerMessageVO info = null; + if (rs.next()) { + info = new SchedulerMessageVO(); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); // 스케쥴 아이디 + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); // Job 구분 코드 + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName"))); // 거래구분코드 + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); // 송수신 시작 시간 + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); // 송수신 종료 시간 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분 코드 + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); // 업무유형 구분 + info.setInstitutionCode(StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); // 대외기관 코드 + info.setPriority ( rs.getInt ("MsgPrcssPrity" )); // 메시지 처리 우선 순위 + info.setHolyProcessGb (StringUtil.nvlTrim(rs.getString("HoldyPrcssDstcd" ))); // 공휴일처리구분 + info.setStartDelayDays ( rs.getInt ("StartDlayNoday" )); + info.setEndDelayDays ( rs.getInt ("EndDlayNoday" )); + }else{ + info = insertNewRecvSchedule( processCode, osidinstidstCode, bizCode ); + } + return info; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAISSC001", new String[] {processCode, osidinstidstCode, bizCode}); + throw new DAOException(errMsg); //해당 스케쥴 정보를 찾을 수 없습니다. (업무구분: %1, 대외기관: %2, 거래구분: %3) + } finally { + disconnect(); + } + } + + public int insertJobToQueue(SchedulerMessageVO info) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + if ( info.getHdrInfoName() == null || info.getHdrInfoName().equals("") ) + info.setHdrInfoName(" "); +// logger.debug( "[insertJobToQueue]line1-->\n"+ info.getHdrInfoName()); +// logger.debug( "[insertJobToQueue]line2-->\n"+ StringUtil.nvlTrim(info.getHdrInfoName() , " ") ); + this.connect(INSERT_JOB_QUEUE); + //logger.debug("SchedulerMessageDAO.insertJobToQueue() >>> 수행 SQL 문 : \n"+ INSERT_JOB_QUEUE); + + index = 1; + this.preparedStatement.setString(index++, info.getUUID().trim()); + this.preparedStatement.setString(index++, info.getSubUUID().trim()); + this.preparedStatement.setInt (index++, info.getRecvFailCnt()); + this.preparedStatement.setString(index++, info.getScheduleCode().trim()); + this.preparedStatement.setString(index++, info.getProcessCode().trim()); + this.preparedStatement.setString(index++, info.getInstitutionCode().trim()); + this.preparedStatement.setString(index++, info.getProcessType().trim()); + this.preparedStatement.setString(index++, info.getStartTime().trim()); + this.preparedStatement.setString(index++, "99999999999999999"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(info.getFilePath() , " ")); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(info.getFileName() , " ")); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(info.getRenamedFileName(), " ")); + this.preparedStatement.setInt (index++, info.getPriority()); + this.preparedStatement.setString(index++, StringUtil.nvl(info.getHdrInfoName() , " ")); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(info.getCreateId() , " ")); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(info.getCreateTime() , " ")); + + retValue = this.executeUpdate(); + //logger.debug("[요구송신 스케쥴러] ==> 배치 JOB QUEUE 테이블 INSERT 건수: "+ retValue); + + if (retValue == 0) throw new DAOException("BECEAISSC019"); //배치작업 스케쥴 대기정보 insert 건 수가 0 건입니다. + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC002"); + throw new DAOException(errMsg); //배치작업 스케쥴 대기정보 등록시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + + + public ArrayList getExecutableJobList() throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(SELECT_EXECUTABLE_JOB_FROM_QUEUE); + //logger.debug("SchedulerMessageDAO.getExecutableJobList() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_EXECUTABLE_JOB_FROM_QUEUE); + + rs = executeQuery(); + + ArrayList alist = new ArrayList(); + while (rs.next()) { + SchedulerMessageVO info = new SchedulerMessageVO(); + info.setUUID (StringUtil.nvlTrim(rs.getString("BjobDmndMsgID" ))); + info.setSubUUID (StringUtil.nvlTrim(rs.getString("BjobDmndSubMsgID" ))); + info.setRecvFailCnt ( rs.getInt ("TelgmReTralCnt" )); + info.setMsgCreateTime (StringUtil.nvlTrim(rs.getString("BjobDmndMsgCretnHMS"))); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); + info.setInstitutionCode(StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); + info.setFilePath (StringUtil.nvlTrim(rs.getString("SndrcvFileDirName" ))); + info.setFileName (StringUtil.nvlTrim(rs.getString("SndrcvFileName" ))); + info.setRenamedFileName(StringUtil.nvlTrim(rs.getString("BkupSndrcvFileName" ))); + info.setPriority ( rs.getInt ("MsgPrcssPrity" )); + info.setUpdateId (StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID" ))); + info.setUpdateTime (StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS" ))); + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName" ))); + info.setInstitutionName(StringUtil.nvlTrim(rs.getString("OsidInstiName" ))); + info.setBlockSize ( rs.getInt ("TelgmBlckSize" )); + info.setSequenceSize ( rs.getInt ("TelgmSernoSize" )); + info.setPacketSize ( rs.getInt ("TelgmPcketSize" )); + info.setFlowRuleCode (StringUtil.nvlTrim(rs.getString("FlowRuleCode" ))); + info.setProcessName (StringUtil.nvlTrim(rs.getString("BjobBzwkName" ))); + info.setHdrInfoName ( rs.getString("HdrInfoName" )); + info.setHolyProcessGb (StringUtil.nvlTrim(rs.getString("HoldyPrcssDstcd" ))); + info.setStartDelayDays ( rs.getInt ("StartDlayNoday" )); + info.setEndDelayDays ( rs.getInt ("EndDlayNoday" )); + info.setRecvRetryFlag (StringUtil.nvlTrim(rs.getString("RqstRecvReTralUseYn")));//2009.6.19 add by kscheon + alist.add(info); + } + + return alist; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC020"); + throw new DAOException(errMsg); //배치작업 스케쥴 대기목록 테이블에서 수행대상 작업 조회시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + public ArrayList getExecutableJobListWithSuspendedJob() throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(SELECT_EXECUTABLE_JOB_FROM_QUEUE_WITH_SUSPENDED_JOB); + //logger.debug("SchedulerMessageDAO.getExecutableJobList() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_EXECUTABLE_JOB_FROM_QUEUE); + + rs = executeQuery(); + + ArrayList alist = new ArrayList(); + while (rs.next()) { + SchedulerMessageVO info = new SchedulerMessageVO(); + info.setUUID (StringUtil.nvlTrim(rs.getString("BjobDmndMsgID" ))); + info.setSubUUID (StringUtil.nvlTrim(rs.getString("BjobDmndSubMsgID" ))); + info.setRecvFailCnt ( rs.getInt ("TelgmReTralCnt" )); + info.setMsgCreateTime (StringUtil.nvlTrim(rs.getString("BjobDmndMsgCretnHMS"))); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); + info.setInstitutionCode(StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); + info.setFilePath (StringUtil.nvlTrim(rs.getString("SndrcvFileDirName" ))); + info.setFileName (StringUtil.nvlTrim(rs.getString("SndrcvFileName" ))); + info.setRenamedFileName(StringUtil.nvlTrim(rs.getString("BkupSndrcvFileName" ))); + info.setPriority ( rs.getInt ("MsgPrcssPrity" )); + info.setUpdateId (StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID" ))); + info.setUpdateTime (StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS" ))); + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName" ))); + info.setInstitutionName(StringUtil.nvlTrim(rs.getString("OsidInstiName" ))); + info.setBlockSize ( rs.getInt ("TelgmBlckSize" )); + info.setSequenceSize ( rs.getInt ("TelgmSernoSize" )); + info.setPacketSize ( rs.getInt ("TelgmPcketSize" )); + info.setFlowRuleCode (StringUtil.nvlTrim(rs.getString("FlowRuleCode" ))); + info.setProcessName (StringUtil.nvlTrim(rs.getString("BjobBzwkName" ))); + info.setHdrInfoName ( rs.getString("HdrInfoName" )); + info.setHolyProcessGb (StringUtil.nvlTrim(rs.getString("HoldyPrcssDstcd" ))); + info.setStartDelayDays ( rs.getInt ("StartDlayNoday" )); + info.setEndDelayDays ( rs.getInt ("EndDlayNoday" )); + info.setRecvRetryFlag (StringUtil.nvlTrim(rs.getString("RqstRecvReTralUseYn")));//2009.6.19 add by kscheon + alist.add(info); + } + + return alist; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC020"); + throw new DAOException(errMsg); //배치작업 스케쥴 대기목록 테이블에서 수행대상 작업 조회시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + + public HashSet getExecutingSysConnList() throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(SELECT_EXECUTING_SYSTEMCONNID_FROM_PROCESSING); + //logger.debug("SchedulerMessageDAO.getExecutingSysConnList() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_EXECUTING_SYSTEMCONNID_FROM_PROCESSING); + + rs = executeQuery(); + + HashSet hSet = new HashSet(); + while (rs.next()) { + hSet.add(rs.getString("SysLnkgDstcd")); + } + + return hSet; + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC021"); + throw new DAOException(errMsg); //배치작업 진행목록 테이블에서 수행중인 작업의 연결정보 조회시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + public int moveExecutableJodToProcessing(ArrayList alist) throws DAOException { + + + try { + + this.connect(MOVE_JOB_FROM_QUEUE_TO_PROCESSING); + //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessing() >>> 수행 SQL 문 : \n"+ MOVE_JOB_FROM_QUEUE_TO_PROCESSING); + + for (int i=0; i < alist.size(); i++) { + + SchedulerMessageVO info = (SchedulerMessageVO)alist.get(i); + + int index = 1; + if ( info.getSystemConnCode().trim().equals("") ){ + this.preparedStatement.setString(index++, " "); + }else{ + this.preparedStatement.setString(index++, info.getSystemConnCode().trim()); + } + // + logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessing() >>> 바인드("+(index-1)+") : ["+ info.getSystemConnCode().trim() +"]"); + this.preparedStatement.setString(index++, info.getUUID().trim() ); + // + logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessing() >>> 바인드("+(index-1)+") : ["+ info.getUUID().trim() +"]"); + this.preparedStatement.setString(index++, info.getSubUUID().trim() ); + // + logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessing() >>> 바인드("+(index-1)+") : ["+ info.getSubUUID().trim() +"]"); + + logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessing() >>> MOVE_JOB_FROM_QUEUE_TO_PROCESSING"); + this.preparedStatement.addBatch(); + + } + + int[] resultCnt = this.preparedStatement.executeBatch(); + + int totalCnt = 0; + for (int i=0; i 배치 JOB 대기목록 -> 진행목록 복사 건 수: "+ totalCnt); + + if (alist.size() != totalCnt) { + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC022", new String[] {Integer.toString(alist.size()), Integer.toString(totalCnt)}); + throw new DAOException(errMsg); //배치작업 대기목록에서 진행목록으로 이동할 작업 건수[{1}]와 이동된 작업 건수[{2}]가 불일치합니다. + } + + this.prepareStatement(DELETE_JOB_FROM_QUEUE); + //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessing() >>> 수행 SQL 문 : \n"+ DELETE_JOB_FROM_QUEUE); + + for (int i=0; i < alist.size(); i++) { + + SchedulerMessageVO info = (SchedulerMessageVO)alist.get(i); + + int index = 1; + this.preparedStatement.setString(index++, info.getUUID().trim() ); + this.preparedStatement.setString(index++, info.getSubUUID().trim() ); + + this.preparedStatement.addBatch(); + } + + resultCnt = this.preparedStatement.executeBatch(); + totalCnt = 0; + for (int i=0; i 배치 JOB 대기목록 DELETE 건 수: "+ totalCnt); + + return totalCnt; + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC023"); + throw new DAOException(errMsg); //배치작업 대기목록에서 진행목록으로 진행할 작업을 이동시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + public int deleteJobFromProcessing(String uuid, String subUUID) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + this.connect(DELETE_JOB_FROM_PROCESSING); + //logger.debug("SchedulerMessageDAO.deleteJobFromProcessing() >>> 수행 SQL 문 : \n"+ DELETE_JOB_FROM_PROCESSING); + + index = 1; + this.preparedStatement.setString(index++, uuid); //logger.debug("SchedulerMessageDAO.deleteJobFromProcessing() >>> 바인드("+(index-1)+") : ["+ uuid +"]"); + this.preparedStatement.setString(index++, subUUID); //logger.debug("SchedulerMessageDAO.deleteJobFromProcessing() >>> 바인드("+(index-1)+") : ["+ subUUID +"]"); + + retValue = this.executeUpdate(); + logger.info("[요구송수신] ==> 진행 완료 및 오류 작업 DELETE 건 수 : "+ retValue); + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC024", new String[] {uuid}); + throw new DAOException(errMsg); //배치작업 진행목록에서 종료된 작업 삭제시 오류가 발생하였습니다. [UUID: {1}] + } finally { + disconnect(); + } + return retValue; + } + + public int deleteJobFromProcessing(String uuid) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + this.connect(DELETE_JOB_FROM_PROCESSING); + //logger.debug("SchedulerMessageDAO.deleteJobFromProcessing() >>> 수행 SQL 문 : \n"+ DELETE_JOB_FROM_PROCESSING); + + index = 1; + this.preparedStatement.setString(index++, uuid); //logger.debug("SchedulerMessageDAO.deleteJobFromProcessing() >>> 바인드("+(index-1)+") : ["+ uuid +"]"); + + retValue = this.executeUpdate(); + logger.info("[요구송수신] ==> 진행 완료 및 오류 작업 DELETE 건 수 : "+ retValue); + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC024", new String[] {uuid}); + throw new DAOException(errMsg); //배치작업 진행목록에서 종료된 작업 삭제시 오류가 발생하였습니다. [UUID: {1}] + } finally { + disconnect(); + } + return retValue; + } + + public int deleteJobFromProcessing() throws Exception { + + int retValue = 0; + + try { + + this.connect(DELETE_ALL_JOBS_FROM_PROCESSING); + + retValue = this.executeUpdate(); + logger.info("[작업 진행 TABLE 초기화] ==> 진행 완료 및 오류 작업 DELETE 건 수 : "+ retValue); + + } catch (Exception ex) { + throw ex; + } finally { + disconnect(); + } + return retValue; + } + + public ArrayList getExecutableRecvScheduleList() throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(SELECT_EXECUTABLE_RECV_SCHEDULE_LIST); + //logger.debug("SchedulerMessageDAO.getExecutableRecvScheduleList() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_EXECUTABLE_RECV_SCHEDULE_LIST); + + rs = executeQuery(); + + int cnt = 1; + ArrayList alist = new ArrayList(); + while (rs.next()) { + SchedulerMessageVO info = new SchedulerMessageVO(); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); // 스케쥴 아이디 + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); // Job 구분 코드 + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName" ))); // 거래구분코드 + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); // 송수신 시작 시간 + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); // 송수신 종료 시간 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분 코드 + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); // 업무유형 구분 + info.setHolyProcessGb (StringUtil.nvlTrim(rs.getString("HoldyPrcssDstcd" ))); // 공휴일 처리 유형 + info.setRpttYn (StringUtil.nvlTrim(rs.getString("RpttYn" ))); // 반복여부 + info.setInstitutionCode (StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); // 대외기관 코드 + info.setRecvRetryFlag (StringUtil.nvlTrim(rs.getString("RqstRecvReTralUseYn"))); // 요구수신실패시 재시도여부 + info.setRecvRetryCnt (rs.getInt("RqstRecvReTralCnt" )); // 요구수신실패시 재시도회수 + info.setRecvRetrySecs (rs.getInt("RqstRecvReTralIntvalTtm")); // 요구수신실패시 재시도간격 + info.setRecvFailCnt (rs.getInt("RecvFileFailCnt" )); // 요구수신실패 회수 + + int recvFileEndCnt = rs.getInt("RecvFileEndCnt"); + int recvFileFailCnt = info.getRecvFailCnt(); + String recentExecTime = StringUtil.nvlTrim(rs.getString("RecentExecTime")) + "0"; //yyyyMMddHHmmssSSS 형태로 맞춤 + + //logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime()); + + String holyProcessGb = info.getHolyProcessGb(); + if ( ( holyProcessGb.equals("1") && HolidayManager.getInstance().isAllHoliday(DatetimeUtil.getCurrentDate()) ) || + ( holyProcessGb.equals("2") && HolidayManager.getInstance().isHoliday(DatetimeUtil.getCurrentDate()) ) ){ + logger.info("[스케쥴 핸들러] ★★★ 영업일이 아니므로 처리 하지 않습니다.("+ info.getProcessCode() +" | "+ info.getInstitutionCode()+" | "+ info.getScheduleCode() +") ★★★"); + continue; + } + + //요구수신 최초 수행인 경우, 요구수신 작업 수행함 + if (recvFileEndCnt == 0 && recvFileFailCnt == 0) { + logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 최초 수행, Job_Queue 에 추가예정."); + alist.add(info); + + //요구수신 수행이 성공적으로 완료된 경우, 요구수신 작업 수행 안함 + } else if ((info.getRpttYn().equals("0")) && (recvFileEndCnt > 0)) { + logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 파일 수신이 이미 완료되었음."); + + //요구수신 수행이 실패한 경우, 재시도 회수를 체크하여 재수행 + } else if (recvFileFailCnt > 0) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + long latestTime = sdf.parse(recentExecTime).getTime(); + Date currDate = new Date(); + long currTime = currDate.getTime(); + long diffSeconds = (currTime - latestTime) / 1000; + Date nextDate = new Date(latestTime + (info.getRecvRetrySecs() * 1000)); + + //해당 스케쥴정보의 요구수신 재시도 여부가 설정되지 않은 경우, 요구수신 작업 수행 안함 + if (info.getRecvRetryFlag().equals("0")) { + logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도가 설정되지 않았음. (미완료 작업건수: "+ info.getRecvFailCnt() +")"); + + //해당 스케쥴정보의 요구수신 재시도 회수를 초과한 경우, 요구수신 작업 수행 안함 + } else if (info.getRecvRetryCnt() > 0 && (info.getRecvFailCnt()-1) >= info.getRecvRetryCnt()) { + logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도 회수만큼 수행하였으나 파일 수신 미완료. (재시도 회수: "+ info.getRecvRetryCnt() +")"); + + //해당 스케쥴정보의 요구수신 재시도 수행 간격에 따른 재시도 시간이 되지 않은 경우, 다음 Timer Event 시 다시 체크 + } else if (diffSeconds < info.getRecvRetrySecs()) { + logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도 시간이 되지 않았음. (재시도 회수: "+ (info.getRecvFailCnt()-1) +"/"+ info.getRecvRetryCnt() +", 현재시간: "+ sdf1.format(currDate) +", 재시도 수행시간: "+ sdf1.format(nextDate) +")"); + + //해당 스케쥴정보의 요구수신 재시도 설정 조건에 일치하는 경우, 요구수신 작업 수행 함 + } else { + logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도 수행, Job_Queue 에 추가예정. (재시도 회수: "+ info.getRecvFailCnt() +"/"+ info.getRecvRetryCnt() +")"); + alist.add(info); + } + } else { + if (info.getRpttYn().equals("1")){ + logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 타이머 성격 요구수신 수행, Job_Queue 에 추가예정. (재시도 회수: "+ info.getRecvFailCnt() +"/"+ info.getRecvRetryCnt() +")"); + alist.add(info); + } + } + cnt++; + } + + return alist; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC025"); + throw new DAOException(errMsg); //작업 대기목록 테이블에서 수행대상 작업 조회시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + public int moveExecutableJodToProcessingWithNewID(SchedulerMessageVO info, String strUUID, String strSubUUID) throws DAOException { + + ResultSet rs = null; + + int retValue = 0; + + try { + + this.connect(SELCT_JOB_FROM_QUEUE); + //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 수행 SQL 문 : \n"+ SELCT_JOB_FROM_QUEUE); + + int index = 1; + this.preparedStatement.setString(index++, info.getUUID()); + this.preparedStatement.setString(index++, info.getSubUUID()); + + rs = executeQuery(); + + String strTelgmReTralCnt ; + String strBjobDmndMsgCretnHMS ; + String strBjobMsgScheID ; + String strBjobBzwkDstcd ; + String strOsidInstiDstcd ; + String strBjobPtrnDstcd ; + String strSndrcvStartHMS ; + String strSndrcvEndHMS ; + String strSndrcvFileDirName ; + String strSndrcvFileName ; + String strBkupSndrcvFileName ; + String strMsgPrcssPrity ; + String strThisMsgAmndrID ; + String strThisMsgAmndHMS ; + + if ( !rs.next()) { + throw new DAOException(" 대기 작업이 없습니다."); //배치작업 대기목록에서 진행목록으로 진행할 작업을 이동시 오류가 발생하였습니다. + } + strTelgmReTralCnt = StringUtil.nvlTrim(rs.getString("TelgmReTralCnt")); + strBjobDmndMsgCretnHMS = StringUtil.nvlTrim(rs.getString("BjobDmndMsgCretnHMS")); + strBjobMsgScheID = StringUtil.nvlTrim(rs.getString("BjobMsgScheID")); + strBjobBzwkDstcd = StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd")); + strOsidInstiDstcd = StringUtil.nvlTrim(rs.getString("OsidInstiDstcd")); + strBjobPtrnDstcd = StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd")); + strSndrcvStartHMS = StringUtil.nvlTrim(rs.getString("SndrcvStartHMS")); + strSndrcvEndHMS = StringUtil.nvlTrim(rs.getString("SndrcvEndHMS")); + strSndrcvFileDirName = StringUtil.nvlTrim(rs.getString("SndrcvFileDirName")); + strSndrcvFileName = StringUtil.nvlTrim(rs.getString("SndrcvFileName")); + strBkupSndrcvFileName = StringUtil.nvlTrim(rs.getString("BkupSndrcvFileName")); + strMsgPrcssPrity = StringUtil.nvlTrim(rs.getString("MsgPrcssPrity")); + strThisMsgAmndrID = StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID")); + strThisMsgAmndHMS = StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS")); + + + this.prepareStatement(UPDATE_PROCESSING_WITH_NEW_JOB); + + index = 1; + + this.preparedStatement.setString(index++, strTelgmReTralCnt ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strTelgmReTralCnt +"]"); + this.preparedStatement.setString(index++, strBjobDmndMsgCretnHMS ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strBjobDmndMsgCretnHMS +"]"); + this.preparedStatement.setString(index++, strBjobMsgScheID ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strBjobMsgScheID +"]"); + this.preparedStatement.setString(index++, strBjobBzwkDstcd ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strBjobBzwkDstcd +"]"); + this.preparedStatement.setString(index++, strOsidInstiDstcd ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strOsidInstiDstcd +"]"); + this.preparedStatement.setString(index++, strBjobPtrnDstcd ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strBjobPtrnDstcd +"]"); + this.preparedStatement.setString(index++, strSndrcvStartHMS ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strSndrcvStartHMS +"]"); + this.preparedStatement.setString(index++, strSndrcvEndHMS ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strSndrcvEndHMS +"]"); + this.preparedStatement.setString(index++, strSndrcvFileDirName ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strSndrcvFileDirName +"]"); + this.preparedStatement.setString(index++, strSndrcvFileName ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strSndrcvFileName +"]"); + this.preparedStatement.setString(index++, strBkupSndrcvFileName ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strBkupSndrcvFileName +"]"); + this.preparedStatement.setString(index++, strMsgPrcssPrity ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strMsgPrcssPrity +"]"); + this.preparedStatement.setString(index++, strThisMsgAmndrID ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strThisMsgAmndrID +"]"); + this.preparedStatement.setString(index++, strThisMsgAmndHMS ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strThisMsgAmndHMS +"]"); + + this.preparedStatement.setString(index++, strSubUUID ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strSubUUID +"]"); + this.preparedStatement.setString(index++, strUUID ); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 바인드("+(index-1)+") : ["+ strUUID +"]"); + + retValue = this.preparedStatement.executeUpdate(); + logger.info("[스케쥴 핸들러] ==> 프로세싱 JOB UPDATE 건 수: "+ retValue); + + // 큐에서 작업 삭제 + this.prepareStatement(DELETE_JOB_FROM_QUEUE); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 수행 SQL 문 : \n"+ DELETE_JOB_FROM_QUEUE); + index = 1; + this.preparedStatement.setString(1, info.getUUID()); + this.preparedStatement.setString(2, info.getSubUUID() ); + retValue = this.preparedStatement.executeUpdate(); + logger.info("[스케쥴 핸들러] ==> 배치 JOB 대기목록 DELETE 건 수: "+ retValue); + + // 로그에서 삭제 + this.prepareStatement(DELETE_JOB_FROM_LOGMASTER); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 수행 SQL 문 : \n"+ DELETE_JOB_FROM_LOGMASTER); + index = 1; + this.preparedStatement.setString(index++, info.getUUID()); + retValue = this.preparedStatement.executeUpdate(); + logger.info("[스케쥴 핸들러] ==> 로그마스터 DELETE 건 수: "+ retValue); + + this.prepareStatement(DELETE_JOB_FROM_LOGDETAIL); //logger.debug("SchedulerMessageDAO.moveExecutableJodToProcessingWithNewID() >>> 수행 SQL 문 : \n"+ DELETE_JOB_FROM_LOGDETAIL); + index = 1; + this.preparedStatement.setString(index++, info.getUUID()); + retValue = this.preparedStatement.executeUpdate(); + logger.info("[스케쥴 핸들러] ==> 로그디테일 DELETE 건 수: "+ retValue); + + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC023"); + throw new DAOException(errMsg); //배치작업 대기목록에서 진행목록으로 진행할 작업을 이동시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + + public SchedulerMessageVO getScheduleByScheduleCode(String ScheduleCode) throws Exception + { + ResultSet rs = null; + SchedulerMessageVO info = new SchedulerMessageVO(); + + try { + this.connect(SELECT_SCHEDULE_BY_CODE); + //logger.debug("SchedulerMessageDAO.getScheduleByScheduleCode() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_SCHEDULE_BY_CODE); + + int index = 1; + this.preparedStatement.setString(index++, ScheduleCode); + logger.debug("SchedulerMessageDAO.getScheduleByScheduleCode() >>> ScheduleCode -->[" + ScheduleCode + "]"); + + rs = executeQuery(); + + while (rs.next()) { + info.setProcessCode (StringUtil.nvlTrim(rs.getString( "BjobBzwkDstcd" ))); + info.setProcessName (StringUtil.nvlTrim(rs.getString( "BjobBzwkName" ))); + info.setInstitutionCode (StringUtil.nvlTrim(rs.getString( "OsidInstiDstcd" ))); + info.setInstitutionName (StringUtil.nvlTrim(rs.getString( "OsidInstiName" ))); + info.setJobCode (StringUtil.nvlTrim(rs.getString( "BjobMsgDstcd" ))); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString( "BjobMsgScheID" ))); + info.setProcessType (StringUtil.nvlTrim(rs.getString( "BjobPtrnDstcd" ))); + info.setBizCode (StringUtil.nvlTrim(rs.getString( "BjobTranDstcdName" ))); + info.setRecvFailCnt (rs.getInt ( "RqstRecvReTralCnt" )); + info.setStartTime (StringUtil.nvlTrim(rs.getString( "SndrcvStartHMS" ))); + info.setEndTime (StringUtil.nvlTrim(rs.getString( "SndrcvEndHMS" ))); + + break; + } + + return info; + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC025"); + throw new DAOException(errMsg); //작업 대기목록 테이블에서 수행대상 작업 조회시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } +// File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회하여 + //가장 우선순위(우선순위 > 스케줄시작시간 > 스케쥴종료시간)가 높은 스케쥴 정보 리턴 + public SchedulerMessageVO getScheduleInfo(String scheduleId) throws DAOException { + + ResultSet rs = null; +// int index = 0; + + try { + this.connect(SELECT_SEND_SCHEDULE_BY_SCHEDULEID); + //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 수행 SQL 문 : \n"+ SELECT_SEND_SCHEDULE_BY_SCHEDULEID); + + this.preparedStatement.setString(1, scheduleId ); + logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 바인드 : ["+ scheduleId +"]"); + + rs = executeQuery(); + + SchedulerMessageVO info = null; + if (rs.next()) { + info = new SchedulerMessageVO(); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); // 스케쥴 아이디 + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); // Job 구분 코드 + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName"))); // 거래구분코드 + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); // 송수신 시작 시간 + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); // 송수신 종료 시간 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분 코드 + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); // 업무유형 구분 + info.setInstitutionCode(StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); // 대외기관 코드 + info.setRecvRetryFlag (StringUtil.nvlTrim(rs.getString("RqstRecvReTralUseYn"))); + + try{ + info.setRecvRetryCnt (Integer.parseInt(StringUtil.nvlTrim(rs.getString("RqstRecvReTralCnt")))); + }catch (Exception e){ + logger.error(scheduleId +" ] RecvRetryCnt 을 설정하는데 오류가 발생했습니다. - "+rs.getString("RqstRecvReTralCnt")); + } + try{ + info.setRecvRetrySecs (Integer.parseInt(StringUtil.nvlTrim(rs.getString("RqstRecvReTralIntvalTtm")))); + }catch (Exception e){ + logger.error(scheduleId +" ] RecvRetrySecs 을 설정하는데 오류가 발생했습니다. - "+rs.getString("RqstRecvReTralIntvalTtm")); + } + } + return info; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + //String errMsg = ExceptionUtil.getErrorCode(e, "BECEAISSC001", new String[] {processCode, osidinstidstCode, bizCode}); + String errMsg = (scheduleId +"] 에 해당하는 스케줄 정보를 조회하는데 오류가 발생했습니다. - "+e.getMessage()); + throw new DAOException(errMsg); //해당 스케쥴 정보를 찾을 수 없습니다. (업무구분: %1, 대외기관: %2, 거래구분: %3) + } finally { + disconnect(); + } + } + + + //2008.09.22 by kscheon + /* + public ArrayList getExecutableReReqRecvScheduleList() throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(SELECT_EXECUTABLE_RE_REQ_RECV_SCHEDULE_LIST); + //logger.debug("SchedulerMessageDAO.getExecutableRecvScheduleList() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_EXECUTABLE_RECV_SCHEDULE_LIST); + + rs = executeQuery(); + + int cnt = 1; + ArrayList alist = new ArrayList(); + ArrayList deletelist = new ArrayList(); + +// boolean isDelete = false; + + while (rs.next()) { + + SchedulerMessageVO info = new SchedulerMessageVO(); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); // 스케쥴 아이디 + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); // Job 구분 코드 + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName" ))); // 거래구분코드 + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); // 송수신 시작 시간 + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); // 송수신 종료 시간 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분 코드 + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); // 업무유형 구분 + info.setInstitutionCode (StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); // 대외기관 코드 + info.setRecvRetryFlag (StringUtil.nvlTrim(rs.getString("RqstRecvReTralUseYn"))); // 요구수신실패시 재시도여부 + info.setRecvRetryCnt (rs.getInt("RqstRecvReTralCnt" )); // 요구수신실패시 재시도회수 + info.setRecvRetrySecs (rs.getInt("RqstRecvReTralIntvalTtm")); // 요구수신실패시 재시도간격 + info.setRecvFailCnt (rs.getInt("RecvFileFailCnt" )); // 요구수신실패 회수 + + info.setRePrcssStartYMS (rs.getString("RePrcssStartYMS")); + + int recvFileEndCnt = rs.getInt("RecvFileEndCnt"); + int recvFileFailCnt = info.getRecvFailCnt(); + String recentExecTime = StringUtil.nvlTrim(rs.getString("RecentExecTime")) + "0"; //yyyyMMddHHmmssSSS 형태로 맞춤 + + //logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime()); + + //요구수신 최초 수행인 경우, 요구수신 작업 수행함 + //if (recvFileEndCnt == 0 && recvFileFailCnt == 0) { + // logger.info("[요구수신 스케쥴러] * 요구수신 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 최초 수행, Job_Queue 에 추가예정."); + // alist.add(info); + + //요구수신 수행이 성공적으로 완료된 경우, 재처리 queue에서 삭제 + //} + if (recvFileEndCnt > 0) { + logger.info("[요구수신 재처리 스케쥴러] * 요구수신 재처리 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 파일 수신이 이미 완료되었음."); + + deletelist.add(info); + + //요구수신 수행이 실패한 경우, 재시도 회수를 체크하여 재수행 + } else if (recvFileFailCnt > 0) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + long latestTime = sdf.parse(recentExecTime).getTime(); + Date currDate = new Date(); + long currTime = currDate.getTime(); + long diffSeconds = (currTime - latestTime) / 1000; + Date nextDate = new Date(latestTime + (info.getRecvRetrySecs() * 1000)); + + //해당 스케쥴정보의 요구수신 재시도 여부가 설정되지 않은 경우, 요구수신 작업 수행 안함 + if (info.getRecvRetryFlag().equals("0")) { + logger.info("[요구수신 재처리 스케쥴러] * 요구수신 재처리 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도가 설정되지 않았음. (미완료 작업건수: "+ info.getRecvFailCnt() +")"); + + //해당 스케쥴정보의 요구수신 재시도 회수를 초과한 경우, 요구수신 작업 수행 안함 + //info.getRecvRetryCnt() != 0 조건은 재시도 반복회수가 0인 경우는 무한 반복하게 하기 위함 + } else if (info.getRecvRetryCnt() > 0 && (info.getRecvFailCnt()-1) >= info.getRecvRetryCnt()) { + logger.info("[요구수신 재처리 스케쥴러] * 요구수신 재처리 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도 회수만큼 수행하였으나 파일 수신 미완료. (재시도 회수: "+ info.getRecvRetryCnt() +")"); + deletelist.add(info); + + //해당 스케쥴정보의 요구수신 재시도 수행 간격에 따른 재시도 시간이 되지 않은 경우, 다음 Timer Event 시 다시 체크 + } else if (diffSeconds < info.getRecvRetrySecs()) { + logger.info("[요구수신 재처리 스케쥴러] * 요구수신 재처리 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도 시간이 되지 않았음. (재시도 회수: "+ (info.getRecvFailCnt()-1) +"/"+ info.getRecvRetryCnt() +", 현재시간: "+ sdf1.format(currDate) +", 재시도 수행시간: "+ sdf1.format(nextDate) +")"); + + //해당 스케쥴정보의 요구수신 재시도 설정 조건에 일치하는 경우, 요구수신 작업 수행 함 + } else { + logger.info("[요구수신 재처리 스케쥴러] * 요구수신 재처리 스케쥴정보 ["+ cnt +"]: "+ info.getScheduleCode() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getBizCode() +" | "+ info.getStartTime() +" | "+ info.getEndTime() +" ==> 요구수신 재시도 수행, Job_Queue 에 추가예정. (재시도 회수: "+ info.getRecvFailCnt() +"/"+ info.getRecvRetryCnt() +")"); + alist.add(info); + } + } + cnt++; + } + + if (deletelist != null && deletelist.size() > 0){ + logger.info("[요구수신 재처리 스케쥴러] 재처리 완료 건수 ["+ deletelist.size() +"] "); + + for (int i=0; i< deletelist.size(); i++){ + SchedulerMessageVO deleteInfo = (SchedulerMessageVO)deletelist.get(i); + logger.info("[요구수신 재처리 스케쥴러] 재처리 대기큐 목록에서 삭제합니다. ["+ deleteInfo.getScheduleCode()+"]"); + this.prepareStatement(DELETE_RETRY_QUEUE); + this.preparedStatement.setString(1,deleteInfo.getScheduleCode() ); + this.preparedStatement.setString(2,deleteInfo.getRePrcssStartYMS() ); + this.preparedStatement.executeUpdate(); + } + } + + return alist; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + ex.printStackTrace(); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC025"); + throw new DAOException(errMsg); //작업 대기목록 테이블에서 수행대상 작업 조회시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } + + //2008.09.22 by kscheon + public void insertRertyQueue(com.eactive.eai.batch.doc.BatchDoc info)throws DAOException{ + + int index = 0; + int retValue = 0; + + try{ + this.connect(INSERT_RETRY_QUEUE); + + index = 1; + + this.preparedStatement.setString(index++, info.getEAIBatchMessage().getHeader().getEventScheduleID()); + this.preparedStatement.setString(index++, info.getEAIBatchMessage().getHeader().getScheduleCode()); + + retValue = this.executeUpdate(); + //logger.debug("[요구송신 스케쥴러] ==> 배치 JOB QUEUE 테이블 INSERT 건수: "+ retValue); + + if (retValue == 0) throw new DAOException("BECEAISSC019"); //배치작업 스케쥴 대기정보 insert 건 수가 0 건입니다. + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC002"); + throw new DAOException(errMsg); //배치작업 스케쥴 대기정보 등록시 오류가 발생하였습니다. + } finally { + disconnect(); + } + + } + */ + + + public SchedulerMessageVO getReqSendScheduleInfo(String scheduleId) throws DAOException { + + ResultSet rs = null; +// int index = 0; + + try { + this.connect(SELECT_REQ_SEND_SCHEDULE_BY_SCHEDULEID); + //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 수행 SQL 문 : \n"+ SELECT_REQ_SEND_SCHEDULE_BY_SCHEDULEID); + + this.preparedStatement.setString(1, scheduleId ); + logger.debug("SchedulerMessageDAO.getReqSendScheduleInfo() >>> 바인드 : ["+ scheduleId +"]"); + + rs = executeQuery(); + + SchedulerMessageVO info = null; + if (rs.next()) { + info = new SchedulerMessageVO(); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); // 스케쥴 아이디 + info.setJobCode (StringUtil.nvlTrim(rs.getString("BjobMsgDstcd" ))); // Job 구분 코드 + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName" ))); // 거래구분코드 + info.setStartTime (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); // 송수신 시작 시간 + info.setEndTime (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); // 송수신 종료 시간 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분 코드 + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); // 업무유형 구분 + info.setPriority ( rs.getInt ("MsgPrcssPrity" )); + info.setInstitutionCode(StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); // 대외기관 코드 + info.setRecvFailCnt ( rs.getInt ("RecvFileFailCnt" )); // 요구송신실패 횟수 + info.setRecvRetryFlag (StringUtil.nvlTrim(rs.getString("RqstRecvReTralUseYn" ))); //재시도사용유무 설정 + info.setRecvRetrySecs ( rs.getInt ("RqstRecvReTralIntvalTtm")); //재시도 간격(초) + info.setRecvRetryCnt ( rs.getInt ("RqstRecvReTralCnt" )); //재시도 횟수 + + } + return info; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + //String errMsg = ExceptionUtil.getErrorCode(e, "BECEAISSC001", new String[] {processCode, osidinstidstCode, bizCode}); + String errMsg = (scheduleId +"] 에 해당하는 스케줄 정보를 조회하는데 오류가 발생했습니다. - "+e.getMessage()); + throw new DAOException(errMsg); //해당 스케쥴 정보를 찾을 수 없습니다. (업무구분: %1, 대외기관: %2, 거래구분: %3) + } finally { + disconnect(); + } + } + + + //2009.8.14 by kscheon 실행큐에 실행중인 작업 조회 + public ArrayList getExecutJobList(String jobCode) throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(SELECT_EXECUTING_JOB_FROM_PROCESSING); + //logger.debug("SchedulerMessageDAO.getExecutableRecvScheduleList() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_EXECUTABLE_RECV_SCHEDULE_LIST); + this.preparedStatement.setString(1, jobCode ); + rs = executeQuery(); + + ArrayList alist = new ArrayList(); + while (rs.next()) { + SchedulerMessageVO info = new SchedulerMessageVO(); + info.setProcessCode(rs.getString("BjobBzwkDstcd")); + info.setPriority (rs.getInt ("MsgPrcssPrity")); + + alist.add(info); + } + return alist; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + + String errMsg = (" 실행큐 조회중에 오류가 발생했습니다. - "+e.getMessage()); + throw new DAOException(errMsg); + } finally { + disconnect(); + } + + } + + private SchedulerMessageVO insertNewRecvSchedule( String processCode, String institutionCode, String jobCode) + throws DAOException { + String id = null; + + BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, jobCode); + if ( bjvo == null ){ + return null; + } + String bjobMsgDstcd = bjvo.getMsgDstCode(); + + try { + ResultSet rs = null; + this.connect(GET_BJOBMSGSCHEID); + + this.preparedStatement.setString(1, "R"); + this.preparedStatement.setString(2, bjobMsgDstcd); + this.preparedStatement.setString(3, bjobMsgDstcd); + rs = executeQuery(); + if (rs.next()) { + id = rs.getString(1); + }else{ + return null; + } + } catch (Exception e) { + logger.error( e.getMessage(), e); + return null; + } finally { + this.disconnect(); + } + + + try { + this.connect(ADD_JOB_SCH_INFO); + this.preparedStatement.setString( 1, id ); + this.preparedStatement.setString( 2, bjobMsgDstcd ); + this.preparedStatement.setString( 3, "RR" ); + this.preparedStatement.setString( 4, institutionCode); + this.preparedStatement.setString( 5, "0000" ); + this.preparedStatement.setString( 6, "2359" ); + this.preparedStatement.setString( 7, "SYSTEM" ); + this.preparedStatement.setString( 8, "0" ); + this.preparedStatement.setString( 9, "0" ); + this.preparedStatement.setString(10, "0" ); + this.preparedStatement.setInt (11, 0 ); + this.preparedStatement.setInt (12, 0 ); + this.preparedStatement.setString(13, "0" ); + this.preparedStatement.setString(14, "0" ); + this.preparedStatement.setString(15, "0" ); + this.preparedStatement.setString(16, "SYSTEM" ); + this.preparedStatement.setString(17, "SYSTEM" ); + executeUpdate(); + SchedulerMessageVO info = new SchedulerMessageVO(); + info.setScheduleCode (id); // 스케쥴 아이디 + info.setJobCode (bjobMsgDstcd); // Job 구분 코드 + info.setBizCode (jobCode); // 거래구분코드 + info.setStartTime ("0000"); // 송수신 시작 시간 + info.setEndTime ("2359"); // 송수신 종료 시간 + info.setProcessCode (processCode); // 업무구분 코드 + info.setProcessType ("RR"); // 업무유형 구분 + info.setInstitutionCode(institutionCode); // 대외기관 코드 + info.setPriority (999); // 메시지 처리 우선 순위 + info.setHolyProcessGb ("0"); // 공휴일처리구분 + info.setStartDelayDays (0); + info.setEndDelayDays (0); + return info; + } catch (Exception e) { + logger.error( e.getMessage(), e); + throw new DAOException( + ExceptionUtil.getErrorCode(e, "BECEAIUSC008")); + } finally { + this.disconnect(); + } + } + + /** + * 2009.11.24 거래로그 화면에서 재전송을 실행하기 위해 데이터 조회(RTS에서 Framework 로 이동 ) + */ + public JobMasterLogVO getJobLogByKey(String uuid,String subUuid) throws DAOException { + + + try{ + this.connect(SELECT_LOG_MASTER_BY_KEYS); + + int index = 1; + this.preparedStatement.setString(index++, uuid ); //logger.debug(">>> 바인드("+(index-1)+") : ["+ uuid +"]"); + this.preparedStatement.setString(index++, subUuid ); //logger.debug(">>> 바인드("+(index-1)+") : ["+ subUuid +"]"); + + ResultSet rs = executeQuery(); + + + JobMasterLogVO info = null; + while (rs.next()) { + + info = new JobMasterLogVO(); + info.setUuid (StringUtil.nvlTrim(rs.getString("BjobDmndMsgID" ))); + info.setSubUuid (StringUtil.nvlTrim(rs.getString("BjobDmndSubMsgID" ))); + info.setRetryCount ( rs.getInt ("TelgmReTralCnt" ) ); + info.setScheduleCode (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); + info.setMsgCreateTime (StringUtil.nvlTrim(rs.getString("BjobDmndMsgCretnHMS" ))); + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); + info.setProcessName (StringUtil.nvlTrim(rs.getString("BjobBzwkName" ))); + info.setOrganCode (StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); + info.setOrganName (StringUtil.nvlTrim(rs.getString("OsidInstiName" ))); + info.setProcessType (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); + info.setMsgSenderId (StringUtil.nvlTrim(rs.getString("MsgSndrID" ))); + info.setMsgSenderName (StringUtil.nvlTrim(rs.getString("MsgSndrName" ))); + info.setSystemConnCode (StringUtil.nvlTrim(rs.getString("SysLnkgDstcd" ))); + info.setRemoteServerIp (StringUtil.nvlTrim(rs.getString("LnkgIPInfoName" ))); + info.setRuleCode (StringUtil.nvlTrim(rs.getString("FlowRuleCd" ))); + info.setWeblogicName (StringUtil.nvlTrim(rs.getString("EAISevrInstncName" ))); + info.setStartTime (StringUtil.nvlTrim(rs.getString("TranStartHMS" ))); + info.setEndTime (StringUtil.nvlTrim(rs.getString("TranEndHMS" ))); + info.setStatus (StringUtil.nvlTrim(rs.getString("TranPrcssDstcd" ))); + info.setErrMsg (StringUtil.nvlTrim(rs.getString("EAIObstclOccurCausCtnt"))); + info.setErrHandleId (StringUtil.nvlTrim(rs.getString("ObstclPrcsrID" ))); + info.setErrHandleTime (StringUtil.nvlTrim(rs.getString("ObstclPrcssHMS" ))); + + } + + return info; + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); + } finally { + disconnect(); + } + } + + public JobFileTransferVO getFileLogList(String uuid, String subUuid, String fileName) throws DAOException { + try { + + this.connect(SELECT_FILE_LOG_BY_KEYS); + logger.debug(">>> 일괄작업 Stage 로그 검색 SQL : \n"+ SELECT_FILE_LOG_BY_KEYS); + + int index = 1; + this.preparedStatement.setString(index++, uuid ); logger.debug(">>> 바인드("+(index-1)+") : ["+ uuid +"]" ); + this.preparedStatement.setString(index++, subUuid ); logger.debug(">>> 바인드("+(index-1)+") : ["+ subUuid +"]" ); + this.preparedStatement.setString(index++, fileName ); logger.debug(">>> 바인드("+(index-1)+") : ["+ fileName +"]"); + + ResultSet rs = executeQuery(); + + if (rs.next()) { + + JobFileTransferVO fileInfo = new JobFileTransferVO(); + fileInfo.setUuid (uuid); + fileInfo.setSubUuid (subUuid); + fileInfo.setFileName (fileName); + fileInfo.setFilePath (StringUtil.nvlTrim(rs.getString("RqstRecvFileStorgDirName"))); + fileInfo.setRenamedFileName (StringUtil.nvlTrim(rs.getString("BkupSndrcvFileName" ))); + fileInfo.setBjobTranDstcdName (rs.getString("BjobTranDstcdName" )); + fileInfo.setHdrInfoName (rs.getString("HdrInfoName" )); + return fileInfo; + } + return null; + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); + } finally { + disconnect(); + } + } + + public ArrayList getScheduledJobList(ArrayList basisList ) throws DAOException { + + ResultSet rs = null; + + try { + + String query = SELECT_SCHEDULE_BASIS; + if ( basisList.size()>0 ){ + query = query + "AND RTRIM( SndrcvCyclTypName ) IN ( '"; + query = query + basisList.get(0) + "'"; + for ( int inx=1; inx < basisList.size(); inx++ ){ + query = query + ", '" + basisList.get(inx) + "'"; + } + query = query + ")"; + } + + this.connect(query); + //logger.debug("SchedulerMessageDAO.getScheduledJobList() >>> 수행 SQL 문 : \n"+ query); + rs = executeQuery(); + + ArrayList alist = new ArrayList(); + while (rs.next()) { + JobFileTransferVO schedule = new JobFileTransferVO(); + schedule.setBjobMsgScheID (rs.getString("BjobMsgScheID" )); + schedule.setBjobBzwkDstcd (rs.getString("BjobBzwkDstcd" )); + schedule.setBjobBzwkName (rs.getString("BjobBzwkName" )); + schedule.setOsidInstiDstcd (rs.getString("OsidInstiDstcd" )); + schedule.setOsidInstiName (rs.getString("OsidInstiName" )); + schedule.setBjobTranDstcdName(rs.getString("BjobTranDstcdName")); + schedule.setBjobMsgDstcd (rs.getString("BjobMsgDstcd" )); + schedule.setSendRecvYn (rs.getString("SendRecvYn" )); + schedule.setSndrcvCyclTypName(rs.getString("SndrcvCyclTypName")); + schedule.setUapplCd (rs.getString("UapplCd" )); + schedule.setThisMsgChrgIDs (rs.getString("ThisMsgChrgIDs" )); + schedule.setSndrcvStartHMS (rs.getString("SndrcvStartHMS" ).trim()); + schedule.setSndrcvEndHMS (rs.getString("SndrcvEndHMS" ).trim()); + + alist.add(schedule); + } + return alist; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + + String errMsg = ("스케쥴 리스트 조회 중에 오류가 발생했습니다. - "+e.getMessage()); + throw new DAOException(errMsg); + } finally { + disconnect(); + } + } + + public ArrayList getProcessinbgJobList() throws DAOException { + + ResultSet rs = null; + + try { + + this.connect(SELECT_ALL_JOBS_FROM_PROCESSING); + //logger.debug("SchedulerMessageDAO.getExecutableJobList() >>> 수행 SQL 문 : \n"+ SchedulerMessageQuery.SELECT_EXECUTABLE_JOB_FROM_QUEUE); + + rs = executeQuery(); + + ArrayList alist = new ArrayList(); + while (rs.next()) { + JobProcessingVO vo = new JobProcessingVO(); + vo.setBjobDmndMsgID (StringUtil.nvlTrim(rs.getString("BjobDmndMsgID" ))); + vo.setBjobDmndSubMsgID (StringUtil.nvlTrim(rs.getString("BjobDmndSubMsgID" ))); + vo.setTelgmReTralCnt (rs.getInt("TelgmReTralCnt" )); + vo.setSysLnkgDstcd (StringUtil.nvlTrim(rs.getString("SysLnkgDstcd" ))); + vo.setBjobDmndMsgCretnHMS (StringUtil.nvlTrim(rs.getString("BjobDmndMsgCretnHMS"))); + vo.setBjobMsgScheID (StringUtil.nvlTrim(rs.getString("BjobMsgScheID" ))); + vo.setBjobBzwkDstcd (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); + vo.setOsidInstiDstcd (StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); + vo.setBjobPtrnDstcd (StringUtil.nvlTrim(rs.getString("BjobPtrnDstcd" ))); + vo.setSndrcvStartHMS (StringUtil.nvlTrim(rs.getString("SndrcvStartHMS" ))); + vo.setSndrcvEndHMS (StringUtil.nvlTrim(rs.getString("SndrcvEndHMS" ))); + vo.setSndrcvFileDirName (StringUtil.nvlTrim(rs.getString("SndrcvFileDirName" ))); + vo.setSndrcvFileName (StringUtil.nvlTrim(rs.getString("SndrcvFileName" ))); + vo.setBkupSndrcvFileName (StringUtil.nvlTrim(rs.getString("BkupSndrcvFileName" ))); + vo.setMsgPrcssPrity (rs.getInt("MsgPrcssPrity" )); + vo.setThisMsgAmndrID (StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID" ))); + vo.setThisMsgAmndHMS (StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS" ))); + vo.setMsgQueEtractDmndHMS (StringUtil.nvlTrim(rs.getString("MsgQueEtractDmndHMS"))); + vo.setMsgPrcssStusCd (StringUtil.nvlTrim(rs.getString("MsgPrcssStusCd" ))); + alist.add(vo); + } + + return alist; + + + } catch (DAOException ex) { + throw ex; + } catch (Exception ex) { + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAISSC020"); + throw new DAOException(errMsg); //배치작업 스케쥴 대기목록 테이블에서 수행대상 작업 조회시 오류가 발생하였습니다. + } finally { + disconnect(); + } + } +} diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageManager.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageManager.java new file mode 100644 index 0000000..898f46b --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageManager.java @@ -0,0 +1,753 @@ +package com.eactive.eai.batch.scheduler; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Properties; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager; +import com.eactive.eai.batch.flowController.DemandTargetVO; +import com.eactive.eai.batch.flowController.FlowControllerManager; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityManager; +import com.eactive.eai.batch.rule.dirInfo.BatchJobPriorityVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + + +/** +* 1. 기능 : Manager 클래스 +* 2. 처리 개요 : 스케줄 내용은 메모리에 로딩하지 않는다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class SchedulerMessageManager +{ + + //디버그용 로그유틸 + private static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + //singleton 객체 생성 + private static SchedulerMessageManager instance = new SchedulerMessageManager(); + //singleton 객체 리턴 + public static SchedulerMessageManager getInstance() { + return instance; + } + + //생성자 (다른 클래스에서 new 불가) + private SchedulerMessageManager() {} + + + + + public SchedulerMessageVO getScheduleInfo(String bizCode, String processCode, String osidinstidstCode) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getScheduleInfo(bizCode, processCode, osidinstidstCode); + } + + public SchedulerMessageVO getRecvScheduleInfo(String bizCode, String processCode, String osidinstidstCode) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getRecvScheduleInfo(bizCode, processCode, osidinstidstCode); + } + + public int insertJobToQueue(SchedulerMessageVO info) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.insertJobToQueue(info); + } + + public int deleteJobFromProcessing(String uuid, String subUUID) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.deleteJobFromProcessing(uuid, subUUID); + } + + public int deleteJobFromProcessing() throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.deleteJobFromProcessing(); + } + + public synchronized ArrayList getExecutableJobFromQueue() throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + ArrayList executeList = new ArrayList(); + + + /* + if ( isInProcess() ){ + long interval = System.currentTimeMillis() - lastProcess; + if ( interval > ( 60 * 1000) ){ + setInProcess(false); + }else{ + return executeList; + } + } + */ + + + //1. Job_Processing 테이블에서 모든 연결정보ID 조회 + HashSet hSet = dao.getExecutingSysConnList(); + //logger.info("[스케쥴 핸들러] - 작업 진행목록의 진행중 작업 건수: "+ hSet.size()); + + //2. Job_Queue 테이블에서 수행 할 작업 (현재시간에 걸려있는 작업) 목록 조회 (순서: 우선순위 > 파일생성일 > 스케쥴시작시간) + ArrayList aList = dao.getExecutableJobList(); + //logger.info("[스케쥴 핸들러] - 작업 대기목록의 수행대상 작업 건수: "+ aList.size()); + if (aList.size() == 0) return aList; + + + //------------------------------------------------------------------------------------------------ + // 2번 에서 조회한 모든 작업을 수행하는 것이 아니라 1번에서 사용중인 망상태를 체크하여 수행 가능한 작업만을 걸러준다. + //------------------------------------------------------------------------------------------------ + int prePriority = -1; + String preProcessCode = ""; + //3. Job_Queue 테이블에서 조회한 수행 할 각 작업마다 수행가능 조건 체크 + for (int i=0; i0){//등록된 우선순위 목록이 있으면.. + + priorityList = plist.split(","); + } + + if (priorityList != null && priorityList.length >0){ + + ArrayList palist = jobpmanager.getPriorityData(priorityList[0]); + + if (palist == null || palist.size() <= 0){ + palist = new ArrayList(); + + for (int plistIndex = 0; plistIndex < priorityList.length; plistIndex++){ + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(info.getProcessCode(), priorityList[plistIndex]); + + if (bJobInfo == null){//우선순위 목록에 있는 작업구분이 등록된 Job이 아니면.. 에러를 띄우고 계속 작업을 진행한다. + logger.error("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName() +" ==> 우선순위 목록에 등록된 배치작업 "+ priorityList[plistIndex]+" 이 BJ01에 등록되어 있지 않습니다. 해당 룰을 확인하세요"); + }else { + BatchJobPriorityVO jpvo = new BatchJobPriorityVO(); + + //기본정보를 설정한다. + jpvo.setBizCode(priorityList[plistIndex]); + jpvo.setOsdCd(info.getInstitutionCode()); + jpvo.setOsdName(info.getInstitutionName()); + jpvo.setProcessCd(info.getProcessCode()); + jpvo.setProcessName(info.getProcessName()); + + palist.add(plistIndex, jpvo); + } + } + + + jobpmanager.addJobPriorityData(priorityList[0], palist); + } + + boolean isresult = jobpmanager.isExecutePrePriority(priorityList[0], info.getBizCode()); + + if (!isresult){//등록된 우선순위 작업 목록중 선행 작업이 실행되지 않았으면.. + logger.info("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName() +" ==> 해당 업무의 선행 우선순위 작업이 수행되지 않아, 다음 Timer Event 시 다시 확인합니다."); + continue; + } + } + + int priority = info.getPriority(); + String processCode = info.getProcessCode(); + + if (prePriority < 0){ + prePriority = priority; + preProcessCode = processCode; + } +// int prePriority = Integer.parseInt(preStrPriority); +// int priority = Integer.parseInt(strpriority); + if (preProcessCode.equals(processCode)){ + if (prePriority != priority){ + logger.info("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName() +" ==> 해당 업무의 선행 우선순위 작업이 먼저 수행합니다."); + continue; + } + + ArrayList exelist = dao.getExecutJobList(info.getProcessCode()); + + if (exelist != null && exelist.size() > 0){//현재 실행중인 작업이 있으면.. + SchedulerMessageVO emessage = (SchedulerMessageVO)exelist.get(0);//첫번째 우선순위 작업을 가져온다.. + int epo = 0; + try{ + epo = emessage.getPriority(); + }catch (Exception ex){ + logger.error("스케쥴 핸들러] "+info.getProcessName() +" 업무의 현재 작업진행큐의 우선순위를 조회하는데 에러가 발생했습니다. - ["+epo+"]"+ex.getMessage()); + } + if (epo < priority){ + logger.info("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName() +" ==> 해당 업무의 선행 우선순위 작업이 실행큐에서 처리중입니다. 다음 Timer Event 시 다시 확인합니다. "); + continue; + } + } + + + if (priorityList != null && priorityList.length >0){//우선순위 목록이 등록되어 있으면 실행목록 변경. + + String dataCountFlag = telegramInfo.getProperty("file.count.flag"); + if(dataCountFlag != null && dataCountFlag.length() > 0 && "Y".equals(dataCountFlag)){//flag가 설정되어 있으면.. + + String fileDir = info.getFilePath(); + String fileNm = info.getRenamedFileName(); + + if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) { + fileDir = fileDir + File.separator; + } + + String fileName = fileDir + fileNm; + File file = new File(fileName); + if (!file.exists()) // 파일이 없으면 리턴 False + { + logger.error("스케쥴 핸들러] 데이터 파일 갯수를 확인하기 위해 파일 생성시 오류가 발생했습니다. ["+fileName+"] - 이후 작업은 에러를 무시하고 진행됩니다."); + }else { + String dataCountPos = telegramInfo.getProperty("count.pos"); + String dataCountLen = telegramInfo.getProperty("count.length"); + String dataBizCode = telegramInfo.getProperty("file.count.bizcode"); + + BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(info.getProcessCode(), dataBizCode); + + if (bJobInfo == null){//데이터 파일로 등록된 작업구분이 작업구분이 등록된 Job이 아니면.. 에러를 띄우고 계속 작업을 진행한다. + logger.error("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName() +" ==> 우선순위 목록에 등록된 배치작업 "+dataBizCode+" 이 BJ01에 등록되어 있지 않습니다. 해당 룰을 확인하세요"); + }else { + BatchJobPriorityVO ldatavo = jobpmanager.getPriorityDatabyBizCode(priorityList[0], dataBizCode); + int executeDataCount = 0; + + if (ldatavo != null){ + executeDataCount = ldatavo.getDataCount(); + }else {// 20250910 npe 경고 아래 추가 + logger.error("[스케쥴 핸들러] getPriorityDatabyBizCode ERROR "); + throw new Exception("[스케쥴 핸들러] getPriorityDatabyBizCode ERROR "); + } + + int countPos = Integer.parseInt(dataCountPos); + int countLen = Integer.parseInt(dataCountLen); + byte[] countBuffer = new byte[countLen]; + + BufferedInputStream bis = null; + try { + bis = new BufferedInputStream (new FileInputStream(file)); + bis.skip(countPos); + bis.read(countBuffer); + } catch (Exception e) { + logger.error(e.getMessage(), e); + }finally{ + if ( bis != null ) + bis.close(); + } + + int countInfo = Integer.parseInt(new String(countBuffer)); + //파일 수 확인을 위해 정보 저장 + ldatavo.setDataCountInfo(countInfo);// 20250910 npe 경고 + + + if (executeDataCount < countInfo){ + logger.info("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+" | "+ info.getFileName() +" | 전송되어야할 데이터파일 수 ["+ countInfo +"]보다 전송된 파일수 [ "+ executeDataCount+"]가 작아서 다음 Timer Event 시 다시 확인합니다. "); + continue; //실행된 데이터 파일이 모두 전송 안되었으면... + } + } + } + } + + + } + String delay = telegramInfo.getProperty("delaysec"); + if (delay != null && delay.length() > 0){ + int delaysec = Integer.parseInt(delay); + + if (delaysec > 0){ + if (priorityList != null && priorityList.length >0){//우선순위 플래그가 Y이면서 우선순위 목록이 있으면.. + + BatchJobPriorityVO lastvo = jobpmanager.getPriorityDatabyBizCode(priorityList[0], info.getBizCode()); + + if (lastvo != null){ + long lastcall = lastvo.getFirstCallForDelayTime(); + if (lastcall == 0){ + lastvo.setFirstCallForDelayTime(System.currentTimeMillis()); //우선순위 작업이 처음 호출된 시간을 저장한다. + continue; + }else{ + int time = (int)((System.currentTimeMillis() - lastcall)/1000); + if (delaysec > time){//설정된 지연시간보다 첫 호출 후 경과시간이 작으면 작업을 진행하지 않는다. + logger.info("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+" | "+ info.getFileName() +" | "+ delaysec +"보다 경과시간 "+ time+"이 작아서 다음 Timer Event 시 다시 확인합니다. "); + continue; + }else {//다음 지연시간 설정을 위해 타임스탬프 초기화.. + lastvo.setFirstCallForDelayTime(System.currentTimeMillis()); //우선순위 작업이 처음 호출된 시간을 저장한다. + } + } + } + } + else{//우선순위 플래그가 Y이면서 우선순위 목록이 없으면.. + if (jobpmanager != null){ + + if (jobpmanager.hasDelaySec(info.getUUID())){ + long lastcall = jobpmanager.getDelaySec(info.getUUID()); + + if (lastcall >= 0){ + + int time = (int)((System.currentTimeMillis() - lastcall)/1000); + if (delaysec > time){//설정된 지연시간보다 첫 호출 후 경과시간이 작으면 작업을 진행하지 않는다. + logger.info("[스케쥴 핸들러] * 대기작업정보 Set DelaySec ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+" | "+ info.getFileName() +" | "+ delaysec +"보다 경과시간 "+ time+"이 작아서 다음 Timer Event 시 다시 확인합니다. "); + continue; + }else {//다음 지연시간 설정을 위해 타임스탬프 초기화.. + jobpmanager.removeDelaySec(info.getUUID()); + } + + } + }else {//초기화.. + jobpmanager.setDelaySec(info.getUUID(), System.currentTimeMillis()); + continue; + } + } + + } + } + } + }else{//업무구분이 달라지면 이전 우선순위값 초기화 + prePriority = info.getPriority(); + preProcessCode = info.getProcessCode(); + } + }else { //우선순위가 없는 작업중 delay time이 설정된 작업 처리.. + if (telegramInfo != null ){ + String delay = telegramInfo.getProperty("delaysec"); + if (delay != null && delay.length() > 0){ + int delaysec = Integer.parseInt(delay); + + if (delaysec > 0){ + + if (jobpmanager != null){ + + if (jobpmanager.hasDelaySec(info.getUUID())){ + long lastcall = jobpmanager.getDelaySec(info.getUUID()); + + if (lastcall > 0){ + + int time = (int)((System.currentTimeMillis() - lastcall)/1000); + if (delaysec > time){//설정된 지연시간보다 첫 호출 후 경과시간이 작으면 작업을 진행하지 않는다. + logger.info("[스케쥴 핸들러] * 대기작업정보 Set DelaySec ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+" | "+ info.getFileName() +" | "+ delaysec +"보다 경과시간 "+ time+"이 작아서 다음 Timer Event 시 다시 확인합니다. "); + continue; + }else {//다음 지연시간 설정을 위해 타임스탬프 초기화.. + jobpmanager.removeDelaySec(info.getUUID()); + } + + } + }else {//초기화.. + jobpmanager.setDelaySec(info.getUUID(), System.currentTimeMillis()); + continue; + } + } + } + } + } + + } + }catch (Exception pex){ + logger.error("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFileName() +" 우선순위 작업 처리시 에러가 발생했습니다. 이후 작업은 무시하고 진행됩니다. - "+pex.getMessage()); + } + }catch (Exception e){ + } +// 2009.8.13 우선순위 작업이 설정된 업무에 우선순위가 다른 작업이 동시에 들어오면 한번의 타이머 이벤트에 같은 우선순위의 작업만 진행함. +// end - by kscheon + + //logger.debug("[스케쥴 핸들러] ★★★ 영업일 체크 안함 ("+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getScheduleCode()+") ★★★"); + //3-1. 해당 작업의 대외기관 연결정보 조회 + DemandTargetVO[] sysConnList = FlowControllerManager.getInstance().getRemoteHostInfo(info.getProcessCode(), info.getInstitutionCode()); + if (sysConnList == null || sysConnList.length == 0) { + //logger.info("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName() +" ==> 해당 작업의 요구송수신 연결정보가 존재하지 않음 !! ★★ 연결정보 체크 필요 ★★"); + continue; + } + + //3-2. 사용하지 않는 대외기관 연결정보ID 할당 + int j=0; + for (j=0; j 해당 작업의 연결정보가 모두 사용중 임 !! -> 다음 Timer Event 시 연결정보 Release 된 경우 수행됨."); + continue; + } + logger.info("[스케쥴 핸들러] * 대기작업정보 ["+ (i+1) +"]: "+ info.getUUID() +" | "+ info.getProcessCode() +" | "+ info.getInstitutionCode() +" | "+ info.getFilePath() +" | "+ info.getFileName() +" ==> 사용 가능한 연결정보 설정됨 !! ("+ sysConnList[j].getSystemConnCode() +" | "+ sysConnList[j].getIpAddress() +" | "+ sysConnList[j].getPortNumber() +" | "+ sysConnList[j].getTimeoutInterval() +")"); + executeList.add(info); + + //setInProcess(true); + + } + + return executeList; + } + + public int moveJobQueueToHandle(SchedulerMessageVO info) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + ArrayList alist = new ArrayList(); + alist.add(info); + return dao.moveExecutableJodToProcessing(alist); + } + + public int moveJobQueueToHandleWithNewID(SchedulerMessageVO info, String strUUID, String strSubUUID) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.moveExecutableJodToProcessingWithNewID(info,strUUID,strSubUUID); + } + + public ArrayList getExecutableRecvScheduleList() throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getExecutableRecvScheduleList(); + } + + public SchedulerMessageVO getExecutableJobFromQueue( String processCode, String institutionCode) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + + // Job_Queue 테이블에서 수행 할 작업 (현재시간에 걸려있는 작업) 목록 조회 (순서: 우선순위 > 파일생성일 > 스케쥴시작시간) + ArrayList aList = dao.getExecutableJobList(); + //logger.info("[스케쥴 핸들러]A - 작업 대기목록의 수행대상 작업 건수: "+ aList.size()); + if (aList.size() == 0) return null; + + for (int i=0; i 파일생성일 > 스케쥴시작시간) + ArrayList aList = dao.getExecutableJobListWithSuspendedJob(); + //logger.info("[스케쥴 핸들러]A - 작업 대기목록의 수행대상 작업 건수: "+ aList.size()); + if (aList.size() == 0) return null; + + for (int i=0; i 파일생성일 > 스케쥴시작시간) + ArrayList aList = dao.getExecutableJobListWithSuspendedJob(); + //logger.info("[스케쥴 핸들러]A - 작업 대기목록의 수행대상 작업 건수: "+ aList.size()); + if (aList.size() == 0) return null; + + for (int i=0; i 파일생성일 > 스케쥴시작시간) + ArrayList aList = dao.getExecutableJobListWithSuspendedJob(); + //logger.info("[스케쥴 핸들러]A - 작업 대기목록의 수행대상 작업 건수: "+ aList.size()); + if (aList.size() == 0) return null; + + for (int i=0; i 배치업무유형코드(ProcessCode) 와 대외기관코드 (InstitutionCode) 로 계산. + String strPathName = BatchDirUtil.getResponseRealDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + + StringBuffer sb = new StringBuffer(); + sb.append(info.getProcessCode()); + sb.append("/"); + sb.append(info.getInstitutionCode()); + strPathName = strPathName + sb.toString(); + + info.setFilePath(strPathName); + batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName); + + + //3. UUID 설정 및 스케쥴 송수신 시각 설정 + info.setUUID (batchMsgDoc.getBatchMsg().getHeader().getUUID()); + info.setSubUUID (batchMsgDoc.getBatchMsg().getBody().getSubUUID()); + int startDelay = info.getStartDelayDays(); + int endDelay = info.getEndDelayDays(); + + if (!info.getStartTime().equals("")) info.setStartTime(DatetimeUtil.getDayAddedDate( DatetimeUtil.getCurrentDate(), startDelay ) + info.getStartTime() +"00" + "000"); + if (!info.getEndTime() .equals("")) info.setEndTime (DatetimeUtil.getDayAddedDate( DatetimeUtil.getCurrentDate(), endDelay ) + info.getEndTime() +"00" + "000"); + + //4. Job_Queue 테이블에 등록 + logger.info("[SchedulerMessageManager:requestRecieveJob] ========================================================================="); + logger.info("[SchedulerMessageManager:requestRecieveJob] ■ 요구수신 스케쥴 정보를 Job_Queue 테이블에 추가......"); + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(info); + logger.info("[SchedulerMessageManager:requestRecieveJob] ==> 배치 Job_Queue 테이블 INSERT 건수: "+ resultCnt); + logger.info("[SchedulerMessageManager:requestRecieveJob] ========================================================================="); + + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setStartLog(batchMsgDoc); + + return resultCnt; + + } + public int requestRecieveJob(String scheduleCode, String reqYYYYMMDD) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + SchedulerMessageVO info = dao.getScheduleByScheduleCode(scheduleCode); + info.setFileName(info.getBizCode() + reqYYYYMMDD); + return requestRecieveJob( info ); + } + + public SchedulerMessageVO getReqRecvSchedule(String scheduleId) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getScheduleInfo(scheduleId); + } + + + public SchedulerMessageVO getReqSendSchedule(String scheduleId) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getReqSendScheduleInfo(scheduleId); + } + +// public synchronized void setInProcess( boolean flag ){ +// inProcess = flag; +// if ( inProcess ) lastProcess = System.currentTimeMillis(); +// } + + + public JobMasterLogVO getJobLogByKey(String uuid,String subUuid) throws Exception { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getJobLogByKey(uuid, subUuid); + } + + public JobFileTransferVO getFileLogList(String uuid,String subUuid, String fileName) throws Exception { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getFileLogList(uuid, subUuid, fileName); + } + + public ArrayList getScheduledJobList(ArrayList basisList ) throws Exception { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getScheduledJobList(basisList); + } + + public ArrayList getProcessinbgJobList() throws Exception { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getProcessinbgJobList(); + + } + + public int deleteJobFromProcessing(String uuid) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.deleteJobFromProcessing(uuid); + } + + +} diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQuery.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQuery.java new file mode 100644 index 0000000..2b1f409 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQuery.java @@ -0,0 +1,628 @@ +package com.eactive.eai.batch.scheduler; + +import com.eactive.eai.common.dao.Keys; + +/** +* 1. 기능 : SchedulerMessageDAO에서 사용하는 SQL Query를 정의한 상수 인터페이스 +* 2. 처리 개요 : SchedulerMessageDAO에서 사용하는 SQL Query를 정의한다. +* * +* 3. 주의사항 +* - JobProcessing 테이블(TSEAIBS04)의 처리구분 필드(MsgPrcssStusCd)는 다음과 같이 태그를 정의한다. +* I(영문 대문자): JobQueue 테이블에서 JobProcessing 테이블로 처음 전달된 레코드(insert default value) +* S: F/C로 전달된 레코드, 즉 진행중임을 나타낸다. +* C: 사용자에 의해서 진행이 중지 요청된 레코드이다. 즉, 완전히 해당 프로세스가 중지되었는지 알 수 없다. +* T: F/C에서 정상 종료된 레코드이다. +* E: F/C에서 진행 중에 에러로 종료된 레코드이다. +* +* @author :송영국 +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : 2006.01.10 +*/ +public interface SchedulerMessageQuery +{ + //1. File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회 + //order by 우선순위에 의한 맨 처음 한건을 수행할 스케쥴로 설정함 + public static String SELECT_SEND_SCHEDULE_BY_BIZCODE = + "SELECT A.BjobMsgScheID ,\n" + + " A.BjobMsgDstcd ,\n" + + " B.BjobTranDstcdName,\n" + + " A.SndrcvStartHMS ,\n" + + " A.SndrcvEndHMS ,\n" + + " B.BjobBzwkDstcd ,\n" + + " A.BjobPtrnDstcd ,\n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " B.MsgPrcssPrity ,\n" + + " CASE WHEN ( TO_CHAR(SYSDATE,'HH24MI') >= A.SndrcvStartHMS AND \n" + + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " END FetchPriority ,\n" + + " A.HoldyPrcssDstcd ,\n" + + " A.StartDlayNoday ,\n" + + " A.EndDlayNoday \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND B.BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ? \n" + + "AND B.BjobTranDstcdName = ? \n" + + "AND A.BjobPtrnDstcd = 'RS'\n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "ORDER BY B.MsgPrcssPrity, FetchPriority, A.SndrcvStartHMS, A.SndrcvEndHMS, B.BjobTranDstcdName"; + + //1-1. File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회 + //order by 우선순위에 의한 맨 처음 한건을 수행할 스케쥴로 설정함 + public static String SELECT_RECV_SCHEDULE_BY_BIZCODE = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " B.MsgPrcssPrity , \n" + + " CASE WHEN ( TO_CHAR(SYSDATE,'HH24MI') >= A.SndrcvStartHMS AND \n" + + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " END FetchPriority , \n" + + " A.HoldyPrcssDstcd , \n" + + " A.StartDlayNoday , \n" + + " A.EndDlayNoday \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd\n" + + "AND B.BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ? \n" + + "AND B.BjobTranDstcdName = ? \n" + + "AND A.BjobPtrnDstcd = 'RR' \n" + //+ "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "ORDER BY B.MsgPrcssPrity, FetchPriority, A.SndrcvStartHMS, A.SndrcvEndHMS, B.BjobTranDstcdName"; + + //2. 위 1번 쿼리에 의한 스케쥴 정보를 작업대기목록 테이블에 INSERT + public static final String INSERT_JOB_QUEUE = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBS03 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID , TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , BjobPtrnDstcd , SndrcvStartHMS , \n" + + " SndrcvEndHMS , SndrcvFileDirName, SndrcvFileName , BkupSndrcvFileName , \n" + + " MsgPrcssPrity , HdrInfoName , ThisMsgAmndrID , ThisMsgAmndHMS ) \n" + + "VALUES ( \n" + + " ? , ? , ? , TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') , ? , \n" + + " ? , ? , ? , ? , \n" + + " ? , ? , ? , ? , \n" + + " ? , ? , ? , ? )"; + + //3. Timer Event 발생시 작업대기목록 테이블에서 수행할(현재시간에 걸리는) 전체 작업목록을 조회 + public static final String SELECT_EXECUTABLE_JOB_FROM_QUEUE = + "SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobDmndMsgCretnHMS, \n" + + " A.BjobMsgScheID , \n" + + " A.BjobBzwkDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " A.SndrcvFileDirName , \n" + + " A.SndrcvFileName , \n" + + " A.BkupSndrcvFileName , \n" + + " A.MsgPrcssPrity , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS , \n" + + " C.BjobMsgDstcd , \n" + + " C.BjobTranDstcdName , \n" + + " D.OsidInstiName , \n" + + " D.TelgmBlckSize , \n" + + " D.TelgmSernoSize , \n" + + " D.TelgmPcketSize , \n" + + " CASE A.BjobPtrnDstcd WHEN 'RS' THEN D.SendPrcssRuleCd \n" + + " WHEN 'RR' THEN D.RecvPrcssRuleCd END AS FlowRuleCode, \n" + + " E.BjobBzwkName , \n" + + " A.HdrInfoName , \n" + + " B.HoldyPrcssDstcd , \n" + + " B.StartDlayNoday , \n" + + " B.EndDlayNoday , \n" + + " B.RqstRecvReTralUseYn \n" //2009.6.16 요구송신의 경우에도 재시도여부 플래그로 사용. by kscheon + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 E \n" + + "WHERE A.BjobMsgScheID = B.BjobMsgScheID \n" + + "AND B.BjobMsgDstcd = C.BjobMsgDstcd \n" + + "AND A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd)) \n" + + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" + + "AND A.MsgPrcssPrity > 0 \n" //--suspend 스케쥴 제외 + + "AND A.SndrcvStartHMS <= TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" + + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; + + //3. Timer Event 발생시 작업대기목록 테이블에서 수행할(현재시간에 걸리는) 전체 작업목록을 조회 + public static final String SELECT_EXECUTABLE_JOB_FROM_QUEUE_WITH_SUSPENDED_JOB = + "SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobDmndMsgCretnHMS, \n" + + " A.BjobMsgScheID , \n" + + " A.BjobBzwkDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " A.SndrcvFileDirName , \n" + + " A.SndrcvFileName , \n" + + " A.BkupSndrcvFileName , \n" + + " A.MsgPrcssPrity , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS , \n" + + " C.BjobMsgDstcd , \n" + + " C.BjobTranDstcdName , \n" + + " D.OsidInstiName , \n" + + " D.TelgmBlckSize , \n" + + " D.TelgmSernoSize , \n" + + " D.TelgmPcketSize , \n" + + " CASE A.BjobPtrnDstcd WHEN 'RS' THEN D.SendPrcssRuleCd \n" + + " WHEN 'RR' THEN D.RecvPrcssRuleCd END AS FlowRuleCode, \n" + + " E.BjobBzwkName , \n" + + " A.HdrInfoName , \n" + + " B.HoldyPrcssDstcd , \n" + + " B.StartDlayNoday , \n" + + " B.EndDlayNoday , \n" + + " B.RqstRecvReTralUseYn \n" //2009.6.16 요구송신의 경우에도 재시도여부 플래그로 사용. by kscheon + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 E \n" + + "WHERE A.BjobMsgScheID = B.BjobMsgScheID \n" + + "AND B.BjobMsgDstcd = C.BjobMsgDstcd \n" + + "AND A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd)) \n" + + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" +// + "AND A.MsgPrcssPrity > '0' \n" //--suspend 스케쥴 제외 + + "AND A.SndrcvStartHMS <= TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" + + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; + + + //4. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 연결정보가 현재 사용중인지 + //체크하기 위해 작업진행목록 테이블에서 전체 연결정보를 조회 + public static final String SELECT_EXECUTING_SYSTEMCONNID_FROM_PROCESSING = + "SELECT SysLnkgDstcd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE MsgPrcssStusCd IN ('S','I','C')"; + +// 4-1. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 앞선 우선순위 작업이 수행중인지 확인하기 위한 쿼리 + //2009.8.14 by kscheon + public static final String SELECT_EXECUTING_JOB_FROM_PROCESSING = + "SELECT BjobBzwkDstcd, MsgPrcssPrity \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE BjobBzwkDstcd = ?\n" + + "AND MsgPrcssStusCd IN ('S','I','C') \n" + + "ORDER BY MsgPrcssPrity "; + + //5. 위 3번 쿼리의 결과 작업중 연결정보의 체크에 의해 걸러진 작업들을 제외한 모든 작업들을 + //작업진행목록 테이블로 이동. 이동 후 각각의 작업을 요구송수신 JPD 호출함. + public static final String MOVE_JOB_FROM_QUEUE_TO_PROCESSING = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBS04 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID, TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , SysLnkgDstcd , BjobPtrnDstcd , \n" + + " SndrcvStartHMS , SndrcvEndHMS , SndrcvFileDirName , SndrcvFileName, \n" + + " BkupSndrcvFileName , MsgPrcssPrity , ThisMsgAmndrID , ThisMsgAmndHMS, \n" + + " MsgQueEtractDmndHMS, MsgPrcssStusCd ) \n" + + "SELECT \n" + + " BjobDmndMsgID , BjobDmndSubMsgID, TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , CAST ( ? AS CHAR(12) ), BjobPtrnDstcd , \n" + + " SndrcvStartHMS , SndrcvEndHMS , SndrcvFileDirName , SndrcvFileName, \n" + + " BkupSndrcvFileName , MsgPrcssPrity , ThisMsgAmndrID , ThisMsgAmndHMS, \n" + + " TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3'), 'I' \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? "; + + //5-1. 위 5번 쿼리를 분리 하여 큐에서 잡을 읽음. + public static final String SELCT_JOB_FROM_QUEUE = + "SELECT TelgmReTralCnt ,\n" + + " BjobDmndMsgCretnHMS,\n" + + " BjobMsgScheID ,\n" + + " BjobBzwkDstcd ,\n" + + " LTRIM(RTRIM(OsidInstiDstcd)) AS OsidInstiDstcd ,\n" + + " BjobPtrnDstcd ,\n" + + " SndrcvStartHMS ,\n" + + " SndrcvEndHMS ,\n" + + " SndrcvFileDirName ,\n" + + " SndrcvFileName ,\n" + + " BkupSndrcvFileName ,\n" + + " MsgPrcssPrity ,\n" + + " ThisMsgAmndrID ,\n" + + " ThisMsgAmndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? "; + + //5-2. 위 5번 쿼리를 분리 하여 프로세싱 테이블에 잡을 INSERT함 + //작업진행목록 테이블로 이동. 이동 후 각각의 작업을 요구송수신 JPD 호출함. + public static final String UPDATE_PROCESSING_WITH_NEW_JOB = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBS04\n" + + "SET TelgmReTralCnt = NVL( ?, TelgmReTralCnt ),\n" + + " BjobDmndMsgCretnHMS = NVL( ?, BjobDmndMsgCretnHMS),\n" + + " BjobMsgScheID = NVL( ?, BjobMsgScheID ),\n" + + " BjobBzwkDstcd = NVL( ?, BjobBzwkDstcd ),\n" + + " OsidInstiDstcd = NVL( ?, OsidInstiDstcd ),\n" + + " BjobPtrnDstcd = NVL( ?, BjobPtrnDstcd ),\n" + + " SndrcvStartHMS = NVL( ?, SndrcvStartHMS ),\n" + + " SndrcvEndHMS = NVL( ?, SndrcvEndHMS ),\n" + + " SndrcvFileDirName = NVL( ?, SndrcvFileDirName ),\n" + + " SndrcvFileName = NVL( ?, SndrcvFileName ),\n" + + " BkupSndrcvFileName = NVL( ?, BkupSndrcvFileName ),\n" + + " MsgPrcssPrity = NVL( ?, MsgPrcssPrity ),\n" + + " ThisMsgAmndrID = NVL( ?, ThisMsgAmndrID ),\n" + + " ThisMsgAmndHMS = NVL( ?, ThisMsgAmndHMS ),\n" + + " MsgQueEtractDmndHMS = TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3'),\n" + + " MsgPrcssStusCd = 'I'\n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ?"; + + //6. 위 5번 쿼리 후 이동한 작업을 대기목록에서 DELETE + public static final String DELETE_JOB_FROM_QUEUE = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? "; + + //7. 요구송수신 JPD에서 해당 작업 종료 및 오류 후 해당 작업을 Job_Processing 테이블에서 DELETE + public static final String DELETE_JOB_FROM_PROCESSING = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? "; + + //9. 요구수신 Timer Event 발생시 스케쥴정보 테이블에서 현재시간에 걸리는 요구수신 스케쥴 정보 조회 + //단, 해당 스케쥴정보는 대기목록 또는 진행목록에 존재하지 않아야 함 + //Master로그 테이블에서 해당 날자의 요구수신 스케쥴ID의 파일 수신완료 건이 존재하지 말아야 함 + public static String SELECT_EXECUTABLE_RECV_SCHEDULE_LIST = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.HoldyPrcssDstcd , \n" + + " A.RpttYn , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd , \n" + + " A.RqstRecvReTralUseYn , \n" + + " A.RqstRecvReTralCnt , \n" + + " A.RqstRecvReTralIntvalTtm, \n" + + " NVL(C.RecvFileEndCnt , 0) RecvFileEndCnt , \n" + + " NVL(C.RecvFileFailCnt, 0) RecvFileFailCnt, \n" + + " NVL(C.RecentExecTime , '') RecentExecTime \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + + " SUM(CASE TranPrcssDstcd WHEN 'T' THEN 1 " + + " ELSE 0 END) AS RecvFileEndCnt ,\n" // --파일전송 완료 건수 + + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " + + " ELSE 1 END) AS RecvFileFailCnt,\n" // --파일전송 미완료 건수 + + " MAX(BjobDmndMsgCretnHMS) RecentExecTime \n" // --최근 수행 시간 + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + " WHERE BjobPtrnDstcd = 'RR' \n" // --요구수신만 + + " AND BjobDmndMsgCretnHMS LIKE TO_CHAR(SYSDATE,'YYYYMMDD')||'%' \n" + + " GROUP BY BjobMsgScheID ) C " + + "on A.BjobMsgScheID = C.BjobMsgScheID \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND A.BjobPtrnDstcd = 'RR' --요구수신만 \n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "AND A.SndrcvStartHMS <= TO_CHAR(SYSDATE,'HH24MI') \n" + + "AND NVL(RTRIM(A.SndrcvEndHMS), '9999') > TO_CHAR(SYSDATE,'HH24MI') \n" + + "AND NOT EXISTS ( SELECT X.BjobMsgScheID \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS03 X \n" //--대기목록 테이블에 존재하지 않고 + + " WHERE X.BjobMsgScheID = A.BjobMsgScheID \n" + + " AND X.SndrcvEndHMS >= TO_CHAR(SYSDATE,'YYYYMMDD') ) \n" //--미래의 스케쥴이 + + "AND NOT EXISTS ( SELECT Y.BjobMsgScheID \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS04 Y \n" //--진행목록 테이블에 존재하지 않고 + + " WHERE Y.BjobMsgScheID = A.BjobMsgScheID ) \n" + + "ORDER BY A.SndrcvStartHMS, B.BjobTranDstcdName, A.SndrcvEndHMS"; + + + //10. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구수신) + public static String SELECT_SEND_SCHEDULE_BY_SCHEDULEID = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd ,\n" + + " A.RqstRecvReTralCnt ,\n" + + " A.RqstRecvReTralUseYn ,\n" + + " A.RqstRecvReTralIntvalTtm \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND A.BjobMsgScheID = ? \n" + + "AND A.BjobPtrnDstcd = 'RR' \n" //--요구수신만 + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n"; + + //12. 주어진 스케쥴 코드로 해당하는 스케쥴 정보를 구한다. + public static final String SELECT_SCHEDULE_BY_CODE = + "SELECT B.BjobBzwkDstcd, \n" + + " C.BjobBzwkName, \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " D.OsidInstiName, \n" + + " A.BjobMsgDstcd, \n" + + " A.BjobMsgScheID, \n" + + " A.BjobPtrnDstcd, \n" + + " B.BjobTranDstcdName, \n" + + " A.RqstRecvReTralCnt, \n" + + " A.SndrcvStartHMS, \n" + + " A.SndrcvEndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + " AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + " AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + " AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd )) \n" + + " AND LTRIM(RTRIM(A.BjobMsgScheID)) = ? \n"; + + + + +// 13. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구송신) + public static String SELECT_REQ_SEND_SCHEDULE_BY_SCHEDULEID = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.RqstRecvReTralUseYn , \n" + + " A.RqstRecvReTralIntvalTtm , \n" + + " A.RqstRecvReTralCnt , \n" + + " B.MsgPrcssPrity , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd, \n" + + " NVL(C.RecvFileFailCnt, 0) AS RecvFileFailCnt \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " + + " ELSE 1 END) AS RecvFileFailCnt\n" //--파일전송 미완료 건수 + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + " WHERE BjobPtrnDstcd = 'RS' \n" //--요구송신만 + + " AND BjobDmndMsgCretnHMS LIKE TO_CHAR(SYSDATE,'YYYYMMDD')||'%' \n" + + " GROUP BY BjobMsgScheID ) C \n" + + " on A.BjobMsgScheID = C.BjobMsgScheID \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND RTRIM(A.BjobMsgScheID) = ? \n" + + "AND A.BjobPtrnDstcd = 'RS'\n" //--요구송신만 + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n"; + + //위 5번 쿼리 후 이전 로그 테이블에서 DELETE + public static final String DELETE_JOB_FROM_LOGMASTER = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + "WHERE BjobDmndMsgID = ?"; + //위 5번 쿼리 후 이전 로그 테이블에서 DELETE + public static final String DELETE_JOB_FROM_LOGDETAIL = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBJ04 \n" + + "WHERE BjobDmndMsgID = ?"; + + /** + * BATCH작업 메시지일정 ID를 조회하는 쿼리 + */ + public static final String GET_BJOBMSGSCHEID = + " SELECT BjobBzwkDstcd|| ? ||BjobTranDstcdName|| " + + " ( " + + " SELECT " + + " CASE LENGTH(TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1)) " + + " WHEN 1 " + + " THEN '00' || TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) " + + " WHEN 2 " + + " THEN '0' || TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) " + + " WHEN 3 " + + " THEN TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) " + + " END " + + " FROM "+Keys.TABLE_OWNER +"TSEAIBS01 " + + " WHERE BjobMsgDstcd = ? " + + " ) LEFTCODE " + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ01 " + + " WHERE BjobMsgDstcd = ? "; + + /** + * BATCH작업 일정 정보를 등록하는 쿼리 + */ + public static final String ADD_JOB_SCH_INFO = + "INSERT INTO "+Keys.TABLE_OWNER +"TSEAIBS01 ( " + + " BjobMsgScheID " + + " ,BjobMsgDstcd " + + " ,BjobPtrnDstcd " + + " ,OsidInstiDstcd " + + " ,SndrcvStartHMS " + + " ,SndrcvEndHMS " + + " ,MsgSndrID " + + " ,ScheFrstRegiHMS " + + " ,RqstRecvReTralCnt " + + " ,RqstRecvReTralUseYn " + + " ,RqstRecvReTralIntvalTtm " + + " ,RqstRecvFileStorgDirName " + + " ,StartDlayNoday " + + " ,EndDlayNoday " + + " ,HoldyPrcssDstcd " + + " ,RpttYn " + + " ,ThisMsgUseYn " + + " ,ThisMsgScheDesc " + + " ,ThisMsgRegsntID " + + " ,ThisMsgRegiHMS " + + " ,ThisMsgAmndrID " + + " ,ThisMsgAmndHMS ) " + + " values ( " + + " ? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ,? " + + " ,? " + + " ,? " + + " ,' ' " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,' ' " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ) "; + + /** + * BATCH작업 일정 정보를 등록하는 쿼리 + */ + public static final String SELECT_LOG_MASTER_BY_KEYS = + " SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobMsgScheID , \n" + + " A.BjobDmndMsgCretnHMS , \n" + + " A.BjobBzwkDstcd , \n" + + " C.BjobBzwkName , \n" + + " A.OsidInstiDstcd , \n" + + " D.OsidInstiName , \n" + + " A.BjobPtrnDstcd , \n" + + " A.MsgSndrID , \n" + + " A.MsgSndrName , \n" + + " A.SysLnkgDstcd , \n" + + " A.LnkgIPInfoName , \n" + + " A.FlowRuleCd , \n" + + " A.EAISevrInstncName , \n" + + " A.TranStartHMS , \n" + + " A.TranEndHMS , \n" + + " A.TranPrcssDstcd , \n" + + " A.EAIObstclOccurCausCtnt, \n" + + " A.ObstclPrcsrID , \n" + + " A.ObstclPrcssHMS \n" + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ03 A\n" + + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ02 C ON A.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ06 D ON A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + " AND A.OsidInstiDstcd = D.OsidInstiDstcd \n" + + " WHERE A.BjobDmndMsgID LIKE ? ||'%' \n" + + " AND A.BjobDmndSubMsgID LIKE ? ||'%' \n"; + + public static final String SELECT_FILE_LOG_BY_KEYS = + "SELECT RqstRecvFileStorgDirName ,\n" + + " BkupSndrcvFileName ,\n" + + " BjobTranDstcdName ,\n" + + " HdrInfoName \n" + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ08 \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND SndrcvFileName = ? \n"; + +// public static final String SELECT_STAGE_LOGS_BY_KEYS = +// "SELECT B.BjobDmndMsgID , \n" +// + " B.BjobDmndSubMsgID , \n" +// + " B.BjobStgeID , \n" +// + " B.PrcssStgeDstcd , \n" +// + " B.BjobRuleCd , \n" +// + " C.FlowRulePtrnDesc , \n" +// + " B.BjobStgeCd , \n" +// + " D.BjobStgeFlxblCndnDesc , \n" +// + " B.BjobStgeSerno , \n" +// + " B.BjobStgePtrnName , \n" +// + " B.BjobFlowCmpoClsName , \n" +// + " B.TelgmDcsnID , \n" +// + " B.TelgmDcsnClsName , \n" +// + " B.TelgmDcsnMsgCd , \n" +// + " B.ThisStgeTelgmID , \n" +// + " B.ThisStgeClsName , \n" +// + " B.ThisStgeMsgCd , \n" +// + " B.TelgmPertypCdValCtnt , \n" +// + " B.TelgmDstcdValCtnt , \n" +// + " B.TelgmMgtCdValCtnt , \n" +// + " B.RspnsCdValCtnt , \n" +// + " B.BjobNodeCasNo , \n" +// + " B.BjobMsgDstcd , \n" +// + " E.BjobMsgDsticName , \n" +// + " B.BjobTranDstcdName , \n" +// + " B.RqstRecvFileStorgDirName, \n" +// + " B.SndrcvFileName , \n" +// + " B.BkupSndrcvFileName , \n" +// + " B.ThisStgeStartHMS , \n" +// + " B.ThisStgeEndHMS , \n" +// + " B.ThisStgePrcssRsultCd , \n" +// + " B.EAIObstclOccurCausCtnt \n" +// + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ04 B LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBR04 C ON B.BjobRuleCd = C.BjobBzwkPrcssDstcd \n" +// + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBR02 D ON B.BjobRuleCd = D.BjobBzwkPrcssDstcd \n" +// + " AND B.BjobStgeSerno = D.BjobStgeSerno \n" +// + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ01 E ON B.BjobMsgDstcd = E.BjobMsgDstcd \n" +// + " WHERE B.BjobDmndMsgID LIKE ? ||'%' \n" +// + " AND B.BjobDmndSubMsgID LIKE ? ||'%' \n" +// + " ORDER BY B.BjobDmndMsgID, B.BjobDmndSubMsgID, B.ThisStgeStartHMS, B.BjobMsgDstcd"; + + public static final String SELECT_SCHEDULE_BASIS = + "SELECT A.BjobMsgScheID , \n" + + " B.BjobBzwkDstcd , \n" + + " C.BjobBzwkName , \n" + + " A.OsidInstiDstcd , \n" + + " D.OsidInstiName , \n" + + " B.BjobTranDstcdName , \n" + + " A.BjobMsgDstcd , \n" + + " A.SendRecvYn , \n" + + " A.SndrcvCyclTypName , \n" + + " B.UapplCd , \n" + + " B.ThisMsgChrgIDs , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS \n" + + "FROM "+Keys.TABLE_OWNER +"TSEAIBS05 A, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ01 B, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ02 C, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ06 D \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + "AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND A.OsidInstiDstcd = D.OsidInstiDstcd\n" + + "AND A.EAIWarnYn = '1' \n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND A.SndrcvEndHMS < TO_CHAR(SYSDATE,'HH24MISS') \n"; + + public static final String DELETE_ALL_JOBS_FROM_PROCESSING = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; + + public static final String SELECT_ALL_JOBS_FROM_PROCESSING = + "SELECT BjobDmndMsgID ,\n" + + " BjobDmndSubMsgID ,\n" + + " TelgmReTralCnt ,\n" + + " SysLnkgDstcd ,\n" + + " BjobDmndMsgCretnHMS,\n" + + " BjobMsgScheID ,\n" + + " BjobBzwkDstcd ,\n" + + " OsidInstiDstcd ,\n" + + " BjobPtrnDstcd ,\n" + + " SndrcvStartHMS ,\n" + + " SndrcvEndHMS ,\n" + + " SndrcvFileDirName ,\n" + + " SndrcvFileName ,\n" + + " BkupSndrcvFileName ,\n" + + " MsgPrcssPrity ,\n" + + " ThisMsgAmndrID ,\n" + + " ThisMsgAmndHMS ,\n" + + " MsgQueEtractDmndHMS,\n" + + " MsgPrcssStusCd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForMariadb.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForMariadb.java new file mode 100644 index 0000000..3e95fa3 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForMariadb.java @@ -0,0 +1,625 @@ +package com.eactive.eai.batch.scheduler; + +import com.eactive.eai.common.dao.Keys; + +/** +* 1. 기능 : SchedulerMessageDAO에서 사용하는 SQL Query를 정의한 상수 인터페이스 +* 2. 처리 개요 : SchedulerMessageDAO에서 사용하는 SQL Query를 정의한다. +* * +* 3. 주의사항 +* - JobProcessing 테이블(TSEAIBS04)의 처리구분 필드(MsgPrcssStusCd)는 다음과 같이 태그를 정의한다. +* I(영문 대문자): JobQueue 테이블에서 JobProcessing 테이블로 처음 전달된 레코드(insert default value) +* S: F/C로 전달된 레코드, 즉 진행중임을 나타낸다. +* C: 사용자에 의해서 진행이 중지 요청된 레코드이다. 즉, 완전히 해당 프로세스가 중지되었는지 알 수 없다. +* T: F/C에서 정상 종료된 레코드이다. +* E: F/C에서 진행 중에 에러로 종료된 레코드이다. +* +* @author :송영국 +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : 2006.01.10 +*/ +public interface SchedulerMessageQueryForMariadb +{ + //1. File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회 + //order by 우선순위에 의한 맨 처음 한건을 수행할 스케쥴로 설정함 + public static String SELECT_SEND_SCHEDULE_BY_BIZCODE = + "SELECT A.BjobMsgScheID ,\n" + + " A.BjobMsgDstcd ,\n" + + " B.BjobTranDstcdName,\n" + + " A.SndrcvStartHMS ,\n" + + " A.SndrcvEndHMS ,\n" + + " B.BjobBzwkDstcd ,\n" + + " A.BjobPtrnDstcd ,\n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " B.MsgPrcssPrity ,\n" + + " CASE WHEN ( DATE_FORMAT( NOW(), '%Y%m') >= A.SndrcvStartHMS AND \n" + + " DATE_FORMAT( NOW(), '%Y%m') < IFNULL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( DATE_FORMAT( NOW(), '%Y%m') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " END FetchPriority ,\n" + + " A.HoldyPrcssDstcd ,\n" + + " A.StartDlayNoday ,\n" + + " A.EndDlayNoday \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND B.BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ? \n" + + "AND B.BjobTranDstcdName = ? \n" + + "AND A.BjobPtrnDstcd = 'RS'\n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "ORDER BY B.MsgPrcssPrity, FetchPriority, A.SndrcvStartHMS, A.SndrcvEndHMS, B.BjobTranDstcdName"; + + //1-1. File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회 + //order by 우선순위에 의한 맨 처음 한건을 수행할 스케쥴로 설정함 + public static String SELECT_RECV_SCHEDULE_BY_BIZCODE = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " B.MsgPrcssPrity , \n" + + " CASE WHEN ( DATE_FORMAT( NOW(), '%Y%m') >= A.SndrcvStartHMS AND \n" + + " DATE_FORMAT( NOW(), '%Y%m') < IFNULL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( DATE_FORMAT( NOW(), '%Y%m') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " END FetchPriority , \n" + + " A.HoldyPrcssDstcd , \n" + + " A.StartDlayNoday , \n" + + " A.EndDlayNoday \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd\n" + + "AND B.BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ? \n" + + "AND B.BjobTranDstcdName = ? \n" + + "AND A.BjobPtrnDstcd = 'RR' \n" + //+ "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "ORDER BY B.MsgPrcssPrity, FetchPriority, A.SndrcvStartHMS, A.SndrcvEndHMS, B.BjobTranDstcdName"; + + //2. 위 1번 쿼리에 의한 스케쥴 정보를 작업대기목록 테이블에 INSERT + public static final String INSERT_JOB_QUEUE = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBS03 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID , TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , BjobPtrnDstcd , SndrcvStartHMS , \n" + + " SndrcvEndHMS , SndrcvFileDirName, SndrcvFileName , BkupSndrcvFileName , \n" + + " MsgPrcssPrity , HdrInfoName , ThisMsgAmndrID , ThisMsgAmndHMS ) \n" + + "VALUES ( \n" + + " ? , ? , ? , SUBSTR( DATE_FORMAT( NOW(2), '%Y%m%d%H%i%s%f'), 1, 16 ) , ? , \n" + + " ? , ? , ? , ? , \n" + + " ? , ? , ? , ? , \n" + + " ? , ? , ? , ? )"; + + //3. Timer Event 발생시 작업대기목록 테이블에서 수행할(현재시간에 걸리는) 전체 작업목록을 조회 + public static final String SELECT_EXECUTABLE_JOB_FROM_QUEUE = + "SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobDmndMsgCretnHMS, \n" + + " A.BjobMsgScheID , \n" + + " A.BjobBzwkDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " A.SndrcvFileDirName , \n" + + " A.SndrcvFileName , \n" + + " A.BkupSndrcvFileName , \n" + + " A.MsgPrcssPrity , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS , \n" + + " C.BjobMsgDstcd , \n" + + " C.BjobTranDstcdName , \n" + + " D.OsidInstiName , \n" + + " D.TelgmBlckSize , \n" + + " D.TelgmSernoSize , \n" + + " D.TelgmPcketSize , \n" + + " CASE A.BjobPtrnDstcd WHEN 'RS' THEN D.SendPrcssRuleCd \n" + + " WHEN 'RR' THEN D.RecvPrcssRuleCd END AS FlowRuleCode, \n" + + " E.BjobBzwkName , \n" + + " A.HdrInfoName , \n" + + " B.HoldyPrcssDstcd , \n" + + " B.StartDlayNoday , \n" + + " B.EndDlayNoday , \n" + + " B.RqstRecvReTralUseYn \n" //2009.6.16 요구송신의 경우에도 재시도여부 플래그로 사용. by kscheon + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 E \n" + + "WHERE A.BjobMsgScheID = B.BjobMsgScheID \n" + + "AND B.BjobMsgDstcd = C.BjobMsgDstcd \n" + + "AND A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd)) \n" + + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" + + "AND A.MsgPrcssPrity > 0 \n" //--suspend 스케쥴 제외 + + "AND A.SndrcvStartHMS <= SUBSTR( DATE_FORMAT( NOW(2), '%Y%m%d%H%i%s%f'), 1, 16 ) \n" + + "AND IFNULL(RTRIM(A.SndrcvEndHMS), '99991231') > SUBSTR( DATE_FORMAT( NOW(2), '%Y%m%d%H%i%s%f'), 1, 16 ) \n" //--종료시간이 없으면 종료시간 체크 안함 + + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; + + //3. Timer Event 발생시 작업대기목록 테이블에서 수행할(현재시간에 걸리는) 전체 작업목록을 조회 + public static final String SELECT_EXECUTABLE_JOB_FROM_QUEUE_WITH_SUSPENDED_JOB = + "SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobDmndMsgCretnHMS, \n" + + " A.BjobMsgScheID , \n" + + " A.BjobBzwkDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " A.SndrcvFileDirName , \n" + + " A.SndrcvFileName , \n" + + " A.BkupSndrcvFileName , \n" + + " A.MsgPrcssPrity , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS , \n" + + " C.BjobMsgDstcd , \n" + + " C.BjobTranDstcdName , \n" + + " D.OsidInstiName , \n" + + " D.TelgmBlckSize , \n" + + " D.TelgmSernoSize , \n" + + " D.TelgmPcketSize , \n" + + " CASE A.BjobPtrnDstcd WHEN 'RS' THEN D.SendPrcssRuleCd \n" + + " WHEN 'RR' THEN D.RecvPrcssRuleCd END AS FlowRuleCode, \n" + + " E.BjobBzwkName , \n" + + " A.HdrInfoName , \n" + + " B.HoldyPrcssDstcd , \n" + + " B.StartDlayNoday , \n" + + " B.EndDlayNoday , \n" + + " B.RqstRecvReTralUseYn \n" //2009.6.16 요구송신의 경우에도 재시도여부 플래그로 사용. by kscheon + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 E \n" + + "WHERE A.BjobMsgScheID = B.BjobMsgScheID \n" + + "AND B.BjobMsgDstcd = C.BjobMsgDstcd \n" + + "AND A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd)) \n" + + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" +// + "AND A.MsgPrcssPrity > '0' \n" //--suspend 스케쥴 제외 + + "AND A.SndrcvStartHMS <= TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" + + "AND IFNULL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; + + + //4. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 연결정보가 현재 사용중인지 + //체크하기 위해 작업진행목록 테이블에서 전체 연결정보를 조회 + public static final String SELECT_EXECUTING_SYSTEMCONNID_FROM_PROCESSING = + "SELECT SysLnkgDstcd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE MsgPrcssStusCd IN ('S','I','C')"; + +// 4-1. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 앞선 우선순위 작업이 수행중인지 확인하기 위한 쿼리 + //2009.8.14 by kscheon + public static final String SELECT_EXECUTING_JOB_FROM_PROCESSING = + "SELECT BjobBzwkDstcd, MsgPrcssPrity \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE BjobBzwkDstcd = ?\n" + + "AND MsgPrcssStusCd IN ('S','I','C') \n" + + "ORDER BY MsgPrcssPrity "; + + //5. 위 3번 쿼리의 결과 작업중 연결정보의 체크에 의해 걸러진 작업들을 제외한 모든 작업들을 + //작업진행목록 테이블로 이동. 이동 후 각각의 작업을 요구송수신 JPD 호출함. + public static final String MOVE_JOB_FROM_QUEUE_TO_PROCESSING = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBS04 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID, TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , SysLnkgDstcd , BjobPtrnDstcd , \n" + + " SndrcvStartHMS , SndrcvEndHMS , SndrcvFileDirName , SndrcvFileName, \n" + + " BkupSndrcvFileName , MsgPrcssPrity , ThisMsgAmndrID , ThisMsgAmndHMS, \n" + + " MsgQueEtractDmndHMS, MsgPrcssStusCd ) \n" + + "SELECT \n" + + " BjobDmndMsgID , BjobDmndSubMsgID, TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , CAST ( ? AS CHAR(12) ), BjobPtrnDstcd , \n" + + " SndrcvStartHMS , SndrcvEndHMS , SndrcvFileDirName , SndrcvFileName, \n" + + " BkupSndrcvFileName , MsgPrcssPrity , ThisMsgAmndrID , ThisMsgAmndHMS, \n" + + " SUBSTR( DATE_FORMAT( NOW(2), '%Y%m%d%H%i%s%f'), 1, 16 ), 'I' \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ?"; + + //5-1. 위 5번 쿼리를 분리 하여 큐에서 잡을 읽음. + public static final String SELCT_JOB_FROM_QUEUE = + "SELECT TelgmReTralCnt ,\n" + + " BjobDmndMsgCretnHMS,\n" + + " BjobMsgScheID ,\n" + + " BjobBzwkDstcd ,\n" + + " LTRIM(RTRIM(OsidInstiDstcd)) AS OsidInstiDstcd ,\n" + + " BjobPtrnDstcd ,\n" + + " SndrcvStartHMS ,\n" + + " SndrcvEndHMS ,\n" + + " SndrcvFileDirName ,\n" + + " SndrcvFileName ,\n" + + " BkupSndrcvFileName ,\n" + + " MsgPrcssPrity ,\n" + + " ThisMsgAmndrID ,\n" + + " ThisMsgAmndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? "; + + //5-2. 위 5번 쿼리를 분리 하여 프로세싱 테이블에 잡을 INSERT함 + //작업진행목록 테이블로 이동. 이동 후 각각의 작업을 요구송수신 JPD 호출함. + public static final String UPDATE_PROCESSING_WITH_NEW_JOB = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBS04\n" + + "SET TelgmReTralCnt = IFNULL( ?, TelgmReTralCnt ),\n" + + " BjobDmndMsgCretnHMS = IFNULL( ?, BjobDmndMsgCretnHMS),\n" + + " BjobMsgScheID = IFNULL( ?, BjobMsgScheID ),\n" + + " BjobBzwkDstcd = IFNULL( ?, BjobBzwkDstcd ),\n" + + " OsidInstiDstcd = IFNULL( ?, OsidInstiDstcd ),\n" + + " BjobPtrnDstcd = IFNULL( ?, BjobPtrnDstcd ),\n" + + " SndrcvStartHMS = IFNULL( ?, SndrcvStartHMS ),\n" + + " SndrcvEndHMS = IFNULL( ?, SndrcvEndHMS ),\n" + + " SndrcvFileDirName = IFNULL( ?, SndrcvFileDirName ),\n" + + " SndrcvFileName = IFNULL( ?, SndrcvFileName ),\n" + + " BkupSndrcvFileName = IFNULL( ?, BkupSndrcvFileName ),\n" + + " MsgPrcssPrity = IFNULL( ?, MsgPrcssPrity ),\n" + + " ThisMsgAmndrID = IFNULL( ?, ThisMsgAmndrID ),\n" + + " ThisMsgAmndHMS = IFNULL( ?, ThisMsgAmndHMS ),\n" + + " MsgQueEtractDmndHMS = TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3'),\n" + + " MsgPrcssStusCd = 'I'\n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ?"; + + //6. 위 5번 쿼리 후 이동한 작업을 대기목록에서 DELETE + public static final String DELETE_JOB_FROM_QUEUE = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ?"; + + //7. 요구송수신 JPD에서 해당 작업 종료 및 오류 후 해당 작업을 Job_Processing 테이블에서 DELETE + public static final String DELETE_JOB_FROM_PROCESSING = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE BjobDmndMsgID = ?"; + + //9. 요구수신 Timer Event 발생시 스케쥴정보 테이블에서 현재시간에 걸리는 요구수신 스케쥴 정보 조회 + //단, 해당 스케쥴정보는 대기목록 또는 진행목록에 존재하지 않아야 함 + //Master로그 테이블에서 해당 날자의 요구수신 스케쥴ID의 파일 수신완료 건이 존재하지 말아야 함 + public static String SELECT_EXECUTABLE_RECV_SCHEDULE_LIST = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.HoldyPrcssDstcd , \n" + + " A.RpttYn , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd , \n" + + " A.RqstRecvReTralUseYn , \n" + + " A.RqstRecvReTralCnt , \n" + + " A.RqstRecvReTralIntvalTtm, \n" + + " IFNULL(C.RecvFileEndCnt , 0) RecvFileEndCnt , \n" + + " IFNULL(C.RecvFileFailCnt, 0) RecvFileFailCnt, \n" + + " IFNULL(C.RecentExecTime , '') RecentExecTime \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + + " SUM(CASE TranPrcssDstcd WHEN 'T' THEN 1 " + + " ELSE 0 END) AS RecvFileEndCnt ,\n" // --파일전송 완료 건수 + + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " + + " ELSE 1 END) AS RecvFileFailCnt,\n" // --파일전송 미완료 건수 + + " MAX(BjobDmndMsgCretnHMS) RecentExecTime \n" // --최근 수행 시간 + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + " WHERE BjobPtrnDstcd = 'RR' \n" // --요구수신만 + + " AND BjobDmndMsgCretnHMS LIKE CONCAT ( DATE_FORMAT( NOW(), '%Y%m%d'), '%') \n" + + " GROUP BY BjobMsgScheID ) C " + + "on A.BjobMsgScheID = C.BjobMsgScheID \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND A.BjobPtrnDstcd = 'RR' \n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "AND A.SndrcvStartHMS <= DATE_FORMAT( NOW(), '%H%i') \n" + + "AND IFNULL(RTRIM(A.SndrcvEndHMS), '9999') > DATE_FORMAT( NOW(), '%H%i') \n" + + "AND NOT EXISTS ( SELECT X.BjobMsgScheID \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS03 X \n" //--대기목록 테이블에 존재하지 않고 + + " WHERE X.BjobMsgScheID = A.BjobMsgScheID \n" + + " AND X.SndrcvEndHMS >= DATE_FORMAT( NOW(), '%Y%m%d') ) \n" //--미래의 스케쥴이 + + "AND NOT EXISTS ( SELECT Y.BjobMsgScheID \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS04 Y \n" //--진행목록 테이블에 존재하지 않고 + + " WHERE Y.BjobMsgScheID = A.BjobMsgScheID ) \n" + + "ORDER BY A.SndrcvStartHMS, B.BjobTranDstcdName, A.SndrcvEndHMS"; + + + //10. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구수신) + public static String SELECT_SEND_SCHEDULE_BY_SCHEDULEID = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd ,\n" + + " A.RqstRecvReTralCnt ,\n" + + " A.RqstRecvReTralUseYn ,\n" + + " A.RqstRecvReTralIntvalTtm \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND A.BjobMsgScheID = ? \n" + + "AND A.BjobPtrnDstcd = 'RR' \n" //--요구수신만 + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n"; + + //12. 주어진 스케쥴 코드로 해당하는 스케쥴 정보를 구한다. + public static final String SELECT_SCHEDULE_BY_CODE = + "SELECT B.BjobBzwkDstcd, \n" + + " C.BjobBzwkName, \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " D.OsidInstiName, \n" + + " A.BjobMsgDstcd, \n" + + " A.BjobMsgScheID, \n" + + " A.BjobPtrnDstcd, \n" + + " B.BjobTranDstcdName, \n" + + " A.RqstRecvReTralCnt, \n" + + " A.SndrcvStartHMS, \n" + + " A.SndrcvEndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + " AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + " AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + " AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd )) \n" + + " AND LTRIM(RTRIM(A.BjobMsgScheID)) = ? \n"; + + + + +// 13. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구송신) + public static String SELECT_REQ_SEND_SCHEDULE_BY_SCHEDULEID = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.RqstRecvReTralUseYn , \n" + + " A.RqstRecvReTralIntvalTtm , \n" + + " A.RqstRecvReTralCnt , \n" + + " B.MsgPrcssPrity , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd, \n" + + " IFNULL(C.RecvFileFailCnt, 0) AS RecvFileFailCnt \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " + + " ELSE 1 END) AS RecvFileFailCnt\n" //--파일전송 미완료 건수 + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + " WHERE BjobPtrnDstcd = 'RS' \n" //--요구송신만 + + " AND BjobDmndMsgCretnHMS LIKE CONCAT( DATE_FORMAT( NOW(), '%Y%m%d'), '%' ) \n" + + " GROUP BY BjobMsgScheID ) C \n" + + " on A.BjobMsgScheID = C.BjobMsgScheID \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND RTRIM(A.BjobMsgScheID) = ? \n" + + "AND A.BjobPtrnDstcd = 'RS'\n" //--요구송신만 + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n"; + + //위 5번 쿼리 후 이전 로그 테이블에서 DELETE + public static final String DELETE_JOB_FROM_LOGMASTER = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + "WHERE BjobDmndMsgID = ?"; + //위 5번 쿼리 후 이전 로그 테이블에서 DELETE + public static final String DELETE_JOB_FROM_LOGDETAIL = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBJ04 \n" + + "WHERE BjobDmndMsgID = ?"; + + /** + * BATCH작업 메시지일정 ID를 조회하는 쿼리 + */ + public static final String GET_BJOBMSGSCHEID = + " SELECT CONCAT( BjobBzwkDstcd, ? , BjobTranDstcdName , " + + " ( " + + " SELECT " + + " CASE LENGTH(TO_CHAR(TO_NUMBER(IFNULL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1)) " + + " WHEN 1 " + + " THEN CONCAT( '00' , TO_CHAR(TO_NUMBER(IFNULL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) ) " + + " WHEN 2 " + + " THEN CONCAT( '0' , TO_CHAR(TO_NUMBER(IFNULL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) ) " + + " WHEN 3 " + + " THEN TO_CHAR(TO_NUMBER(IFNULL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) " + + " END " + + " FROM "+Keys.TABLE_OWNER +"TSEAIBS01 " + + " WHERE BjobMsgDstcd = ? " + + " ) LEFTCODE " + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ01 " + + " WHERE BjobMsgDstcd = ? "; + + /** + * BATCH작업 일정 정보를 등록하는 쿼리 + */ + public static final String ADD_JOB_SCH_INFO = + "INSERT INTO "+Keys.TABLE_OWNER +"TSEAIBS01 ( " + + " BjobMsgScheID " + + " ,BjobMsgDstcd " + + " ,BjobPtrnDstcd " + + " ,OsidInstiDstcd " + + " ,SndrcvStartHMS " + + " ,SndrcvEndHMS " + + " ,MsgSndrID " + + " ,ScheFrstRegiHMS " + + " ,RqstRecvReTralCnt " + + " ,RqstRecvReTralUseYn " + + " ,RqstRecvReTralIntvalTtm " + + " ,RqstRecvFileStorgDirName " + + " ,StartDlayNoday " + + " ,EndDlayNoday " + + " ,HoldyPrcssDstcd " + + " ,RpttYn " + + " ,ThisMsgUseYn " + + " ,ThisMsgScheDesc " + + " ,ThisMsgRegsntID " + + " ,ThisMsgRegiHMS " + + " ,ThisMsgAmndrID " + + " ,ThisMsgAmndHMS ) " + + " values ( " + + " ? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ,? " + + " ,? " + + " ,? " + + " ,' ' " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,' ' " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ) "; + + /** + * BATCH작업 일정 정보를 등록하는 쿼리 + */ + public static final String SELECT_LOG_MASTER_BY_KEYS = + " SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobMsgScheID , \n" + + " A.BjobDmndMsgCretnHMS , \n" + + " A.BjobBzwkDstcd , \n" + + " C.BjobBzwkName , \n" + + " A.OsidInstiDstcd , \n" + + " D.OsidInstiName , \n" + + " A.BjobPtrnDstcd , \n" + + " A.MsgSndrID , \n" + + " A.MsgSndrName , \n" + + " A.SysLnkgDstcd , \n" + + " A.LnkgIPInfoName , \n" + + " A.FlowRuleCd , \n" + + " A.EAISevrInstncName , \n" + + " A.TranStartHMS , \n" + + " A.TranEndHMS , \n" + + " A.TranPrcssDstcd , \n" + + " A.EAIObstclOccurCausCtnt, \n" + + " A.ObstclPrcsrID , \n" + + " A.ObstclPrcssHMS \n" + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ03 A\n" + + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ02 C ON A.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ06 D ON A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + " AND A.OsidInstiDstcd = D.OsidInstiDstcd \n" + + " WHERE A.BjobDmndMsgID LIKE CONCAT( ? ,'%' ) \n" + + " AND A.BjobDmndSubMsgID LIKE CONCAT( ? ,'%' ) \n"; + + public static final String SELECT_FILE_LOG_BY_KEYS = + "SELECT RqstRecvFileStorgDirName ,\n" + + " BkupSndrcvFileName ,\n" + + " BjobTranDstcdName ,\n" + + " HdrInfoName \n" + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ08 \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND SndrcvFileName = ? \n"; + +// public static final String SELECT_STAGE_LOGS_BY_KEYS = +// "SELECT B.BjobDmndMsgID , \n" +// + " B.BjobDmndSubMsgID , \n" +// + " B.BjobStgeID , \n" +// + " B.PrcssStgeDstcd , \n" +// + " B.BjobRuleCd , \n" +// + " C.FlowRulePtrnDesc , \n" +// + " B.BjobStgeCd , \n" +// + " D.BjobStgeFlxblCndnDesc , \n" +// + " B.BjobStgeSerno , \n" +// + " B.BjobStgePtrnName , \n" +// + " B.BjobFlowCmpoClsName , \n" +// + " B.TelgmDcsnID , \n" +// + " B.TelgmDcsnClsName , \n" +// + " B.TelgmDcsnMsgCd , \n" +// + " B.ThisStgeTelgmID , \n" +// + " B.ThisStgeClsName , \n" +// + " B.ThisStgeMsgCd , \n" +// + " B.TelgmPertypCdValCtnt , \n" +// + " B.TelgmDstcdValCtnt , \n" +// + " B.TelgmMgtCdValCtnt , \n" +// + " B.RspnsCdValCtnt , \n" +// + " B.BjobNodeCasNo , \n" +// + " B.BjobMsgDstcd , \n" +// + " E.BjobMsgDsticName , \n" +// + " B.BjobTranDstcdName , \n" +// + " B.RqstRecvFileStorgDirName, \n" +// + " B.SndrcvFileName , \n" +// + " B.BkupSndrcvFileName , \n" +// + " B.ThisStgeStartHMS , \n" +// + " B.ThisStgeEndHMS , \n" +// + " B.ThisStgePrcssRsultCd , \n" +// + " B.EAIObstclOccurCausCtnt \n" +// + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ04 B LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBR04 C ON B.BjobRuleCd = C.BjobBzwkPrcssDstcd \n" +// + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBR02 D ON B.BjobRuleCd = D.BjobBzwkPrcssDstcd \n" +// + " AND B.BjobStgeSerno = D.BjobStgeSerno \n" +// + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ01 E ON B.BjobMsgDstcd = E.BjobMsgDstcd \n" +// + " WHERE B.BjobDmndMsgID LIKE CONCAT( ? ,'%' ) \n" +// + " AND B.BjobDmndSubMsgID LIKE CONCAT( ? ,'%' ) \n" +// + " ORDER BY B.BjobDmndMsgID, B.BjobDmndSubMsgID, B.ThisStgeStartHMS, B.BjobMsgDstcd"; + + public static final String SELECT_SCHEDULE_BASIS = + "SELECT A.BjobMsgScheID , \n" + + " B.BjobBzwkDstcd , \n" + + " C.BjobBzwkName , \n" + + " A.OsidInstiDstcd , \n" + + " D.OsidInstiName , \n" + + " B.BjobTranDstcdName , \n" + + " A.BjobMsgDstcd , \n" + + " A.SendRecvYn , \n" + + " A.SndrcvCyclTypName , \n" + + " B.UapplCd , \n" + + " B.ThisMsgChrgIDs , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS \n" + + "FROM "+Keys.TABLE_OWNER +"TSEAIBS05 A, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ01 B, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ02 C, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ06 D \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + "AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND A.OsidInstiDstcd = D.OsidInstiDstcd\n" + + "AND A.EAIWarnYn = '1' \n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND A.SndrcvEndHMS < DATE_FORMAT( NOW(), '%H%i%s') \n"; + + public static final String DELETE_ALL_JOBS_FROM_PROCESSING = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; + + public static final String SELECT_ALL_JOBS_FROM_PROCESSING = + "SELECT BjobDmndMsgID ,\n" + + " BjobDmndSubMsgID ,\n" + + " TelgmReTralCnt ,\n" + + " SysLnkgDstcd ,\n" + + " BjobDmndMsgCretnHMS,\n" + + " BjobMsgScheID ,\n" + + " BjobBzwkDstcd ,\n" + + " OsidInstiDstcd ,\n" + + " BjobPtrnDstcd ,\n" + + " SndrcvStartHMS ,\n" + + " SndrcvEndHMS ,\n" + + " SndrcvFileDirName ,\n" + + " SndrcvFileName ,\n" + + " BkupSndrcvFileName ,\n" + + " MsgPrcssPrity ,\n" + + " ThisMsgAmndrID ,\n" + + " ThisMsgAmndHMS ,\n" + + " MsgQueEtractDmndHMS,\n" + + " MsgPrcssStusCd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForOracle.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForOracle.java new file mode 100644 index 0000000..f674f3b --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForOracle.java @@ -0,0 +1,625 @@ +package com.eactive.eai.batch.scheduler; + +import com.eactive.eai.common.dao.Keys; + +/** +* 1. 기능 : SchedulerMessageDAO에서 사용하는 SQL Query를 정의한 상수 인터페이스 +* 2. 처리 개요 : SchedulerMessageDAO에서 사용하는 SQL Query를 정의한다. +* * +* 3. 주의사항 +* - JobProcessing 테이블(TSEAIBS04)의 처리구분 필드(MsgPrcssStusCd)는 다음과 같이 태그를 정의한다. +* I(영문 대문자): JobQueue 테이블에서 JobProcessing 테이블로 처음 전달된 레코드(insert default value) +* S: F/C로 전달된 레코드, 즉 진행중임을 나타낸다. +* C: 사용자에 의해서 진행이 중지 요청된 레코드이다. 즉, 완전히 해당 프로세스가 중지되었는지 알 수 없다. +* T: F/C에서 정상 종료된 레코드이다. +* E: F/C에서 진행 중에 에러로 종료된 레코드이다. +* +* @author :송영국 +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : 2006.01.10 +*/ +public interface SchedulerMessageQueryForOracle +{ + //1. File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회 + //order by 우선순위에 의한 맨 처음 한건을 수행할 스케쥴로 설정함 + public static String SELECT_SEND_SCHEDULE_BY_BIZCODE = + "SELECT A.BjobMsgScheID ,\n" + + " A.BjobMsgDstcd ,\n" + + " B.BjobTranDstcdName,\n" + + " A.SndrcvStartHMS ,\n" + + " A.SndrcvEndHMS ,\n" + + " B.BjobBzwkDstcd ,\n" + + " A.BjobPtrnDstcd ,\n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " B.MsgPrcssPrity ,\n" + + " CASE WHEN ( TO_CHAR(SYSDATE,'HH24MI') >= A.SndrcvStartHMS AND \n" + + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " END FetchPriority ,\n" + + " A.HoldyPrcssDstcd ,\n" + + " A.StartDlayNoday ,\n" + + " A.EndDlayNoday \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND B.BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ? \n" + + "AND B.BjobTranDstcdName = ? \n" + + "AND A.BjobPtrnDstcd = 'RS'\n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "ORDER BY B.MsgPrcssPrity, FetchPriority, A.SndrcvStartHMS, A.SndrcvEndHMS, B.BjobTranDstcdName"; + + //1-1. File Event 발생시 스케쥴정보에서 해당 거래구분코드의 전체 스케쥴 정보 조회 + //order by 우선순위에 의한 맨 처음 한건을 수행할 스케쥴로 설정함 + public static String SELECT_RECV_SCHEDULE_BY_BIZCODE = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " B.MsgPrcssPrity , \n" + + " CASE WHEN ( TO_CHAR(SYSDATE,'HH24MI') >= A.SndrcvStartHMS AND \n" + + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " END FetchPriority , \n" + + " A.HoldyPrcssDstcd , \n" + + " A.StartDlayNoday , \n" + + " A.EndDlayNoday \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd\n" + + "AND B.BjobBzwkDstcd = ? \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ? \n" + + "AND B.BjobTranDstcdName = ? \n" + + "AND A.BjobPtrnDstcd = 'RR' \n" + //+ "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "ORDER BY B.MsgPrcssPrity, FetchPriority, A.SndrcvStartHMS, A.SndrcvEndHMS, B.BjobTranDstcdName"; + + //2. 위 1번 쿼리에 의한 스케쥴 정보를 작업대기목록 테이블에 INSERT + public static final String INSERT_JOB_QUEUE = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBS03 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID , TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , BjobPtrnDstcd , SndrcvStartHMS , \n" + + " SndrcvEndHMS , SndrcvFileDirName, SndrcvFileName , BkupSndrcvFileName , \n" + + " MsgPrcssPrity , HdrInfoName , ThisMsgAmndrID , ThisMsgAmndHMS ) \n" + + "VALUES ( \n" + + " ? , ? , ? , TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') , ? , \n" + + " ? , ? , ? , ? , \n" + + " ? , ? , ? , ? , \n" + + " ? , ? , ? , ? )"; + + //3. Timer Event 발생시 작업대기목록 테이블에서 수행할(현재시간에 걸리는) 전체 작업목록을 조회 + public static final String SELECT_EXECUTABLE_JOB_FROM_QUEUE = + "SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobDmndMsgCretnHMS, \n" + + " A.BjobMsgScheID , \n" + + " A.BjobBzwkDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " A.SndrcvFileDirName , \n" + + " A.SndrcvFileName , \n" + + " A.BkupSndrcvFileName , \n" + + " A.MsgPrcssPrity , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS , \n" + + " C.BjobMsgDstcd , \n" + + " C.BjobTranDstcdName , \n" + + " D.OsidInstiName , \n" + + " D.TelgmBlckSize , \n" + + " D.TelgmSernoSize , \n" + + " D.TelgmPcketSize , \n" + + " CASE A.BjobPtrnDstcd WHEN 'RS' THEN D.SendPrcssRuleCd \n" + + " WHEN 'RR' THEN D.RecvPrcssRuleCd END AS FlowRuleCode, \n" + + " E.BjobBzwkName , \n" + + " A.HdrInfoName , \n" + + " B.HoldyPrcssDstcd , \n" + + " B.StartDlayNoday , \n" + + " B.EndDlayNoday , \n" + + " B.RqstRecvReTralUseYn \n" //2009.6.16 요구송신의 경우에도 재시도여부 플래그로 사용. by kscheon + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 E \n" + + "WHERE A.BjobMsgScheID = B.BjobMsgScheID \n" + + "AND B.BjobMsgDstcd = C.BjobMsgDstcd \n" + + "AND A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd)) \n" + + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" + + "AND A.MsgPrcssPrity > 0 \n" //--suspend 스케쥴 제외 + + "AND A.SndrcvStartHMS <= TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" + + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; + + //3. Timer Event 발생시 작업대기목록 테이블에서 수행할(현재시간에 걸리는) 전체 작업목록을 조회 + public static final String SELECT_EXECUTABLE_JOB_FROM_QUEUE_WITH_SUSPENDED_JOB = + "SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobDmndMsgCretnHMS, \n" + + " A.BjobMsgScheID , \n" + + " A.BjobBzwkDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " A.SndrcvFileDirName , \n" + + " A.SndrcvFileName , \n" + + " A.BkupSndrcvFileName , \n" + + " A.MsgPrcssPrity , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS , \n" + + " C.BjobMsgDstcd , \n" + + " C.BjobTranDstcdName , \n" + + " D.OsidInstiName , \n" + + " D.TelgmBlckSize , \n" + + " D.TelgmSernoSize , \n" + + " D.TelgmPcketSize , \n" + + " CASE A.BjobPtrnDstcd WHEN 'RS' THEN D.SendPrcssRuleCd \n" + + " WHEN 'RR' THEN D.RecvPrcssRuleCd END AS FlowRuleCode, \n" + + " E.BjobBzwkName , \n" + + " A.HdrInfoName , \n" + + " B.HoldyPrcssDstcd , \n" + + " B.StartDlayNoday , \n" + + " B.EndDlayNoday , \n" + + " B.RqstRecvReTralUseYn \n" //2009.6.16 요구송신의 경우에도 재시도여부 플래그로 사용. by kscheon + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 E \n" + + "WHERE A.BjobMsgScheID = B.BjobMsgScheID \n" + + "AND B.BjobMsgDstcd = C.BjobMsgDstcd \n" + + "AND A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd)) \n" + + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" +// + "AND A.MsgPrcssPrity > '0' \n" //--suspend 스케쥴 제외 + + "AND A.SndrcvStartHMS <= TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" + + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; + + + //4. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 연결정보가 현재 사용중인지 + //체크하기 위해 작업진행목록 테이블에서 전체 연결정보를 조회 + public static final String SELECT_EXECUTING_SYSTEMCONNID_FROM_PROCESSING = + "SELECT SysLnkgDstcd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE MsgPrcssStusCd IN ('S','I','C')"; + +// 4-1. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 앞선 우선순위 작업이 수행중인지 확인하기 위한 쿼리 + //2009.8.14 by kscheon + public static final String SELECT_EXECUTING_JOB_FROM_PROCESSING = + "SELECT BjobBzwkDstcd, MsgPrcssPrity \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE BjobBzwkDstcd = ?\n" + + "AND MsgPrcssStusCd IN ('S','I','C') \n" + + "ORDER BY MsgPrcssPrity "; + + //5. 위 3번 쿼리의 결과 작업중 연결정보의 체크에 의해 걸러진 작업들을 제외한 모든 작업들을 + //작업진행목록 테이블로 이동. 이동 후 각각의 작업을 요구송수신 JPD 호출함. + public static final String MOVE_JOB_FROM_QUEUE_TO_PROCESSING = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBS04 ( \n" + + " BjobDmndMsgID , BjobDmndSubMsgID, TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , SysLnkgDstcd , BjobPtrnDstcd , \n" + + " SndrcvStartHMS , SndrcvEndHMS , SndrcvFileDirName , SndrcvFileName, \n" + + " BkupSndrcvFileName , MsgPrcssPrity , ThisMsgAmndrID , ThisMsgAmndHMS, \n" + + " MsgQueEtractDmndHMS, MsgPrcssStusCd ) \n" + + "SELECT \n" + + " BjobDmndMsgID , BjobDmndSubMsgID, TelgmReTralCnt , BjobDmndMsgCretnHMS, BjobMsgScheID , \n" + + " BjobBzwkDstcd , OsidInstiDstcd , CAST ( ? AS CHAR(12) ), BjobPtrnDstcd , \n" + + " SndrcvStartHMS , SndrcvEndHMS , SndrcvFileDirName , SndrcvFileName, \n" + + " BkupSndrcvFileName , MsgPrcssPrity , ThisMsgAmndrID , ThisMsgAmndHMS, \n" + + " TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3'), 'I' \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ? AND BjobDmndSubMsgID = ?"; + + //5-1. 위 5번 쿼리를 분리 하여 큐에서 잡을 읽음. + public static final String SELCT_JOB_FROM_QUEUE = + "SELECT TelgmReTralCnt ,\n" + + " BjobDmndMsgCretnHMS,\n" + + " BjobMsgScheID ,\n" + + " BjobBzwkDstcd ,\n" + + " LTRIM(RTRIM(OsidInstiDstcd)) AS OsidInstiDstcd ,\n" + + " BjobPtrnDstcd ,\n" + + " SndrcvStartHMS ,\n" + + " SndrcvEndHMS ,\n" + + " SndrcvFileDirName ,\n" + + " SndrcvFileName ,\n" + + " BkupSndrcvFileName ,\n" + + " MsgPrcssPrity ,\n" + + " ThisMsgAmndrID ,\n" + + " ThisMsgAmndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? "; + + //5-2. 위 5번 쿼리를 분리 하여 프로세싱 테이블에 잡을 INSERT함 + //작업진행목록 테이블로 이동. 이동 후 각각의 작업을 요구송수신 JPD 호출함. + public static final String UPDATE_PROCESSING_WITH_NEW_JOB = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBS04\n" + + "SET TelgmReTralCnt = NVL( ?, TelgmReTralCnt ),\n" + + " BjobDmndMsgCretnHMS = NVL( ?, BjobDmndMsgCretnHMS),\n" + + " BjobMsgScheID = NVL( ?, BjobMsgScheID ),\n" + + " BjobBzwkDstcd = NVL( ?, BjobBzwkDstcd ),\n" + + " OsidInstiDstcd = NVL( ?, OsidInstiDstcd ),\n" + + " BjobPtrnDstcd = NVL( ?, BjobPtrnDstcd ),\n" + + " SndrcvStartHMS = NVL( ?, SndrcvStartHMS ),\n" + + " SndrcvEndHMS = NVL( ?, SndrcvEndHMS ),\n" + + " SndrcvFileDirName = NVL( ?, SndrcvFileDirName ),\n" + + " SndrcvFileName = NVL( ?, SndrcvFileName ),\n" + + " BkupSndrcvFileName = NVL( ?, BkupSndrcvFileName ),\n" + + " MsgPrcssPrity = NVL( ?, MsgPrcssPrity ),\n" + + " ThisMsgAmndrID = NVL( ?, ThisMsgAmndrID ),\n" + + " ThisMsgAmndHMS = NVL( ?, ThisMsgAmndHMS ),\n" + + " MsgQueEtractDmndHMS = TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3'),\n" + + " MsgPrcssStusCd = 'I'\n" + + "WHERE BjobDmndMsgID = ? \n" + + "AND BjobDmndSubMsgID = ?"; + + //6. 위 5번 쿼리 후 이동한 작업을 대기목록에서 DELETE + public static final String DELETE_JOB_FROM_QUEUE = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS03 \n" + + "WHERE BjobDmndMsgID = ? AND BjobDmndSubMsgID = ?"; + + //7. 요구송수신 JPD에서 해당 작업 종료 및 오류 후 해당 작업을 Job_Processing 테이블에서 DELETE + public static final String DELETE_JOB_FROM_PROCESSING = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + + "WHERE BjobDmndMsgID = ?"; + + //9. 요구수신 Timer Event 발생시 스케쥴정보 테이블에서 현재시간에 걸리는 요구수신 스케쥴 정보 조회 + //단, 해당 스케쥴정보는 대기목록 또는 진행목록에 존재하지 않아야 함 + //Master로그 테이블에서 해당 날자의 요구수신 스케쥴ID의 파일 수신완료 건이 존재하지 말아야 함 + public static String SELECT_EXECUTABLE_RECV_SCHEDULE_LIST = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.HoldyPrcssDstcd , \n" + + " A.RpttYn , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd , \n" + + " A.RqstRecvReTralUseYn , \n" + + " A.RqstRecvReTralCnt , \n" + + " A.RqstRecvReTralIntvalTtm, \n" + + " NVL(C.RecvFileEndCnt , 0) RecvFileEndCnt , \n" + + " NVL(C.RecvFileFailCnt, 0) RecvFileFailCnt, \n" + + " NVL(C.RecentExecTime , '') RecentExecTime \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + + " SUM(CASE TranPrcssDstcd WHEN 'T' THEN 1 " + + " ELSE 0 END) AS RecvFileEndCnt ,\n" // --파일전송 완료 건수 + + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " + + " ELSE 1 END) AS RecvFileFailCnt,\n" // --파일전송 미완료 건수 + + " MAX(BjobDmndMsgCretnHMS) RecentExecTime \n" // --최근 수행 시간 + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + " WHERE BjobPtrnDstcd = 'RR' \n" // --요구수신만 + + " AND BjobDmndMsgCretnHMS LIKE TO_CHAR(SYSDATE,'YYYYMMDD')||'%' \n" + + " GROUP BY BjobMsgScheID ) C " + + "on A.BjobMsgScheID = C.BjobMsgScheID \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND A.BjobPtrnDstcd = 'RR' --요구수신만 \n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n" + + "AND A.SndrcvStartHMS <= TO_CHAR(SYSDATE,'HH24MI') \n" + + "AND NVL(RTRIM(A.SndrcvEndHMS), '9999') > TO_CHAR(SYSDATE,'HH24MI') \n" + + "AND NOT EXISTS ( SELECT X.BjobMsgScheID \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS03 X \n" //--대기목록 테이블에 존재하지 않고 + + " WHERE X.BjobMsgScheID = A.BjobMsgScheID \n" + + " AND X.SndrcvEndHMS >= TO_CHAR(SYSDATE,'YYYYMMDD') ) \n" //--미래의 스케쥴이 + + "AND NOT EXISTS ( SELECT Y.BjobMsgScheID \n" + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS04 Y \n" //--진행목록 테이블에 존재하지 않고 + + " WHERE Y.BjobMsgScheID = A.BjobMsgScheID ) \n" + + "ORDER BY A.SndrcvStartHMS, B.BjobTranDstcdName, A.SndrcvEndHMS"; + + + //10. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구수신) + public static String SELECT_SEND_SCHEDULE_BY_SCHEDULEID = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName, \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd ,\n" + + " A.RqstRecvReTralCnt ,\n" + + " A.RqstRecvReTralUseYn ,\n" + + " A.RqstRecvReTralIntvalTtm \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND A.BjobMsgScheID = ? \n" + + "AND A.BjobPtrnDstcd = 'RR' \n" //--요구수신만 + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n"; + + //12. 주어진 스케쥴 코드로 해당하는 스케쥴 정보를 구한다. + public static final String SELECT_SCHEDULE_BY_CODE = + "SELECT B.BjobBzwkDstcd, \n" + + " C.BjobBzwkName, \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + + " D.OsidInstiName, \n" + + " A.BjobMsgDstcd, \n" + + " A.BjobMsgScheID, \n" + + " A.BjobPtrnDstcd, \n" + + " B.BjobTranDstcdName, \n" + + " A.RqstRecvReTralCnt, \n" + + " A.SndrcvStartHMS, \n" + + " A.SndrcvEndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ02 C, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ06 D \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + " AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + " AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + " AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd )) \n" + + " AND LTRIM(RTRIM(A.BjobMsgScheID)) = ? \n"; + + + + +// 13. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구송신) + public static String SELECT_REQ_SEND_SCHEDULE_BY_SCHEDULEID = + "SELECT A.BjobMsgScheID , \n" + + " A.BjobMsgDstcd , \n" + + " B.BjobTranDstcdName , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS , \n" + + " B.BjobBzwkDstcd , \n" + + " A.BjobPtrnDstcd , \n" + + " A.RqstRecvReTralUseYn , \n" + + " A.RqstRecvReTralIntvalTtm , \n" + + " A.RqstRecvReTralCnt , \n" + + " B.MsgPrcssPrity , \n" + + " LTRIM(RTRIM(A.OsidInstiDstcd )) AS OsidInstiDstcd, \n" + + " NVL(C.RecvFileFailCnt, 0) AS RecvFileFailCnt \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " + + " ELSE 1 END) AS RecvFileFailCnt\n" //--파일전송 미완료 건수 + + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + " WHERE BjobPtrnDstcd = 'RS' \n" //--요구송신만 + + " AND BjobDmndMsgCretnHMS LIKE TO_CHAR(SYSDATE,'YYYYMMDD')||'%' \n" + + " GROUP BY BjobMsgScheID ) C \n" + + " on A.BjobMsgScheID = C.BjobMsgScheID \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND RTRIM(A.BjobMsgScheID) = ? \n" + + "AND A.BjobPtrnDstcd = 'RS'\n" //--요구송신만 + + "AND A.ThisMsgUseYn = '1' \n" + + "AND B.ThisMsgUseYn = '1' \n"; + + //위 5번 쿼리 후 이전 로그 테이블에서 DELETE + public static final String DELETE_JOB_FROM_LOGMASTER = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + + "WHERE BjobDmndMsgID = ?"; + //위 5번 쿼리 후 이전 로그 테이블에서 DELETE + public static final String DELETE_JOB_FROM_LOGDETAIL = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBJ04 \n" + + "WHERE BjobDmndMsgID = ?"; + + /** + * BATCH작업 메시지일정 ID를 조회하는 쿼리 + */ + public static final String GET_BJOBMSGSCHEID = + " SELECT BjobBzwkDstcd|| ? ||BjobTranDstcdName|| " + + " ( " + + " SELECT " + + " CASE LENGTH(TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1)) " + + " WHEN 1 " + + " THEN '00' || TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) " + + " WHEN 2 " + + " THEN '0' || TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) " + + " WHEN 3 " + + " THEN TO_CHAR(TO_NUMBER(NVL(MAX(SUBSTR(RTRIM(BjobMsgScheID), LENGTH(RTRIM(BjobMsgScheID))-2, 3)), '0')) + 1) " + + " END " + + " FROM "+Keys.TABLE_OWNER +"TSEAIBS01 " + + " WHERE BjobMsgDstcd = ? " + + " ) LEFTCODE " + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ01 " + + " WHERE BjobMsgDstcd = ? "; + + /** + * BATCH작업 일정 정보를 등록하는 쿼리 + */ + public static final String ADD_JOB_SCH_INFO = + "INSERT INTO "+Keys.TABLE_OWNER +"TSEAIBS01 ( " + + " BjobMsgScheID " + + " ,BjobMsgDstcd " + + " ,BjobPtrnDstcd " + + " ,OsidInstiDstcd " + + " ,SndrcvStartHMS " + + " ,SndrcvEndHMS " + + " ,MsgSndrID " + + " ,ScheFrstRegiHMS " + + " ,RqstRecvReTralCnt " + + " ,RqstRecvReTralUseYn " + + " ,RqstRecvReTralIntvalTtm " + + " ,RqstRecvFileStorgDirName " + + " ,StartDlayNoday " + + " ,EndDlayNoday " + + " ,HoldyPrcssDstcd " + + " ,RpttYn " + + " ,ThisMsgUseYn " + + " ,ThisMsgScheDesc " + + " ,ThisMsgRegsntID " + + " ,ThisMsgRegiHMS " + + " ,ThisMsgAmndrID " + + " ,ThisMsgAmndHMS ) " + + " values ( " + + " ? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ,? " + + " ,? " + + " ,? " + + " ,' ' " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,? " + + " ,' ' " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ,? " + + " ,TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') " + + " ) "; + + /** + * BATCH작업 일정 정보를 등록하는 쿼리 + */ + public static final String SELECT_LOG_MASTER_BY_KEYS = + " SELECT A.BjobDmndMsgID , \n" + + " A.BjobDmndSubMsgID , \n" + + " A.TelgmReTralCnt , \n" + + " A.BjobMsgScheID , \n" + + " A.BjobDmndMsgCretnHMS , \n" + + " A.BjobBzwkDstcd , \n" + + " C.BjobBzwkName , \n" + + " A.OsidInstiDstcd , \n" + + " D.OsidInstiName , \n" + + " A.BjobPtrnDstcd , \n" + + " A.MsgSndrID , \n" + + " A.MsgSndrName , \n" + + " A.SysLnkgDstcd , \n" + + " A.LnkgIPInfoName , \n" + + " A.FlowRuleCd , \n" + + " A.EAISevrInstncName , \n" + + " A.TranStartHMS , \n" + + " A.TranEndHMS , \n" + + " A.TranPrcssDstcd , \n" + + " A.EAIObstclOccurCausCtnt, \n" + + " A.ObstclPrcsrID , \n" + + " A.ObstclPrcssHMS \n" + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ03 A\n" + + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ02 C ON A.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ06 D ON A.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + " AND A.OsidInstiDstcd = D.OsidInstiDstcd \n" + + " WHERE A.BjobDmndMsgID LIKE ? ||'%' \n" + + " AND A.BjobDmndSubMsgID LIKE ? ||'%' \n"; + + public static final String SELECT_FILE_LOG_BY_KEYS = + "SELECT RqstRecvFileStorgDirName ,\n" + + " BkupSndrcvFileName ,\n" + + " BjobTranDstcdName ,\n" + + " HdrInfoName \n" + + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ08 \n" + + " WHERE BjobDmndMsgID = ? \n" + + " AND BjobDmndSubMsgID = ? \n" + + " AND SndrcvFileName = ? \n"; + +// public static final String SELECT_STAGE_LOGS_BY_KEYS = +// "SELECT B.BjobDmndMsgID , \n" +// + " B.BjobDmndSubMsgID , \n" +// + " B.BjobStgeID , \n" +// + " B.PrcssStgeDstcd , \n" +// + " B.BjobRuleCd , \n" +// + " C.FlowRulePtrnDesc , \n" +// + " B.BjobStgeCd , \n" +// + " D.BjobStgeFlxblCndnDesc , \n" +// + " B.BjobStgeSerno , \n" +// + " B.BjobStgePtrnName , \n" +// + " B.BjobFlowCmpoClsName , \n" +// + " B.TelgmDcsnID , \n" +// + " B.TelgmDcsnClsName , \n" +// + " B.TelgmDcsnMsgCd , \n" +// + " B.ThisStgeTelgmID , \n" +// + " B.ThisStgeClsName , \n" +// + " B.ThisStgeMsgCd , \n" +// + " B.TelgmPertypCdValCtnt , \n" +// + " B.TelgmDstcdValCtnt , \n" +// + " B.TelgmMgtCdValCtnt , \n" +// + " B.RspnsCdValCtnt , \n" +// + " B.BjobNodeCasNo , \n" +// + " B.BjobMsgDstcd , \n" +// + " E.BjobMsgDsticName , \n" +// + " B.BjobTranDstcdName , \n" +// + " B.RqstRecvFileStorgDirName, \n" +// + " B.SndrcvFileName , \n" +// + " B.BkupSndrcvFileName , \n" +// + " B.ThisStgeStartHMS , \n" +// + " B.ThisStgeEndHMS , \n" +// + " B.ThisStgePrcssRsultCd , \n" +// + " B.EAIObstclOccurCausCtnt \n" +// + " FROM "+Keys.TABLE_OWNER +"TSEAIBJ04 B LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBR04 C ON B.BjobRuleCd = C.BjobBzwkPrcssDstcd \n" +// + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBR02 D ON B.BjobRuleCd = D.BjobBzwkPrcssDstcd \n" +// + " AND B.BjobStgeSerno = D.BjobStgeSerno \n" +// + " LEFT OUTER JOIN "+Keys.TABLE_OWNER +"TSEAIBJ01 E ON B.BjobMsgDstcd = E.BjobMsgDstcd \n" +// + " WHERE B.BjobDmndMsgID LIKE ? ||'%' \n" +// + " AND B.BjobDmndSubMsgID LIKE ? ||'%' \n" +// + " ORDER BY B.BjobDmndMsgID, B.BjobDmndSubMsgID, B.ThisStgeStartHMS, B.BjobMsgDstcd"; + + public static final String SELECT_SCHEDULE_BASIS = + "SELECT A.BjobMsgScheID , \n" + + " B.BjobBzwkDstcd , \n" + + " C.BjobBzwkName , \n" + + " A.OsidInstiDstcd , \n" + + " D.OsidInstiName , \n" + + " B.BjobTranDstcdName , \n" + + " A.BjobMsgDstcd , \n" + + " A.SendRecvYn , \n" + + " A.SndrcvCyclTypName , \n" + + " B.UapplCd , \n" + + " B.ThisMsgChrgIDs , \n" + + " A.SndrcvStartHMS , \n" + + " A.SndrcvEndHMS \n" + + "FROM "+Keys.TABLE_OWNER +"TSEAIBS05 A, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ01 B, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ02 C, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ06 D \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + + "AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + "AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND A.OsidInstiDstcd = D.OsidInstiDstcd\n" + + "AND A.EAIWarnYn = '1' \n" + + "AND A.ThisMsgUseYn = '1' \n" + + "AND A.SndrcvEndHMS < TO_CHAR(SYSDATE,'HH24MISS') \n"; + + public static final String DELETE_ALL_JOBS_FROM_PROCESSING = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; + + public static final String SELECT_ALL_JOBS_FROM_PROCESSING = + "SELECT BjobDmndMsgID ,\n" + + " BjobDmndSubMsgID ,\n" + + " TelgmReTralCnt ,\n" + + " SysLnkgDstcd ,\n" + + " BjobDmndMsgCretnHMS,\n" + + " BjobMsgScheID ,\n" + + " BjobBzwkDstcd ,\n" + + " OsidInstiDstcd ,\n" + + " BjobPtrnDstcd ,\n" + + " SndrcvStartHMS ,\n" + + " SndrcvEndHMS ,\n" + + " SndrcvFileDirName ,\n" + + " SndrcvFileName ,\n" + + " BkupSndrcvFileName ,\n" + + " MsgPrcssPrity ,\n" + + " ThisMsgAmndrID ,\n" + + " ThisMsgAmndHMS ,\n" + + " MsgQueEtractDmndHMS,\n" + + " MsgPrcssStusCd \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageVO.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageVO.java new file mode 100644 index 0000000..22ba7a3 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageVO.java @@ -0,0 +1,202 @@ +package com.eactive.eai.batch.scheduler; + +import java.io.Serializable; + +/** +* 1. 기능 : 하나의 스케쥴 정보를 나타내는 Java Value Object 클래스. +* 2. 처리 개요 :Java Value Object 클래스. +* 3. 주의사항 +* +* @author : 송영국 +* @version : v 1.0.0 +* @see : SchedulerMessageDAO, SchedulerMessageManager +* @since : 2006.01.10 +*/ +public class SchedulerMessageVO implements Serializable +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + private String uuid = ""; + private String subUuid = ""; + private String msgCreateTime = ""; + private String scheduleCode = ""; + private String jobCode = ""; + private String bizCode = ""; + private String processCode = ""; + private String processName = ""; + private String processType = ""; + private String institutionCode = ""; + private String startTime = ""; + private String endTime = ""; + private String filePath = ""; + private String fileName = ""; + private String renamedFileName = ""; + private int priority = 999; + private String hdrInfoName = ""; + private String systemConnCode = ""; + private String flowRuleCode = ""; +// private String protocol = ""; + private String useFlag = ""; + private String createId = ""; + private String createTime = ""; + private String updateId = ""; + private String updateTime = ""; + private String recvRetryFlag = ""; + private int recvRetryCnt = 0; + private int recvRetrySecs = 0; + private int recvFailCnt = 0; + private String institutionName = ""; //TSEAIBJ06 필드값 +// private String institutionType = ""; //TSEAIBJ06 필드값 + private int blockSize = 0; //TSEAIBJ06 필드값 + private int sequenceSize = 0; //TSEAIBJ06 필드값 + private String rempoteIP = ""; //TSEAIBJ05 필드값 + private String remotePort = ""; //TSEAIBJ05 필드값 + private String remoteUserID = ""; //TSEAIBJ05 필드값 + private String remoteUserPW = ""; //TSEAIBJ05 필드값 + private String telegramTimeout = ""; //TSEAIBJ05 필드값 (사용안함) + private int packetSize = 4096; + private String rqstRspnsDstcd = ""; + + //2008.10.15 BY KSCHEON + private String rePrcssStartYMS = ""; + + //2009.04.02 BY DHJEONG + private String holyProcessGb = ""; + private int startDelayDays = 0; + private int endDelayDays = 0; + private String rpttYn = ""; + + public void setUUID (String arg) { uuid = arg; } + public void setSubUUID (String arg) { subUuid = arg; } + public void setMsgCreateTime (String arg) { msgCreateTime = arg; } + public void setScheduleCode (String arg) { scheduleCode = arg; } + public void setJobCode (String arg) { jobCode = arg; } + public void setBizCode (String arg) { bizCode = arg; } + public void setProcessCode (String arg) { processCode = arg; } + public void setProcessName (String arg) { processName = arg; } + public void setProcessType (String arg) { processType = arg; } + public void setInstitutionCode (String arg) { institutionCode = arg; } + public void setStartTime (String arg) { startTime = arg; } + public void setEndTime (String arg) { endTime = arg; } + public void setFilePath (String arg) { filePath = arg; } + public void setFileName (String arg) { fileName = arg; } + public void setRenamedFileName (String arg) { renamedFileName = arg; } + public void setPriority (int arg) { priority = arg; } + public void setHdrInfoName (String arg) { hdrInfoName = arg; } + public void setSystemConnCode (String arg) { systemConnCode = arg; } + public void setFlowRuleCode (String arg) { flowRuleCode = arg; } +// public void setProtocol (String arg) { protocol = arg; } + public void setUseFlag (String arg) { useFlag = arg; } + public void setCreateId (String arg) { createId = arg; } + public void setCreateTime (String arg) { createTime = arg; } + public void setUpdateId (String arg) { updateId = arg; } + public void setUpdateTime (String arg) { updateTime = arg; } + public void setRecvRetryFlag (String arg) { recvRetryFlag = arg; } + public void setRecvRetryCnt (int arg) { recvRetryCnt = arg; } + public void setRecvRetrySecs (int arg) { recvRetrySecs = arg; } + public void setRecvFailCnt (int arg) { recvFailCnt = arg; } + public void setInstitutionName (String arg) { institutionName = arg; } +// public void setInstitutionType (String arg) { institutionType = arg; } + public void setBlockSize (int arg) { blockSize = arg; } + public void setSequenceSize (int arg) { sequenceSize = arg; } + public void setRempoteIP (String arg) { rempoteIP = arg; } + public void setRemotePort (String arg) { remotePort = arg; } + public void setRemoteUserID (String arg) { remoteUserID = arg; } + public void setRemoteUserPW (String arg) { remoteUserPW = arg; } + public void setTelegramTimeout (String arg) { telegramTimeout = arg; } + public void setPacketSize (int arg) { packetSize = arg; } + public void setRqstRspnsDstcd (String arg) { this.rqstRspnsDstcd = arg; } + + //2008.10.15 by kscheon + public void setRePrcssStartYMS (String arg) { this.rePrcssStartYMS = arg; } + + //2009.04.02 BY DHJEONG + public void setHolyProcessGb (String arg) { this.holyProcessGb = arg; } + public void setStartDelayDays (int arg) { this.startDelayDays = arg; } + public void setEndDelayDays (int arg) { this.endDelayDays = arg; } + public void setRpttYn (String arg) { this.rpttYn = arg; } + + public String getUUID () { return uuid ; } + public String getSubUUID () { return subUuid ; } + public String getMsgCreateTime () { return msgCreateTime ; } + public String getScheduleCode () { return scheduleCode ; } + public String getJobCode () { return jobCode ; } + public String getBizCode () { return bizCode ; } + public String getProcessCode () { return processCode ; } + public String getProcessName () { return processName ; } + public String getProcessType () { return processType ; } + public String getInstitutionCode () { return institutionCode ; } + public String getStartTime () { return startTime ; } + public String getEndTime () { return endTime ; } + public String getFilePath () { return filePath ; } + public String getFileName () { return fileName ; } + public String getRenamedFileName () { return renamedFileName ; } + public int getPriority () { return priority ; } + public String getHdrInfoName () { return hdrInfoName ; } + public String getSystemConnCode () { return systemConnCode ; } + public String getFlowRuleCode () { return flowRuleCode ; } +// public String getProtocol () { return protocol ; } + public String getUseFlag () { return useFlag ; } + public String getCreateId () { return createId ; } + public String getCreateTime () { return createTime ; } + public String getUpdateId () { return updateId ; } + public String getUpdateTime () { return updateTime ; } + public String getRecvRetryFlag () { return recvRetryFlag ; } + public int getRecvRetryCnt () { return recvRetryCnt ; } + public int getRecvRetrySecs () { return recvRetrySecs ; } + public int getRecvFailCnt () { return recvFailCnt ; } + public String getInstitutionName () { return institutionName ; } +// public String getInstitutionType () { return institutionType ; } + public int getBlockSize () { return blockSize ; } + public int getSequenceSize () { return sequenceSize ; } + public String getRempoteIP () { return rempoteIP ; } + public String getRemotePort () { return remotePort ; } + public String getRemoteUserID () { return remoteUserID ; } + public String getRemoteUserPW () { return remoteUserPW ; } + public String getTelegramTimeout () { return telegramTimeout ; } + public int getPacketSize () { return packetSize ; } + public String getRqstRspnsDstcd () { return this.rqstRspnsDstcd; } + +// 2008.10.15 by kscheon + public String getRePrcssStartYMS () { return this.rePrcssStartYMS;} + + //2009.04.02 BY DHJEONG + public String getHolyProcessGb () { return this.holyProcessGb;} + public int getStartDelayDays () { return startDelayDays ;} + public int getEndDelayDays () { return endDelayDays ;} + public String getRpttYn () { return this.rpttYn ;} + + @Override + public String toString() { + return "SchedulerMessageVO [uuid=" + uuid + ", subUuid=" + subUuid + + ", msgCreateTime=" + msgCreateTime + ", scheduleCode=" + + scheduleCode + ", jobCode=" + jobCode + ", bizCode=" + + bizCode + ", processCode=" + processCode + ", processName=" + + processName + ", processType=" + processType + + ", institutionCode=" + institutionCode + ", startTime=" + + startTime + ", endTime=" + endTime + ", filePath=" + filePath + + ", fileName=" + fileName + ", renamedFileName=" + + renamedFileName + ", priority=" + priority + ", hdrInfoName=" + + hdrInfoName + ", systemConnCode=" + systemConnCode + + ", flowRuleCode=" + flowRuleCode + ", useFlag=" + useFlag + + ", createId=" + createId + ", createTime=" + createTime + + ", updateId=" + updateId + ", updateTime=" + updateTime + + ", recvRetryFlag=" + recvRetryFlag + ", recvRetryCnt=" + + recvRetryCnt + ", recvRetrySecs=" + recvRetrySecs + + ", recvFailCnt=" + recvFailCnt + ", institutionName=" +// + institutionName + ", institutionType=" + institutionType + + institutionName + + ", blockSize=" + blockSize + ", sequenceSize=" + sequenceSize + + ", rempoteIP=" + rempoteIP + ", remotePort=" + remotePort + + ", remoteUserID=" + remoteUserID + ", remoteUserPW=" + + remoteUserPW + ", telegramTimeout=" + telegramTimeout + + ", packetSize=" + packetSize + ", rqstRspnsDstcd=" + + rqstRspnsDstcd + ", rePrcssStartYMS=" + rePrcssStartYMS + + ", holyProcessGb=" + holyProcessGb + ", startDelayDays=" + + startDelayDays + ", endDelayDays=" + endDelayDays + "]"; + } + +} diff --git a/src/com/eactive/eai/batch/scheduler/TransJobMonitor.java b/src/com/eactive/eai/batch/scheduler/TransJobMonitor.java new file mode 100644 index 0000000..046b205 --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/TransJobMonitor.java @@ -0,0 +1,207 @@ +package com.eactive.eai.batch.scheduler; + +import java.util.Timer; + +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.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.UCMsgSenderUtil; + +public class TransJobMonitor implements Lifecycle{ + + /** + * EAI FRAMEWORK DEFAULT FILE LOGGER + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + /** + * TransJobMonitor의 Singleton object + */ + private static TransJobMonitor instance = new TransJobMonitor(); + + /** + * TransJobMonitor의 Lifecycle Event 처리를 위한 LifecycleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 일일, 최근시간별 데이터 저장을 위해 주기적으로 실행 Monitor check를 하는 TimerTask object + */ + private TransferJobChecker checker; + + /** + * MonitorChecker를 실제 실행하는 Timer object + */ + private Timer timer; + + + /** + * TransJobMonitor starting 여부를 체크하는 flag 변수 + */ + private boolean started; + + + + /** + * 1. 기능 : Default 생성자 + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + private TransJobMonitor() { + + } + + /** + * 1. 기능 : TransJobMonitor Singleton object를 반환하는 메서드 + * 2. 처리 개요 : + * - TransJobMonitor Singleton object의 reference 반환 + * 3. 주의사항 + * + *@return TransJobMonitor Singleton object + **/ + public static TransJobMonitor getInstance() { + if(instance==null) { + synchronized(TransJobMonitor.class) { + if(instance==null) { + instance = new TransJobMonitor(); + } + } + } + + return instance; + } + + + /** + * 1. 기능 : TransJobMonitor의 초기화 작업을 실행하는 메서드 + * 2. 처리 개요 : + * - MonitorChecker객체를 생성해 Timer에 등록 실행한다. + * 3. 주의사항 + * + *@exception LifecycleException TransJobMonitor 초기화 실패 시 발생 + **/ + public void start() throws LifecycleException { + if (started) { + throw new LifecycleException("BECEAIMEH201"); + } + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + long period = 1000*60*60*1; //밀리 * 초 * 분 * 시간 ( 1000*60*60*1 = 1시간 ) + try { + period = 60 * 1000 * Long.parseLong(PropManager.getInstance().getProperty(UCMsgSenderUtil.UCINFO, UCMsgSenderUtil.CHECK_PERIOD )); + + } catch(Exception e) {} + + + this.checker = new TransferJobChecker(); + + this.timer = new Timer(); + + String currentTime = DatetimeUtil.getCurrentTimeMillis(); + + long delay = ( 60 * 60 * 1000 - ( 60 * 1000 * Long.parseLong(currentTime.substring(10,12))) - Long.parseLong(currentTime.substring(12,17))); +// try { +// delay += 60 * 1000 * Long.parseLong(PropManager.getInstance().getProperty(ItmsSmsUtil.SMSINFO, ItmsSmsUtil.CHECK_DELAY )); +// +// } catch(Exception e) {} + + delay %= period; // delay 가 한주기를 넘지않도록 한다. + + this.timer.schedule(this.checker, delay, period); + + started = true; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : TransJobMonitor의 종료시 undo 작업을 실행하는 메서드 + * 2. 처리 개요 : + * - 초기화 작업 시 생성한 MonitorChecker객체를 종료한다. + * 3. 주의사항 + * + *@exception LifecycleException TransJobMonitor undo 작업 실패 시 발생 + **/ + public void stop() throws LifecycleException { + if(!started){ + throw new LifecycleException("BECEAIMEH203"); + } else { + lifecycle.fireLifecycleEvent("stoping", this); + + started = false; + this.timer.cancel(); + this.timer = null; + this.checker = null; + + lifecycle.fireLifecycleEvent("stopped", this); + + return; + } + + + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : + * - LifecycleListener를 등록한다. + * 3. 주의사항 + * + *@param listener Lifecycle Evnet를 받을 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 반환하는 메서드 + * 2. 처리 개요 : + * - 등록된 LifecycleListener를 반환한다. + * 3. 주의사항 + * + *@return 등록된 LifecycleListner들 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 중 특정 LifecyleListener를 삭제하는 메서드 + * 2. 처리 개요 : + * - 등록된 특정 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + *@param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : TransJobMonitor의 start 여부를 반환하는 getter method + * 2. 처리 개요 : + * - TransJobMonitor의 start 여부를 반환한다. + * 3. 주의사항 + * + *@return TransJobMonitor의 start 여부 + **/ + public boolean isStarted() { + return this.started; + } + + +} diff --git a/src/com/eactive/eai/batch/scheduler/TransferJobChecker.java b/src/com/eactive/eai/batch/scheduler/TransferJobChecker.java new file mode 100644 index 0000000..c73c3de --- /dev/null +++ b/src/com/eactive/eai/batch/scheduler/TransferJobChecker.java @@ -0,0 +1,128 @@ +package com.eactive.eai.batch.scheduler; + +import java.util.ArrayList; +import java.util.TimerTask; + +import com.eactive.eai.batch.logger.LogManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.UCMsgSenderUtil; +public class TransferJobChecker extends TimerTask{ + + public static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public void run(){ + + logger.debug("[TransferJobChecker]시작"); + try { + ArrayList alInterval = ScheduleBasisManager.getInstance().getIntervalTypes( DatetimeUtil.getCurrentDate() ); + ArrayList alScheduleList = SchedulerMessageManager.getInstance().getScheduledJobList(alInterval); + ArrayList alLogList = LogManager.getInstance().getFileLogSuccess(); + JobFileTransferVO svo = null; + JobFileTransferVO lvo = null; + int sstart = 0; + int lstart = 0; + for ( int inx = 0; inx < alScheduleList.size(); inx++){ + svo = alScheduleList.get(inx); + logger.debug("[TransferJobChecker]svo(" + inx + ")-->" + svo); + try { + sstart = Integer.parseInt(svo.getSndrcvStartHMS()); + } catch (Exception e) {} + + boolean logFlag = false; + for ( int jnx = 0; jnx < alLogList.size(); jnx++){ + lvo = alLogList.get(jnx); + try { + lstart = Integer.parseInt(lvo.getSndrcvStartHMS()); + } catch (Exception e) {} + if ( ( svo.getBjobMsgDstcd().equals(lvo.getBjobMsgDstcd()) || // 같은 파일인지 ( 작업메시지 구분이 같거나 ) + ( svo.getBjobBzwkDstcd().equals(lvo.getBjobBzwkDstcd()) && // "" ( 업무구분이 같고 + svo.getBjobTranDstcdName().equals(lvo.getBjobTranDstcdName()) // "" 거래구분코드가 같은 경우 ) + ) + ) && + svo.getSendRecvYn().equals(lvo.getSendRecvYn()) && // 송수신 구분이 같은지 + sstart <= lstart // 송수신 시작 시간이 스케쥴된 시작 시간 이후이고 + ){ + logFlag = true; + break; + } + } + if ( !logFlag ){ + sendUC(svo); + } + } + + } catch (Exception e) { + logger.error( e.getMessage(), e); + return; + } finally { + } + + logger.debug("[TransferJobChecker]끝"); + + return; + } + +// private void sendSms ( JobFileTransferVO vo ){ +// +// String message = "[송신지연]"; +// if ( "R".equals(vo.getSendRecvYn())){ +// message = "[수신지연]"; +// } +// +// // 지연된 시간 계산 +// int scheduleT = Integer.parseInt(vo.getSndrcvEndHMS().substring(0,2)); +// int scheduleM = Integer.parseInt(vo.getSndrcvEndHMS().substring(2,4)); +// +// String currentTime = DatetimeUtil.getCurrentTime(); +// int currentT = Integer.parseInt(currentTime.substring(0,2)); +// int currentM = Integer.parseInt(currentTime.substring(2,4)); +// +// int diffM = currentM-scheduleM; +// int diffT = currentT-scheduleT; +// if (diffM < 0){ +// diffM = (currentM+60)-scheduleM; +// diffT = (currentT-1)-scheduleT; +// } +// +// message = message + "("+diffT+":"+diffM+")파일명:" + vo.getBjobTranDstcdName() +// + ",업무명:" + vo.getBjobBzwkName() +// + ",기관명:" + vo.getOsidInstiName(); +// ItmsSmsUtil.sendSMS(PropManager.getInstance().getProperty(ItmsSmsUtil.SMSINFO, ItmsSmsUtil.REQ_BY_GROUP), vo.getUapplCd(), message); +// if ( vo.getUapplCd() != null && !vo.getUapplCd().trim().equals("")){ +// if (!PropManager.getInstance().getProperty(ItmsSmsUtil.SMSINFO, ItmsSmsUtil.EAI_SEND_YN).trim().equals("")){ +// ItmsSmsUtil.sendSMS( PropManager.getInstance().getProperty(ItmsSmsUtil.SMSINFO, ItmsSmsUtil.REQ_BY_GROUP), "", message); +// } +// } +// } + + private void sendUC ( JobFileTransferVO vo ){ + + String message = "[송신지연]"; + if ( "R".equals(vo.getSendRecvYn())){ + message = "[수신지연]"; + } + + // 지연된 시간 계산 + int scheduleT = Integer.parseInt(vo.getSndrcvEndHMS().substring(0,2)); + int scheduleM = Integer.parseInt(vo.getSndrcvEndHMS().substring(2,4)); + + String currentTime = DatetimeUtil.getCurrentTime(); + int currentT = Integer.parseInt(currentTime.substring(0,2)); + int currentM = Integer.parseInt(currentTime.substring(2,4)); + + int diffM = currentM-scheduleM; + int diffT = currentT-scheduleT; + if (diffM < 0){ + diffM = (currentM+60)-scheduleM; + diffT = (currentT-1)-scheduleT; + } + + message = message + "("+diffT+":"+diffM+")파일명:" + vo.getBjobTranDstcdName() + + ",업무명:" + vo.getBjobBzwkName() + + ",기관명:" + vo.getOsidInstiName(); + logger.info("[TransferJobChecker][sendUC]" + message); + UCMsgSenderUtil.sendUCMsg( message); + } + +} diff --git a/src/com/eactive/eai/batch/telegram/TelegramDAO.java b/src/com/eactive/eai/batch/telegram/TelegramDAO.java new file mode 100644 index 0000000..302f080 --- /dev/null +++ b/src/com/eactive/eai/batch/telegram/TelegramDAO.java @@ -0,0 +1,220 @@ +package com.eactive.eai.batch.telegram; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.HashMap; + +/** +* 1. 기능 : 전문 정보 테이블에 대한 Data Access Object 이다. +* 2. 처리 개요 : 전문 정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다. +* +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : +* @since : +*/ +public class TelegramDAO extends BaseDAO implements TelegramQuery +{ + + /** + * 1. 기능 : 특정 전문 Key에 해당하는 객체를 DB에서 로딩하여 HashMap에 추가한다. + * 2. 처리 개요 : 특정 전문 정보를 SELECT해서 하나의 TelegramVO의 배열을 만들어서 저장한다. + * + * 3. 주의사항 + * + * @return + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 EAI서버 정보를 가져오다 발생되는 모든 에러 + **/ + public TelegramVO getTelegram(String telegramKey) throws DAOException + { + ResultSet rs = null; + TelegramVO telegramVO = new TelegramVO(); + + try + { + // 해당 전문의 필드의 갯수를 읽어온다. + int totalFieldCnt = this.getTelegramFieldCount(telegramKey); + + // 해당 전문의 내용을 읽어온다. + this.connect(GET_TELEGRAM_INFO); + this.preparedStatement.setString(1, telegramKey); + rs = this.executeQuery(); + + telegramVO = new TelegramVO(telegramKey, totalFieldCnt); + + while(rs.next()) + { + // telegramitem 순서값은 런타임시에는 사용하지 않는다. 대신 TelegramVO에서 item이 추가될때 순서를 부여한다. + // 이러한 이유는 TSEAIBM02에서 수정작업을 편하게 하도록 하기 위함이다. + TelegramItemVO itemVO = new TelegramItemVO(rs.getString(3).trim(), rs.getString(4).trim(), rs.getString(5).trim(), rs.getString(6).trim()); + + // 전문 필드중에 가변부가 있으면 전문의 variableFieldCheckTag를 true로 세팅한다. + if (rs.getString(5).trim().toUpperCase().equals("XX")) + { + telegramVO.setVariableFieldCheckTag(true); + } + telegramVO.addTelegramItem(itemVO); + + } + //all.put(telegramVO.getTelegramKey(), telegramVO); + + } catch(Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIMTM001", new String[] {telegramKey}); + throw new DAOException(errMsg); //전문Key (%1)에 해당하는 전문필드 정보 조회시 오류가 발생하였습니다. + } finally { + this.disconnect(); + } + return telegramVO; + } + + + /** + * 1. 기능 : 전문 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서 + * TelegramVO 객체 리스트로 생성 반환하는 메서드. + * 2. 처리 개요 : 전문 정보 전체를 SELECT해서 하나의 TelegramVO의 배열을 만들어서 저장한다. + * + * 3. 주의사항 + * + * @return + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 EAI서버 정보를 가져오다 발생되는 모든 에러 + **/ + public HashMap getAllTelegrams() throws DAOException + { + HashMap all = new HashMap(); + ResultSet rs = null; + try + { + // 전문의 전체 갯수를 읽어온다. + int totalKeyCnt = this.getTelegramKeyCount(); + + // 전문의 Key를 읽어온다. + String[] keys = new String[totalKeyCnt]; + String[] fieldsCount = new String[totalKeyCnt]; + this.connect(GET_TELEGRAM_KEYS); + rs = this.executeQuery(); + int k=0; + while(rs.next()) + { + keys[k] = rs.getString(1); + fieldsCount[k] = rs.getString(2); + k++; + } + rs.close(); + + // 전문 Key별로 해당 필드들의 내용을 읽어온다. + for(int i=0; i telegrams; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : 전문(Telegram) 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private TelegramManager() { + telegrams = new HashMap(); + + } + + /** + * 1. 기능 : TelegramManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : TelegramManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return TelegramManager Singleton object + **/ + public static TelegramManager getInstance() { + + return instance; + } + + + /* ****************************************************************** */ + /* Web Agent 호출을 위한 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 삭제한다. + */ + public boolean removeTelegram(String telegramKey) + { + TelegramVO telegramVO = telegrams.get(telegramKey); + if(telegramVO != null) + telegrams.remove(telegramKey); + return true; + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 다시 읽어온다. + */ + public TelegramVO updateTelegram(String telegramKey) throws Exception + { + // 먼저 해당 객체를 삭제한다. + removeTelegram(telegramKey); + + // 입력된 telegramKey에 해당하는 객체를 다시 읽어와서 추가한다. + addTelegram(telegramKey); + + return this.getTelegramByKey(telegramKey); + } + + /** + * 1.기능: 전문 Key에 해당하는 전문 객체를 전체 HashMap에 추가한다. + */ + private TelegramVO addTelegram(String telegramKey) throws Exception + { + // 입력된 telegramKey에 해당하는 객체를 읽어와서 HashMap에 추가한다. + TelegramDAO dao = (TelegramDAO)DAOFactory.newInstance().create(TelegramDAO.class); + TelegramVO telegramVO = dao.getTelegram(telegramKey); + telegrams.put(telegramVO.getTelegramKey(), telegramVO); + + return this.getTelegramByKey(telegramKey); + } + + + /* ****************************************************************** */ + /* TelegramManager 자체적인 메소드 정의 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : 전문 Key에 의해서 해당 전문 객체를 반환한다. + * 2. 처리 개요 : + * - HashMap(telegrams)의 Key는 전문코드와 동일하다. + * 3. 주의사항 + * + * @parm : 전문 key + * @return 해당 전문 Key의 전체 필드를 담고 있는 TelegramVO 객체를 반환 + * @exception throw TelegramNotFoundException + **/ + public TelegramVO getTelegramByKey(String telegramKey) throws Exception + { + TelegramVO telegramVO = (TelegramVO)telegrams.get(telegramKey); + if(telegramVO == null) + { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM007", new String[] {telegramKey}); + throw new Exception(errMsg); //해당 전문(%1)이 존재하지 않습니다. + } + else + return telegramVO; + } + + /** + * 1. 기능 : 입력된 전문코드에서 index에 해당하는 필드 객체(TelegramItemVO)를 반환한다. + * 2. 처리 개요 : + * - 하나의 전문은 여러개의 TelegramItemVO의 모임으로 구성된 HashMap을 가진다. + * - 이 HashMap에서 입력된 index에 해당하는 객체를 반환하면 된다. + * 3. 주의사항 + * + * @parm : 전문 key, 해당 전문에서 추출하고자하는 필드의 index + * @return 해당 전문에서 입력된 index에 해당하는 TelegramItemVO 객체를 반환 + * @exception throw TelegramNotFoundException + **/ + public TelegramItemVO getTelegramField(String telegramKey, int index) + { + TelegramVO telegramVO = (TelegramVO)telegrams.get(telegramKey); + return telegramVO.getTelegramItem(index); + } + + /** + * 1. 기능 : 해당 전문의 필드순서에 맞게 각 필드의 길이만 반환한다. + * 전문이 들어왔을 때에 Parsing하기 위한 용도이다. + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @parm : 전문 Key + * @return 해당 전문의 길이 필드만으로 구성된 String 배열을 반환한다. + * @exception throw TelegramNotFoundException + **/ + public String[] getTelegramFieldLengthsArray(String telegramKey) throws Exception + { + // 입력된 전문코드에 해당하는 TelegramVO 객체를 찾는다. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + return telegramVO.getTelegramFieldLengthsArray(); + } + + /** + * 1. 기능 : 해당 전문의 필드순서에 맞게 각 필드의 타입만 반환한다. + * 전문이 들어왔을 때에 Parsing하기 위한 용도이다. + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @parm : 전문 Key + * @return 해당 전문의 타입 필드만으로 구성된 String 배열을 반환한다. + * @exception + **/ + public String[] getTelegramFieldTypesArray(String telegramKey) throws Exception + { + // 입력된 전문코드에 해당하는 TelegramVO 객체를 찾는다. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + return telegramVO.getTelegramFieldTypesArray(); + } + + public String[] getTelegramFieldNamesArray(String telegramKey) throws Exception + { + // 입력된 전문코드에 해당하는 TelegramVO 객체를 찾는다. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + return telegramVO.getTelegramFieldNamesArray(); + } + + public String[] getTelegramFieldIDsArray(String telegramKey) throws Exception + { + // 입력된 전문코드에 해당하는 TelegramVO 객체를 찾는다. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + return telegramVO.getTelegramFieldIDsArray(); + } + + /** + * 1. 기능 : 해당 전문이 가변 길이부를 갖는 전문인지 판단한다. + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @parm : 전문 Key + * @return 해당 전문이 가변부를 가지면 true, 아니면 false + * @exception + **/ + public boolean hasVariableField(String telegramKey) throws Exception + { + // 입력된 전문코드에 해당하는 TelegramVO 객체를 찾는다. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + return telegramVO.getVariableFieldCheckTag(); + } + + /** + * 1. 기능 : 해당 전문의 전체 길이를 반환하는 메소드 + * 단, 가변부의 길이를 반환하지 않는다. + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @parm : 전문 Key + * @return 해당 전문의 길이를 반환한다. + * @exception + **/ + public int getTelegramLength(String telegramKey) throws Exception + { + return this.getTotalLength(this.getTelegramFieldLengthsArray(telegramKey)); + } + + + /** + * 1. 기능 : =============== 전문을 파싱하는 메인 메소드이다. =============== + * 전문이 들어왔을 때에 해당 전문의 길이로 파싱한 후 String[]로 반환한다. + * 파싱된 각각의 값에 대해서 해당 전문필드의 타입으로 형 검사를 실시한다. + * 2. 처리 개요 : + * - 입력된 전문을 해당 전문코드 필드의 순서대로 파싱을 수행한 후 + * 다시 필드 타입에 맞는지 형 검사를 실시한다. + * + * 3. 주의사항 + * @parm : 전문 key, 입력된 전문(String) + * @return 입력된 전문을 각 필드의 길이에 맞게 파싱한 후 String 배열로 반환한다. + * @exception throw TelegramNotFoundException(전문이 없는 경우), + * throw TelegramNotCompatable (전문의 길이가 틀리거나, 타입이 맞지 않는 경우) + **/ + public String[] parseTelegram(String telegramKey, String telegram) throws Exception + { + // 이부분에 필드 타입하고 길이를 가져오는 배열을 설정하고 Validation을 부르게 하자. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + String[] lengthsArray = telegramVO.getTelegramFieldLengthsArray(); + String[] typesArray = telegramVO.getTelegramFieldTypesArray(); + + // 반환할 String[] 초기화 + String result[] = new String[lengthsArray.length]; + + // 전문이 파싱 가능한지 미리 판단 + if(!this.checkTelegram(telegramKey, telegram)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM009", new String[] {telegramKey}); + throw new Exception(errMsg); //입력된 전문이 해당 전문(%1) 의 총 Size 와 일치하지 않습니다. + } + + int beginIndex=0; + for(int i=0; i< lengthsArray.length; i++) + { + String length_token = lengthsArray[i]; + String type_token = typesArray[i]; + + // length별로 입력된 String을 잘라낸다. + if(length_token.toUpperCase().equals("XX")) // 가변길이 부분, xx는 반드시 제일 마지막으로 전달되어야 한다. + { + result[i]=telegram.substring(beginIndex); + logger.debug("> 수신 전문필드 파싱... Index: ["+ i +"], Type: ["+ type_token +"], Length: ["+ length_token +"], Name: ["+ telegramVO.getTelegramItem(i+1).getFieldName() +"], Value: ["+ result[i] +"]");//길어서 print skip..."); + } + else + { + int delim = new Integer(length_token).intValue(); + result[i]=telegram.substring(beginIndex, beginIndex+=delim); + logger.debug("> 수신 전문필드 파싱... Index: ["+ i +"], Type: ["+ type_token +"], Length: ["+ length_token +"], Name: ["+ telegramVO.getTelegramItem(i+1).getFieldName() +"], Value: ["+ result[i] +"]"); + } + + // Parsing된 결과가 정의된 Type에 맞는지 확인, 적합하지 않으면 에러 발생 + if (!this.checkType(type_token, result[i])) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM100", new String[] {Integer.toString(i), result[i], type_token}); + throw new Exception(errMsg); //%1 번째 index 전문필드 값(%2)이 정의된 타입(%3)에 맞지 않는 부분이 있습니다. + } + } + return result; + } + + //========================================================================================== + //이하 정영우 추가 (2006.02.20) - 응답수신 F/C에서 사용 + // + //수신전문 문자열을 전문코드에 해당하는 필드 길이로 잘라서 리턴한다. + public String[] parseTelegramNotCheck(String telegramKey, String telegram) throws Exception + { + // 이부분에 필드 타입하고 길이를 가져오는 배열을 설정하고 Validation을 부르게 하자. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + String[] lengthsArray = telegramVO.getTelegramFieldLengthsArray(); + + // 반환할 String[] 초기화 + String result[] = new String[lengthsArray.length]; + + // 전문이 파싱 가능한지 미리 판단 + if(!this.checkTelegram(telegramKey, telegram)) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM009", new String[] {telegramKey}); + throw new Exception(errMsg); //입력된 전문이 해당 전문(%1) 의 총 Size 와 일치하지 않습니다. + } + + int beginIndex=0; + for(int i=0; i< lengthsArray.length; i++) + { + String length_token = lengthsArray[i]; + + // length별로 입력된 String을 잘라낸다. + if(length_token.toUpperCase().equals("XX")) // 가변길이 부분, xx는 반드시 제일 마지막으로 전달되어야 한다. + { + result[i]=telegram.substring(beginIndex); + logger.debug("> 수신 전문필드 파싱... Index: ["+ i +"], Length: ["+ length_token +"], Name: ["+ telegramVO.getTelegramItem(i+1).getFieldName() +"], Value: ["+ result[i] +"]");//길어서 print skip..."); + } + else + { + int delim = new Integer(length_token).intValue(); + result[i]=telegram.substring(beginIndex, beginIndex+=delim); + logger.debug("> 수신 전문필드 파싱... Index: ["+ i +"], Length: ["+ length_token +"], Name: ["+ telegramVO.getTelegramItem(i+1).getFieldName() +"], Value: ["+ result[i] +"]"); + } + } + return result; + } + + //파싱된 수신전문을 전문코드에 해당하는 필드 타입이 맞는지 체크한다. + public void checkParsedTelegram(String telegramKey, String[] telegramFiels) throws Exception + { + // 이부분에 필드 타입하고 길이를 가져오는 배열을 설정하고 Validation을 부르게 하자. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + String[] typesArray = telegramVO.getTelegramFieldTypesArray(); + + for(int i=0; i< typesArray.length; i++) + { + String type_token = typesArray[i]; + + // Parsing된 결과가 정의된 Type에 맞는지 확인, 적합하지 않으면 에러 발생 + if(!this.checkType(type_token, telegramFiels[i])) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM100", new String[] {Integer.toString(i), telegramFiels[i], type_token}); + throw new Exception(errMsg); //%1 번째 index 전문필드 값(%2)이 정의된 타입(%3)에 맞지 않는 부분이 있습니다. + } + } + } + //========================================================================================== + + /** + * 1. 기능 : parseTelegram() 메소드에서 호출되는 private 메소드 + * 전문의 필드의 type을 체크한다 + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @parm : 전문필드 Type, 필드값(String) + * @return 타입에 적합한 경우 true를 반환한다. + * @exception + **/ + private boolean checkType(String type, String str) + { + if(type.equals("AA")||type.equals("A")) // 문자만 와야 됨 + { + return StringUtil.isAlpha(str); + } + else if(type.equals("NN")||type.equals("N")) + { + return StringUtil.isNumeric(str); + } + else if(type.equals("AN")) + { + return true; + } + else // 타입이 정의되지 않은 경우-이런 경우는 없어야 한다. + { + // 나중에 에러 처리 할 것 + return false; + } + } + + /** + * 1. 기능 : parseTelegram() 메소드에서 호출되는 private 메소드 + * 전문의 전체 길이가 해당 전문정의에서 요구하는 길이와 같은지 확인한다. + * 2. 처리 개요 : + * - 가변 필드가 있는 경우에는 가변 필드가 0인 경우를 고려하여 전체 길이가 정의된 길이보다 같거나 커야한다. + * + * 3. 주의사항 + * + * @parm : 전문 Key, 전체전문(String) + * @return 길이가 맞는 경우 true를 반환한다. + * @exception + **/ + private boolean checkTelegram(String telegramKey, String telegram) throws Exception + { + // Key에 해당하는 전문을 가져온다. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + + // 해당 전문이 가변부가 있는지 확인한다. + boolean variableFieldCheckTag = telegramVO.getVariableFieldCheckTag(); + String[] telegramFiledLengths = telegramVO.getTelegramFieldLengthsArray(); + + // 가변길이 전문이 아닌 경우 - 필드의 길이와 전문의 길이가 반드시 같아야 한다. + if(!variableFieldCheckTag) + { + if(telegram.length() == this.getTotalLength(telegramFiledLengths)) + { + return true; + } + else + { + logger.debug(" ************** 입력전문 길이 : " + telegram.length()); + logger.debug(" ************** 요구전문 길이 : " + this.getTotalLength(telegramFiledLengths)); + return false; + } + } + else // 가변길이 전문인 경우, 입력된 전문의 길이는 전문에 정의된 필드들의 길이의 합보다 크거나 같아야 된다. + { + if(telegram.length() >= this.getTotalLength(telegramFiledLengths)) + { + return true; + } + else + { + logger.debug(" ************** 입력전문 길이(가변) : " + telegram.length()); + logger.debug(" ************** 요구전문 길이(가변) : " + this.getTotalLength(telegramFiledLengths)); + return false; + } + } + + } + + /** + * 1. 기능 : parseTelegram() 메소드에서 호출되는 private 메소드 + * String 배열을 받아들여 전체 값의 합을 반환한다. + * 2. 처리 개요 : + * - 가변 필드가 있는 경우에는 제외하고 계산한다. + * + * 3. 주의사항 + * + * @parm : 전문길이 배열 + * @return 배열의 각 항목의 값을 모두 더해서 반환한다. + * @exception + **/ + private int getTotalLength(String[] lengths) + { + int totalLength = 0; + + int i=0; + while(i < lengths.length) + { + if (!lengths[i].trim().toUpperCase().equals("XX")) + totalLength += new Integer(lengths[i]).intValue(); + i++; + } + return totalLength; + } + + + /** + * 1. 기능 : =============== 전문을 생성하는 메인 메소드이다. =============== + * 전문의 코드번호(Key)와 각 전문을 구성하는 값들을 String[] 형태로 받아들인다. + * String[]에서 하나씩 + * 2. 처리 개요 : + * - String[]에서 하나씩 값을 꺼내서 해당 필드의 Type, Length에 의해서 값을 보정한다. + * - 보정작업이란 입력된 값의 길이가 필드 정의보다 짧은 경우 대체 문자로 치환한다. + * - 대체 문자 + * 1) 숫자(NN, N): 오른쪽 정렬하고 나머지는 0으로 채운다. + * 2) 문자(AA, A): 왼쪽 정렬하고 나머지는 공백으로 채운다. + * 3) 문자,숫자(AN): 문자 기준으로 정렬한다. + * + * 3. 주의사항 + * + * @parm : 전문 key, 전문필드의 값(String[]) + * @return 하나의 전문을 나타내는 String으로 반환 + * @exception throw TelegramNotFoundException(전문 코드가 없는 경우), + * throw TelegramFieldNotCompatable (입력된 값이 정의된 Field의 길이보다 긴 경우) + **/ + public String createTelegram(String telegramKey, String[] objs) throws Exception + { + String telegram = ""; + + // Key에 해당하는 전문을 가져온다. + TelegramVO telegramVO = this.getTelegramByKey(telegramKey); + String[] telegramFieldLengthsArray = telegramVO.getTelegramFieldLengthsArray(); + String[] telegramFieldTypesArray = telegramVO.getTelegramFieldTypesArray(); + + // 전문 생성이 가능한지 사전 체크 + if (objs.length != telegramFieldLengthsArray.length) + { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM011", new String[] {Integer.toString(telegramFieldLengthsArray.length), Integer.toString(objs.length)}); + throw new Exception(errMsg); //전문 생성을 위한 요구 필드 개수가 적합하지 않습니다. (요구필드수: %1, 입력필드수: %2) + } + + // 배열에서 값을 꺼내서 값을 모두 더한다. + for(int i=0; i 송신 전문필드 생성... Index: ["+ i +"], Type: ["+ telegramFieldTypesArray[i] +"], Length: ["+ telegramFieldLengthsArray[i] +"], Name: ["+ telegramVO.getTelegramItem(i+1).getFieldName() +"], Value: ["+ fieldValue +"]"); + telegram += fieldValue; + } + + return telegram; + } + + /** + * 1. 기능 : createTelegram() 메소드에서 호출되는 private 메소드 + * 전달된 값을 전문 정의에 맞춰 정렬 및 Data 보정작업을 수행한다. + * + * 2. 처리 개요 : + * - 가변 필드인 경우에는 그대로 반환한다. (즉, 보정작업을 수행하지 않는다.) + * - 전문필드의 이름을 입력으로 받는 이유는 로깅시 어느 필드인지를 알기 위함이다. + * 3. 주의사항 + * + * @parm : 전문필드에 해당하는 값, 전문필드의 형, 전문필드의 길이, 전문필드의 이름 + * @return 입력된 값을 형에 따라 Data 보정작업을 수행한 String을 반환한다. + * @exception throw TelegramFieldNotCompatable (입력된 값이 정의된 Field의 길이보다 긴 경우) + **/ + private String createField(String fieldContent, String fieldType, String fieldLength, String fieldName) throws Exception + { + // 입력값을 대문자로 변경한다. - 혹시나 소문자로 전달되는 것이 있을까봐... + fieldType = fieldType.toUpperCase(); + fieldLength = fieldLength.toUpperCase(); + + // 가변길이부인 경우 입력된 값을 그냥 반환한다. + if(fieldLength.equals("XX")) + return fieldContent; + else + { + // 정의된 필드의 길이 + int fieldLen = new Integer(fieldLength).intValue(); + + // 정의된 필드의 길이보다 큰 경우 예외 처리 + if (fieldContent.length() > fieldLen) + { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM012", new String[] {fieldName, fieldLength, Integer.toString(fieldContent.length()), fieldContent}); + throw new Exception(errMsg); //전문필드 생성시 오류가 발생하였습니다. (전문필드명: %1, 정의된필드길이: %2, 입력된필드길이: %3, 입력된필드값: %4) + } + + // 보정작업 구간 + if(fieldType.equals("AN")||fieldType.equals("AA")||fieldType.equals("A")) // 문자형인 경우-왼쪽정렬 및 Blank처리 + { + while(fieldContent.length() < fieldLen) + { + fieldContent += " "; // 공백 1칸 처리 + } + } + else if(fieldType.equals("NN")||fieldType.equals("N")) + { + while(fieldContent.length() < fieldLen) + { + fieldContent = "0" + fieldContent; // 0을 앞에 추가한다. + } + } + else + { + String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM013", new String[] {fieldType}); + throw new Exception(errMsg); //정의되지 않은 전문필드 Type입니다. (%1) + } + return fieldContent; + } + } + + /** + * 1. 기능 : 전체 전문을 반환하는 메소드 + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @return 전체 전문의 정보 + * @exception + **/ + public HashMap getAllTelegrams(){ + return this.telegrams; + } + + + /* ****************************************************************** */ + /* Lifecycle 인터페이스에 정의된 메소드 */ + /* ****************************************************************** */ + + /** + * 1. 기능 : Lifecycle의 start 메서드로 TelegramManager를 초기화하는 메서드 + * 2. 처리 개요 : TelegramDAO를 이용해 추출 전문 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, + * EAIServerDAO를 통해 Rule 정보를 가져온다. + * DAOExcepiton이 발생될 경우 + **/ + public void start() throws LifecycleException + { + if (started) throw new LifecycleException("BECEAIMTM014"); //TelegramMansger 가 이미 시작되었습니다. + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + DAOFactory daoFactory = DAOFactory.newInstance(); + TelegramDAO dao = null; + try { + dao = (TelegramDAO)daoFactory.create(TelegramDAO.class); + this.telegrams = dao.getAllTelegrams(); + + } catch (DAOException e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIMTM015"); + throw new LifecycleException(errMsg); //Lifecycle 에서 TelegramMansger 시작 시 (전문정보 로딩) 오류가 발생하였습니다. + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) throw new LifecycleException("BECEAIMTM016"); //TelegramMansger 가 이미 종료되었습니다. + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/telegram/TelegramQuery.java b/src/com/eactive/eai/batch/telegram/TelegramQuery.java new file mode 100644 index 0000000..d278c3e --- /dev/null +++ b/src/com/eactive/eai/batch/telegram/TelegramQuery.java @@ -0,0 +1,62 @@ +package com.eactive.eai.batch.telegram; + +import com.eactive.eai.common.dao.Keys; + +/** +* 1. 기능 : EAIServerDAO에서 사용하는 SQL Query를 정의한 Interface +* 2. 처리 개요 : +* - EAIServerDAO에서 사용하는 SQL Query를 정의한 Interface +* 3. 주의사항 +* +* @author : YCLee 05/12/22 +* @version : v 1.0.0 +* @see : +* @since :JDK v1.4.2 +*/ +public interface TelegramQuery +{ + /** + * 전문의 갯수를 반환하는 Query + */ + public static final String GET_TELEGRAM_KEYS_COUNT = + "SELECT COUNT(DISTINCT B.MsgGroupDstcd) AS count \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBM01 A, \n" + + Keys.TABLE_OWNER + "TSEAIBM02 B \n" + + "WHERE A.MsgItemDsticName = B.MsgItemDsticName "; + + /** + * 전문의 대표 Key 값을 반환하는 Query + */ + public static final String GET_TELEGRAM_KEYS = + "SELECT DISTINCT B.MsgGroupDstcd, \n" + + " COUNT(B.MsgItemDsticName) \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBM01 A,\n" + + Keys.TABLE_OWNER + "TSEAIBM02 B \n" + + "WHERE A.MsgItemDsticName = B.MsgItemDsticName\n" + + "GROUP BY B.MsgGroupDstcd "; + + /** + * 해당 전문 Key에 해당하는 필드들을 조회하는 Query + */ + public static final String GET_TELEGRAM_INFO = + "SELECT A.MsgGroupDstcd ,\n" + + " A.MsgClmnSeq ,\n" + + " B.MsgClmnName ,\n" + + " B.MsgClmnAttriPtrnCd,\n" + + " B.MsgClmnVal ,\n" + + " A.MsgItemDsticName \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBM02 A,\n" + + Keys.TABLE_OWNER + "TSEAIBM01 B \n" + + "WHERE A.MsgItemDsticName = b.MsgItemDsticName\n" + + "AND A.MsgGroupDstcd=? \n" + + "ORDER BY A.MsgClmnSeq \n"; + + /** + * 특정 전문의 필드 갯수를 반환하는 Query + */ + public static final String GET_TELEGRAM_FIELD_COUNT = + "SELECT COUNT(MsgGroupDstcd) \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBM02\n" + + "WHERE MsgGroupDstcd = ? "; + +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/telegram/TelegramVO.java b/src/com/eactive/eai/batch/telegram/TelegramVO.java new file mode 100644 index 0000000..c4c0456 --- /dev/null +++ b/src/com/eactive/eai/batch/telegram/TelegramVO.java @@ -0,0 +1,242 @@ +package com.eactive.eai.batch.telegram; + +import java.io.Serializable; +import java.util.HashMap; + +public class TelegramVO implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** + * 전문의 Key + */ + private String telegramKey; + + /** + * 전문 필드의 각 길이들의 배열 + */ + private String[] telegramFieldLengths; + + /** + * 전문 필드가 가변부를 가지는지를 판단하는 태그 + * true: 가변부가 있는 전문, false: 가변부가 없는 전문 + */ + private boolean variableFieldCheckTag; + + /** + * 전문 아이템의 내용 - TelegramItemVO의 배열로 구성된다. + */ + private HashMap itemVOs; + + + /* *********************** 생성자 *********************** */ + + /** + * 1. 기능 : Defualt Constructor + * 2. 처리 개요 : + * - Defualt Constructor + * 3. 주의사항 + * + **/ + public TelegramVO() { + } + + /** + * 1. 기능 : Constructor, 전문 Key와 필드 집합으로 생성 + * 2. 처리 개요 : + * - EAI 서버 이름을 저장하는 생성자 함수 + * 3. 주의사항 + * + * @param + **/ + public TelegramVO(String telegramKey, HashMap itemVOs) { + this.telegramKey = telegramKey; + this.telegramFieldLengths = new String[itemVOs.size()]; + this.variableFieldCheckTag = false; + this.itemVOs = itemVOs; + } + + /** + * 1. 기능 : Constructor, 전문 Key로 생성 + * 2. 처리 개요 : + * - EAI 서버 이름을 저장하는 생성자 함수 + * 3. 주의사항 + * + * @param telegramKey 전문의 Key + **/ + public TelegramVO(String telegramKey, int fieldCount) { + this.telegramKey = telegramKey; + this.telegramFieldLengths = new String[fieldCount]; + this.variableFieldCheckTag = false; + this.itemVOs = new HashMap(); + } + + /* *********************** GET, SET 함수 *********************** */ + + /** + * 1. 기능 : telegramKey를 세팅하는 setter 메소드 + * 2. 처리 개요 : + * 3. 주의사항 + * + * @return + **/ + public void setTelegramKey(String telegramKey) { + this.telegramKey = telegramKey; + } + + /** + * 1. 기능 : Rule Key를 반환하는 getter method + * 2. 처리 개요 : + * - Rule Key를 반환한다. + * 3. 주의사항 + * + * @return + **/ + public String getTelegramKey() { + return this.telegramKey; + } + + + /** + * 1. 기능 : 전문을 구성하는 필드의 갯수를 반환한다. + * 2. 처리 개요 : + * - 전문 필드로 구성되는 HashMap의 사이즈를 반환한다. + * 3. 주의사항 + * + **/ + public int getFieldSize() { + return this.itemVOs.size(); + } + + /** + * 1. 기능 : 전문의 필드중에 가변부가 있는지를 판단하는 태그 + * 2. 처리 개요 : + * - 전문 필드중 가변부의 존재 여부를 반환한다. + * - true: 가변부가 있는 전문, false: 가변부가 없는 전문 + * 3. 주의사항 + * + **/ + public void setVariableFieldCheckTag(boolean tag) + { + this.variableFieldCheckTag = tag; + } + + /** + * 1. 기능 : 전문의 필드중에 가변부가 있는지를 판단하는 태그 + * 2. 처리 개요 : + * - 전문 필드중 가변부의 존재 여부를 반환한다. + * - true: 가변부가 있는 전문, false: 가변부가 없는 전문 + * 3. 주의사항 + * + **/ + public boolean getVariableFieldCheckTag() + { + return this.variableFieldCheckTag; + } + + /** + * 1. 기능 : 전문 필드의 길이로 구성된 배열을 반환한다. + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + **/ + public String[] getTelegramFieldLengthsArray() + { + String lengthsarray[] = new String[itemVOs.size()]; + for(int i=0; i[" + encType + "]"); +// logger.debug( "plainFile-->[" + plainFile + "]"); +// logger.debug( "encFile-->[" + encFile + "]"); +// String groupName = ENC_TYPE_INFO + "{" + encType + "}"; +// String serverType = PropManager.getInstance().getProperty( groupName, ENC_SERVER_TYPE); +// if (serverType == null) { +// logger.warn("'암/복호화 서버타입' 프라퍼티 정보가 없습니다. (PropGroupName:"+ groupName +", PropName:"+ ENC_SERVER_TYPE +")"); +// throw new Exception(); +// } +// +// logger.debug( "KEY-->[" + new String(getKey(encType)) + "]"); +// +// if ( serverType.equalsIgnoreCase(ENC_SERVER_TYPE_SERVER) ){ +// XCServerBigfile xs = new XCServerBigfile(getKey(encType)); +// xs.encryptBig( plainFile, encFile ); +// }else if( serverType.equalsIgnoreCase(ENC_SERVER_TYPE_CLIENT) ){ +// XCClientBigfile xc = new XCClientBigfile(getKey(encType)); +// xc.encryptBig( plainFile, encFile ); +// }else{ +// throw new Exception(); +// } +// } +// +// public void decryptFile( String encType, String encFile, String plainFile) throws Exception{ +// logger.debug( "encType-->[" + encType + "]"); +// logger.debug( "plainFile-->[" + plainFile + "]"); +// logger.debug( "encFile-->[" + encFile + "]"); +// +// String groupName = ENC_TYPE_INFO + "{" + encType + "}"; +// String serverType = PropManager.getInstance().getProperty( groupName, ENC_SERVER_TYPE); +// if (serverType == null) { +// logger.warn("'암/복호화 서버타입' 프라퍼티 정보가 없습니다. (PropGroupName:"+ groupName +", PropName:"+ ENC_SERVER_TYPE +")"); +// throw new Exception(); +// } +// +// logger.debug( "KEY-->[" + new String(getKey(encType)) + "]"); +// +// if ( serverType.equalsIgnoreCase(ENC_SERVER_TYPE_SERVER) ){ +// XCServerBigfile xs = new XCServerBigfile(getKey(encType)); +// xs.decryptBig( encFile, plainFile ); +// }else if( serverType.equalsIgnoreCase(ENC_SERVER_TYPE_CLIENT) ){ +// XCClientBigfile xc = new XCClientBigfile(getKey(encType)); +// xc.decryptBig( encFile, plainFile ); +// }else{ +// throw new Exception(); +// } +// } +// +//} diff --git a/src/com/eactive/eai/common/activemq/AmqQueueProducer.java b/src/com/eactive/eai/common/activemq/AmqQueueProducer.java new file mode 100644 index 0000000..58f3525 --- /dev/null +++ b/src/com/eactive/eai/common/activemq/AmqQueueProducer.java @@ -0,0 +1,66 @@ +package com.eactive.eai.common.activemq; + +import java.io.Serializable; + +import javax.jms.Connection; +import javax.jms.DeliveryMode; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.MessageProducer; +import javax.jms.ObjectMessage; +import javax.jms.Session; + +import org.apache.activemq.ActiveMQConnectionFactory; + +import com.eactive.eai.common.util.Logger; + +public class AmqQueueProducer { + + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + Connection connection = null; + Session session = null; + MessageProducer producer = null; + String connectionUrl = null; + String queueName = null; + + public AmqQueueProducer(String connectionUrl, String queueName) throws Exception { + this.connectionUrl = connectionUrl; + this.queueName = queueName; + } + + public void sendMessage(Serializable object) throws Exception { + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUrl); + connectionFactory.setTrustAllPackages(true); + + // Create a Connection + connection = connectionFactory.createConnection(); + connection.start(); + + // Create a Session + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Create the destination (Topic or Queue) + Destination destination = session.createQueue(queueName); + producer = session.createProducer(destination); + producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + ObjectMessage message = session.createObjectMessage(object); + producer.send(message); + } + catch(Exception ex) { + logger.error("Send Error = " + ex.getMessage(), ex); + throw ex; + } + finally { + if(session != null) + try { + session.close(); + } catch (JMSException e) { } + if(connection != null) + try { + connection.close(); + } catch (JMSException e) { } + } + } +} diff --git a/src/com/eactive/eai/common/dao/BaseDAO.java b/src/com/eactive/eai/common/dao/BaseDAO.java new file mode 100644 index 0000000..60fb5d8 --- /dev/null +++ b/src/com/eactive/eai/common/dao/BaseDAO.java @@ -0,0 +1,231 @@ +package com.eactive.eai.common.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import javax.sql.DataSource; + + +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.ServiceLocator; + +/** +* 1. 기능 : DB Access 관련 로직을 구현하기 위한 DAO 클래스의 기본 기능을 갖는 Base 클래스 +* 2. 처리 개요 : DB Access 관련 로직을 구현하기 위한 DAO 클래스의 기본 기능을 갖는 Base 클래스를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public abstract class BaseDAO +{ + /** + * JDBC Connection object + */ + protected Connection conn; + /** + * JDBC PreparedStatement + */ + protected PreparedStatement preparedStatement; + /** + * JDBC DataSource의 JNDI 이름 + */ + protected String jndiName; + + protected Logger logger; + + protected static boolean isApplication; + + static { + String wlServer = System.getProperty("weblogic.Name"); + isApplication = (wlServer==null)? true : false; + } + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : jndiName을 Keys.EAI_DATASOURCE로 초기화한다. + * 3. 주의사항 + * + **/ + public BaseDAO() { + this.jndiName = Keys.EAI_DATASOURCE; + this.logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + } + + /** + * 1. 기능 : jndiDataSource 이름을 초기화하기 위한 setter 메서드 + * 2. 처리 개요 : jndiDataSource 이름을 초기화한다. + * - + * 3. 주의사항 + * + * @param jndiDataSource JDBCDataSource의 jndi 이름 + **/ + protected void setJNDIName(String jndiDataSource) { + this.jndiName = jndiDataSource; + } + + /** + * 1. 기능 : JDBC Connection 을 생성하는 메서드 + * 2. 처리 개요 : JDBC DataSource를 JNDI 서비스로 부터 얻어 Connection 객체를 생성 초기화하고, + * Connection으로 부터 PreparedStatement를 얻어 초기화한다. + * + * 3. 주의사항 + * + * @param query 실행한 SQL Query + * @exception DAOException Connection 및 PreparedStatement를 생성 초기화 할때 발생하는 오류 + **/ + protected void connect(String query) throws DAOException { + try { + if (conn != null && !conn.isClosed()) { + logger.warn("★★★★★ Connection 이 이미 연결되어있습니다. 기존 Connection의 PreparedStatement를 재설정합니다."); + closeStatement(); + } else { + ServiceLocator sl = ServiceLocator.getInstance(); + DataSource dataSource = sl.getDataSource(jndiName); + + conn = dataSource.getConnection(); + } + + preparedStatement = conn.prepareStatement(query); + + } catch(Exception e) { + logger.error("BaseDAO:connect 시 에러 발생["+ e.toString() + "]"); + throw new DAOException("BaseDAO:connect 시 에러 발생["+ e.toString() + "]"); + } + } + + /** + * 1. 기능 : JDBC Connection 을 생성하는 메서드 + * 2. 처리 개요 : JDBC DataSource를 JNDI 서비스로 부터 얻어 Connection 객체를 생성 초기화하고, + * Connection으로 부터 PreparedStatement를 얻어 초기화한다. + * - + * 3. 주의사항 + * + * @param providerURL DataSource가 Remote 서버에 있을 경우 Remote 서버의 URL + * @param query 실행한 SQL Query + * @exception DAOException Connection 및 PreparedStatement를 생성 초기화 할때 발생하는 오류 + **/ + protected void connect(String providerURL, String query) throws DAOException { + try { + if (conn != null && !conn.isClosed()) { + logger.warn("★★★★★ Connection 이 이미 연결되어있습니다. 기존 Connection의 PreparedStatement를 재설정합니다."); + closeStatement(); + + } else { + ServiceLocator sl = ServiceLocator.getInstance(); + DataSource dataSource = sl.getRemoteDataSource(providerURL, jndiName); + conn = dataSource.getConnection(); + } + + preparedStatement = conn.prepareStatement(query); + } catch(Exception e) { + logger.error("BaseDAO:connect 시 에러 발생["+ e.toString() + "]"); + throw new DAOException("BaseDAO:connect 시 에러 발생["+ e.toString() + "]"); + } + } + + /** + * 1. 기능 : 초기화된 SQL Query를 실행하여 결과에 접근하기 위한 ResultSet을 반환하는 메서드 + * 2. 처리 개요 : PreparedStatement의 executeQuery를 실행하고 결과값인 ResultSet을 반환한다. + * - + * 3. 주의사항 + * + * @return SELECT Query 결과 + * @exception DAOException SQLException 발생 시 + **/ + protected ResultSet executeQuery() throws DAOException { + try { + ResultSet rs = preparedStatement.executeQuery(); + return rs; + } catch(SQLException e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAICDB102")); + } + } + + /** + * 1. 기능 : 초기화된 SQL Query를 실행하여 결과에 접근하기 위한 ResultSet을 반환하는 메서드 + * 2. 처리 개요 : PreparedStatement의 executeUpdate를 실행하고 결과값인 변경된 record 수를 반환한다. + * - + * 3. 주의사항 + * + * @return 변경된 Record 수 + * @exception DAOException SQLException 발생 시 + **/ + protected int executeUpdate() throws DAOException { + try { + int result = preparedStatement.executeUpdate(); + return result; + } catch(SQLException e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAICDB103")); + } + } + + /** + * 1. 기능 : PreparedStatement를 재 초기화하는 메서드 + * 2. 처리 개요 : 기존 PreparedStatement를 close하고, 새로운 PreparedStatement를 생성 초기화한다. + * - + * 3. 주의사항 + * + * @param query PreparedStatement초기화하기 위한 SQL Query + * @exception DAOException PreparedStatemnt를 생성하다 발생하는 SQLException + **/ + protected void prepareStatement(String query) throws DAOException { + try { + closeStatement(); + preparedStatement = conn.prepareStatement(query); + + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAICDB104")); + } + } + + /** + * 1. 기능 : 생성한 Connection과 PreparedStatement를 close하는 메서드 + * 2. 처리 개요 : 생성한 Connection,PreparedStatement를 close 한다. + * - + * 3. 주의사항 + * + * @exception DAOException + **/ + protected void disconnect() throws DAOException{ + closeStatement(); + closeConnection(); + } + + /** + * 1. 기능 : 생성한 PreparedStatement를 close하는 메서드 + * 2. 처리 개요 : 생성한 PreparedStatement를 close한다. + * - + * 3. 주의사항 + * + * @exception DAOException + **/ + protected void closeStatement() throws DAOException { + if (preparedStatement != null) { + try { preparedStatement.close(); } catch(Exception e) {throw new DAOException("BECEAICDB107");} + } + } + + /** + * 1. 기능 : 생성한 Connection를 close하는 메서드 + * 2. 처리 개요 : 생성한 Connection를 close한다. + * - + * 3. 주의사항 + * + * @exception DAOException + **/ + protected void closeConnection() throws DAOException{ + + try { + if (conn != null) conn.close(); + } catch (Exception e) { + throw new DAOException("BECEAICDB108"); + } + } +} diff --git a/src/com/eactive/eai/common/dao/DAOException.java b/src/com/eactive/eai/common/dao/DAOException.java new file mode 100644 index 0000000..8383c07 --- /dev/null +++ b/src/com/eactive/eai/common/dao/DAOException.java @@ -0,0 +1,43 @@ +package com.eactive.eai.common.dao; + +/** +* 1. 기능 : Data Access Object 예외 처리를 정의한 Exception 클래스 +* 2. 처리 개요 : DAO 예외 처리 정의를 위한 Exception 클래스 이다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class DAOException extends Exception +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : Default Constructor + * - + * 3. 주의사항 + * + **/ + public DAOException() { + super("DAOException is occured."); + } + + /** + * 1. 기능 : 오류 메시지를 저장하는 생성자 함수 + * 2. 처리 개요 : 파라미터의 오류 메시지를 저장한다. + * - + * 3. 주의사항 + * + * @param msg 오류 메시지 + **/ + public DAOException(String msg) { + super(msg); + } +} diff --git a/src/com/eactive/eai/common/dao/DAOFactory.java b/src/com/eactive/eai/common/dao/DAOFactory.java new file mode 100644 index 0000000..2ebe4ca --- /dev/null +++ b/src/com/eactive/eai/common/dao/DAOFactory.java @@ -0,0 +1,92 @@ +package com.eactive.eai.common.dao; + +import com.eactive.eai.common.exception.ExceptionUtil; + +/** +* 1. 기능 : DAO 객체를 생성하기 위한 Factory 클래스 +* 2. 처리 개요 : DAO 객체를 생성하는 Factory 메서드를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +@SuppressWarnings("rawtypes") +public class DAOFactory +{ + + /** + * 1. 기능 : Default Contructor + * 2. 처리 개요 : Default Contructor + * - + * 3. 주의사항 + * + **/ + private DAOFactory() { + + } + + /** + * 1. 기능 : DAOFactory 객체를 생성 반환하는 메서드 + * 2. 처리 개요 : DAOFactory 객체를 생성 반환한다. + * - + * 3. 주의사항 + * + * @return DAOFactory + **/ + public static DAOFactory newInstance() { + return new DAOFactory(); + } + + /** + * 1. 기능 : BaseDAO 객체를 생성 반환하는 메서드 + * 2. 처리 개요 : 파라미터의 DAO 객체를 생성 반환한다. + * - + * 3. 주의사항 + * + * @param daoClassName 생성할 DAO 클래스 + * @return BaseDAO Data Access Object + * @exception 클래스를 찾지 못하거나 객체를 생성하지 못할 경우 + **/ + public BaseDAO create(String daoClassName) throws DAOException { + Class daoClass = null; + try { + daoClass = Class.forName(daoClassName); + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAICDB111")); + } + + BaseDAO dao = null; + try { + dao = (BaseDAO)daoClass.newInstance(); + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAICDB112")); + } + + return dao; + } + + /** + * 1. 기능 : BaseDAO 객체를 생성 반환하는 메서드 + * 2. 처리 개요 : 파라미터의 DAO 객체를 생성 반환한다. + * - + * 3. 주의사항 + * + * @param daoClass 생성할 DAO 클래스 + * @return BaseDAO Data Access Object + * @exception 클래스를 찾지 못하거나 객체를 생성하지 못할 경우 + **/ + public BaseDAO create(Class daoClass) throws DAOException { + BaseDAO dao = null; + try { + dao = (BaseDAO)daoClass.newInstance(); + } catch(Exception e) { + //throw new DAOException("Cannot create a instance of DAO class. - "+e.getMessage()); + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAICDB112")); + } + + return dao; + } +} diff --git a/src/com/eactive/eai/common/dao/Keys.java b/src/com/eactive/eai/common/dao/Keys.java new file mode 100644 index 0000000..ee7e695 --- /dev/null +++ b/src/com/eactive/eai/common/dao/Keys.java @@ -0,0 +1,35 @@ +package com.eactive.eai.common.dao; + +/** +* 1. 기능 : DAO에서 사용하는 JDBC DataSource에 대한 JNDI 이름을 정의한 상수 클래스 +* 2. 처리 개요 : DAO에서 사용하는 JDBC DataSource에 대한 JNDI 이름을 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public interface Keys +{ + /** + * EAI 프레임웍에서 사용하는 기본 DataSource에 대한 JNDI 이름 + */ + public static final String EAI_DATASOURCE = "jdbc/dsCHN_fep"; + + /** + * TABLE 의 OWNER 명 + */ + public static final String TABLE_OWNER_KEY = "eai.tableowner"; + public static final String SERVER_KEY = "inst.Name"; + + public static final String TABLE_OWNER = System.getProperty(TABLE_OWNER_KEY)+"."; + public static final String BAP01_JOB_QUEUE = "jms/qu01Bap11Svr01JobQueue"; + public static final String BAP01_TIMER_QUEUE = "jms/qu01Bap11Svr01TimerQueue"; + public static final String BAP02_JOB_QUEUE = "jms/qu01Bap21Svr01JobQueue"; + public static final String BAP02_TIMER_QUEUE = "jms/qu01Bap21Svr01TimerQueue"; + + public static final String CONNECT_FACTORY = "jms/cft01BapConnectionFactory"; + +} diff --git a/src/com/eactive/eai/common/exception/ExceptionUtil.java b/src/com/eactive/eai/common/exception/ExceptionUtil.java new file mode 100644 index 0000000..4f5a076 --- /dev/null +++ b/src/com/eactive/eai/common/exception/ExceptionUtil.java @@ -0,0 +1,194 @@ +package com.eactive.eai.common.exception; + +import com.eactive.eai.batch.code.CodeMessageHandler; +import com.eactive.eai.batch.code.CodeMessageManager; +import com.eactive.eai.batch.code.CodeMessageVO; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Exception 발생 시 메시지를 처리하기 위한 Utility 클래스 +* 2. 처리 개요 : Exception 발생 시 메시지를 처리하는 메서드를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public abstract class ExceptionUtil +{ + //Exception 파일 로거 + private static Logger exLogger = Logger.getLogger(Logger.LOGGER_EXCEPTION); + + //SMS전송 파일 로거 + private static Logger smsLogger = Logger.getLogger(Logger.LOGGER_SMS); + + + private static void writeExceptionLog(String code, String msg, Throwable cause) { + if (cause == null) { + if (code.startsWith("BW")) exLogger.warn (msg); + else if (code.startsWith("BE")) exLogger.error(msg); + else if (code.startsWith("BF")) exLogger.error(msg); + } else { + if (code.startsWith("BD")) exLogger.debug(msg, cause); + else if (code.startsWith("BI")) exLogger.info (msg, cause); + else if (code.startsWith("BW")) exLogger.warn (msg, cause); + else if (code.startsWith("BE")) exLogger.error(msg, cause); + else if (code.startsWith("BF")) exLogger.error(msg, cause); + else exLogger.debug(msg, cause); + } + } + + + public static String getErrorCode(String code) { + return getErrorCode(null, null, code, null); + } + + public static String getErrorCode(String code, String[] args) { + return getErrorCode(null, null, code, args); + } + + public static String getErrorCode(Throwable cause, String code) { + return getErrorCode(cause, null, code, null); + } + + public static String getErrorCode(Throwable cause, String code, String[] args) { + return getErrorCode(cause, null, code, args); + } + + + + + public static String getErrorCode(BatchDoc batchMsgDoc, String code) { + return getErrorCode(null, batchMsgDoc, code, null); + } + + public static String getErrorCode(Throwable cause, BatchDoc batchMsgDoc, String code) { + return getErrorCode(cause, batchMsgDoc, code, null); + } + + public static String getErrorCode(BatchDoc batchMsgDoc, String code, String[] args) { + return getErrorCode(null, batchMsgDoc, code, args); + } + + public static String getErrorCode(Throwable cause, BatchDoc batchMsgDoc, String code, String[] args) { + + code = StringUtil.nvlTrim(code); + + String returnMsg = make(batchMsgDoc, code, args); + String errMsg = (cause == null)? "" : StringUtil.nvlTrim(cause.getMessage()); + + //사용자 Exception : 메시지에 '에러코드'가 설정된 경우 + if (isErrorCode(errMsg)) { + returnMsg += "\n caused by..."+ make(errMsg); + + //사용자 Exception : 메시지에 '[에러코드] 에러메시지' 형태가 설정된 경우 + } else if (isErrorCodeMsg(errMsg)) { + returnMsg += "\n caused by..."+ errMsg; + + //Java Exception + } else if (cause != null) { + returnMsg += "\n caused by..."+ cause.toString(); + } + + //batchMsgDoc 이 null 이 아닌 경우 배치메시지의 에러메시지를 Append + if (batchMsgDoc != null) { + String prevMsg = batchMsgDoc.getBatchMsg().getBody().getErrorMsg(); + if (prevMsg != null && !prevMsg.equals("")) { + returnMsg += "\n caused by..."+ prevMsg; + } + } + + //Exception 파일로그를 따로 남김 + writeExceptionLog(code, returnMsg, cause); + return returnMsg; + } + + + + + + + public static String make(String errorCode) { + return make(errorCode, new String[] {}); + } + + public static String make(String errorCode, String[] args) { + return make(null, errorCode, args); + } + + public static String make(BatchDoc batchMsgDoc, String errorCode, String[] args) { + if (args == null || args.length == 0) { + return make(batchMsgDoc, errorCode, CodeMessageHandler.getMessage(errorCode)); + } else { + return make(batchMsgDoc, errorCode, CodeMessageHandler.getMessage(errorCode, args)); + } + } + + public static String make(String errorCode, String errorText) { + return make(null, errorCode, errorText); + } + + // 2008.12.30 정동한 + //기존의 make(String errorCode, String errorText) 메소드에 추가 로깅을 위해 BatchDoc 을 추가 + public static String make(BatchDoc batchMsgDoc, String errorCode, String errorText) { + + //=============================================================================== + //코드정보의 SMS전송여부가 설정되어있으면 SMS 파일로그를 남김 + CodeMessageVO codeInfo = null; + + codeInfo = CodeMessageManager.getInstance().getMessageVO(errorCode); + + if (codeInfo == null) { + exLogger.warn("****** 해당 메시지코드["+ errorCode +"] 가 코드테이블에 정의되지 않았습니다. ******"); + + } else { + //해당 코드의 SMS전송여부가 설정되었으면 SMS 로그 남김 -- SMS 로그포맷에 준하여 남겨야함 + //(SMS 시스템이 해당 로그파일을 Polling 하여 SMS가 발송됨) + if (codeInfo.getSmsSendType() != null && codeInfo.getSmsSendType().equals("1")) { + String msg = "[" + codeInfo.getMsgTxt() + "]"; + if ( batchMsgDoc != null ){ + smsLogger.debug( batchMsgDoc.toString() ); + //[수신실패] 파일명:xxxxxxxxxxxxxxxx 기관명:yyyyyyyyyyyyyyy 업무명:zzzzzzzzzzz + if (batchMsgDoc.getBatchMsg().getHeader().getBizCode() != null ) + msg = msg + "파일명:" + batchMsgDoc.getBatchMsg().getHeader().getBizCode() + ","; + if (batchMsgDoc.getBatchMsg().getHeader().getProcessName() != null ) + msg = msg + "업무명:" + batchMsgDoc.getBatchMsg().getHeader().getProcessName() + ","; + if (batchMsgDoc.getBatchMsg().getHeader().getInstitutionName() != null ) + msg = msg + "기관명:" + batchMsgDoc.getBatchMsg().getHeader().getInstitutionName(); + } + // 업무팀이 세팅 되어 있으면 EAI에도 한번 더 보낸다. +// UCMsgSenderUtil.sendUCMsg( msg ); + exLogger.info("****** 해당 메시지코드["+ errorCode +"] 를 SMS 전송 파일로그에 기록하였습니다. ******"); + } + } + //=============================================================================== + + return "["+ errorCode +"] "+ errorText; + } + + + private static boolean isErrorCode(String str) { + if (str == null || str.equals("")) return false; + str = str.trim(); + if (str.length() != 12) return false; + if (StringUtil.isAlpha(str.substring(0, 9)) && + StringUtil.isNumeric(str.substring(9))) return true; + return false; + } + + private static boolean isErrorCodeMsg(String str) { + if (str == null || str.equals("")) return false; + str = str.trim(); + if (str.length() < 14) return false; + if (str.substring(0, 1).equals("[") && + StringUtil.isAlpha(str.substring(1, 10)) && + StringUtil.isNumeric(str.substring(10, 13)) && + str.substring(13, 14).equals("]")) return true; + return false; + } + +} diff --git a/src/com/eactive/eai/common/jdbc/CallableStatementProxy.java b/src/com/eactive/eai/common/jdbc/CallableStatementProxy.java new file mode 100644 index 0000000..26b80cc --- /dev/null +++ b/src/com/eactive/eai/common/jdbc/CallableStatementProxy.java @@ -0,0 +1,1150 @@ +package com.eactive.eai.common.jdbc; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.Date; +import java.sql.NClob; +import java.sql.ParameterMetaData; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Map; + + +public class CallableStatementProxy implements CallableStatement { +// private Connection con; + private CallableStatement stmt; +// private String query; + + public CallableStatementProxy(Connection con, String query, CallableStatement stmt) { +// this.con = con; +// this.query = query; + if (stmt != null) + this.stmt = stmt;// 20250910 uwf 주석제거 + } + + public void registerOutParameter(int parameterIndex, int sqlType) + throws SQLException { + stmt.registerOutParameter(parameterIndex, sqlType); + } + + public void registerOutParameter(int parameterIndex, int sqlType, int scale) + throws SQLException { + stmt.registerOutParameter(parameterIndex, sqlType, scale); + } + + public boolean wasNull() throws SQLException { + return stmt.wasNull(); + } + + public String getString(int parameterIndex) throws SQLException { + return stmt.getString(parameterIndex); + } + + public boolean getBoolean(int parameterIndex) throws SQLException { + return stmt.getBoolean(parameterIndex); + } + + public byte getByte(int parameterIndex) throws SQLException { + return stmt.getByte(parameterIndex); + } + + public short getShort(int parameterIndex) throws SQLException { + return stmt.getShort(parameterIndex); + } + + public int getInt(int parameterIndex) throws SQLException { + return stmt.getInt(parameterIndex); + } + + public long getLong(int parameterIndex) throws SQLException { + return stmt.getLong(parameterIndex); + } + + public float getFloat(int parameterIndex) throws SQLException { + return stmt.getFloat(parameterIndex); + } + + public double getDouble(int parameterIndex) throws SQLException { + return stmt.getDouble(parameterIndex); + } + + @SuppressWarnings("deprecation") + public BigDecimal getBigDecimal(int parameterIndex, int scale) + throws SQLException { + return stmt.getBigDecimal(parameterIndex, scale); + } + + public byte[] getBytes(int parameterIndex) throws SQLException { + return stmt.getBytes(parameterIndex); + } + + public java.sql.Date getDate(int parameterIndex) throws SQLException { + return stmt.getDate(parameterIndex); + } + + public java.sql.Time getTime(int parameterIndex) throws SQLException { + return stmt.getTime(parameterIndex); + } + + public java.sql.Timestamp getTimestamp(int parameterIndex) + throws SQLException { + return stmt.getTimestamp(parameterIndex); + } + + public Object getObject(int parameterIndex) throws SQLException { + return stmt.getObject(parameterIndex); + } + + public BigDecimal getBigDecimal(int parameterIndex) + throws SQLException { + return stmt.getBigDecimal(parameterIndex); + } + +// public Object getObject(int i, Map map) throws SQLException { +// return stmt.getObject(i, map); +// } + + public Ref getRef(int i) throws SQLException { + return stmt.getRef(i); + } + + public Blob getBlob(int i) throws SQLException { + return stmt.getBlob(i); + } + + public Clob getClob(int i) throws SQLException { + return stmt.getClob(i); + } + + public Array getArray(int i) throws SQLException { + return stmt.getArray(i); + } + + public java.sql.Date getDate(int parameterIndex, Calendar cal) + throws SQLException { + return stmt.getDate(parameterIndex, cal); + } + + public java.sql.Time getTime(int parameterIndex, Calendar cal) + throws SQLException { + return stmt.getTime(parameterIndex, cal); + } + + public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) + throws SQLException { + return stmt.getTimestamp(parameterIndex, cal); + } + + public void registerOutParameter(int paramIndex, int sqlType, + String typeName) throws SQLException { + stmt.registerOutParameter(paramIndex, sqlType, typeName); + } + + //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + public ResultSet executeQuery() throws SQLException { + return new ResultSetProxy(this, stmt.executeQuery()); + } + + public int executeUpdate() throws SQLException { + return stmt.executeUpdate(); + } + + public void setNull(int parameterIndex, int sqlType) + throws SQLException { + stmt.setNull(parameterIndex, sqlType); + } + + public void setBoolean(int parameterIndex, boolean x) + throws SQLException { + stmt.setBoolean(parameterIndex, x); + } + + public void setByte(int parameterIndex, byte x) throws SQLException { + stmt.setByte(parameterIndex, x); + } + + public void setShort(int parameterIndex, short x) throws SQLException { + stmt.setShort(parameterIndex, x); + } + + public void setInt(int parameterIndex, int x) throws SQLException { + stmt.setInt(parameterIndex, x); + } + + public void setLong(int parameterIndex, long x) throws SQLException { + stmt.setLong(parameterIndex, x); + } + + public void setFloat(int parameterIndex, float x) throws SQLException { + stmt.setFloat(parameterIndex, x); + } + + public void setDouble(int parameterIndex, double x) + throws SQLException { + stmt.setDouble(parameterIndex, x); + } + + public void setBigDecimal(int parameterIndex, BigDecimal x) + throws SQLException { + stmt.setBigDecimal(parameterIndex, x); + } + + public void setString(int parameterIndex, String x) + throws SQLException { + stmt.setString(parameterIndex, x); + } + + public void setBytes(int parameterIndex, byte[] x) + throws SQLException { + stmt.setBytes(parameterIndex, x); + } + + public void setDate(int parameterIndex, java.sql.Date x) + throws SQLException { + stmt.setDate(parameterIndex, x); + } + + public void setTime(int parameterIndex, java.sql.Time x) + throws SQLException { + stmt.setTime(parameterIndex, x); + } + + public void setTimestamp(int parameterIndex, java.sql.Timestamp x) + throws SQLException { + stmt.setTimestamp(parameterIndex, x); + } + + public void setAsciiStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + stmt.setAsciiStream(parameterIndex, x, length); + } + + @SuppressWarnings("deprecation") + public void setUnicodeStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + stmt.setUnicodeStream(parameterIndex, x, length); + } + + public void setBinaryStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + stmt.setBinaryStream(parameterIndex, x, length); + } + + public void clearParameters() throws SQLException { + stmt.clearParameters(); + } + + public void setObject(int parameterIndex, Object x, int targetSqlType, + int scale) throws SQLException { + stmt.setObject(parameterIndex, x, targetSqlType, scale); + } + + public void setObject(int parameterIndex, Object x, int targetSqlType) + throws SQLException { + stmt.setObject(parameterIndex, x, targetSqlType); + } + + public void setObject(int parameterIndex, Object x) + throws SQLException { + stmt.setObject(parameterIndex, x); + } + + public boolean execute() throws SQLException { + return stmt.execute(); + } + + public void addBatch() throws SQLException { + stmt.addBatch(); + } + + public void setCharacterStream(int parameterIndex, java.io.Reader reader, + int length) throws SQLException { + stmt.setCharacterStream(parameterIndex, reader, length); + } + + public void setRef(int i, Ref x) throws SQLException { + stmt.setRef(i, x); + } + + public void setBlob(int i, Blob x) throws SQLException { + stmt.setBlob(i, x); + } + + public void setClob(int i, Clob x) throws SQLException { + stmt.setClob(i, x); + } + + public void setArray(int i, Array x) throws SQLException { + stmt.setArray(i, x); + } + + public ResultSetMetaData getMetaData() throws SQLException { + return stmt.getMetaData(); + } + + public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) + throws SQLException { + stmt.setDate(parameterIndex, x, cal); + } + + public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) + throws SQLException { + stmt.setTime(parameterIndex, x, cal); + } + + public void setTimestamp(int parameterIndex, java.sql.Timestamp x, + Calendar cal) throws SQLException { + stmt.setTimestamp(parameterIndex, x, cal); + } + + public void setNull(int paramIndex, int sqlType, String typeName) + throws SQLException { + stmt.setNull(paramIndex, sqlType, typeName); + } + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + public ResultSet executeQuery(String sql) throws SQLException { + return new ResultSetProxy(this, stmt.executeQuery(sql)); + } + + public int executeUpdate(String sql) throws SQLException { + return stmt.executeUpdate(sql); + } + + public void close() throws SQLException { + stmt.close(); + } + + public int getMaxFieldSize() throws SQLException { + return stmt.getMaxFieldSize(); + } + + public void setMaxFieldSize(int max) throws SQLException { + stmt.setMaxFieldSize(max); + } + + public int getMaxRows() throws SQLException { + return stmt.getMaxRows(); + } + + public void setMaxRows(int max) throws SQLException { + stmt.setMaxRows(max); + } + + public void setEscapeProcessing(boolean enable) throws SQLException { + stmt.setEscapeProcessing(enable); + } + + public int getQueryTimeout() throws SQLException { + return stmt.getQueryTimeout(); + } + + public void setQueryTimeout(int seconds) throws SQLException { + stmt.setQueryTimeout(seconds); + } + + public void cancel() throws SQLException { + stmt.cancel(); + } + + public SQLWarning getWarnings() throws SQLException { + return stmt.getWarnings(); + } + + public void clearWarnings() throws SQLException { + stmt.clearWarnings(); + } + + public void setCursorName(String name) throws SQLException { + stmt.setCursorName(name); + } + + public boolean execute(String sql) throws SQLException { + return stmt.execute(sql); + } + + public ResultSet getResultSet() throws SQLException { + return new ResultSetProxy(this, stmt.getResultSet()); + } + + public int getUpdateCount() throws SQLException { + return stmt.getUpdateCount(); + } + + public boolean getMoreResults() throws SQLException { + return stmt.getMoreResults(); + } + + public void setFetchDirection(int direction) throws SQLException { + stmt.setFetchDirection(direction); + } + + public int getFetchDirection() throws SQLException { + return stmt.getFetchDirection(); + } + + public void setFetchSize(int rows) throws SQLException { + stmt.setFetchSize(rows); + } + + public int getFetchSize() throws SQLException { + return stmt.getFetchSize(); + } + + public int getResultSetConcurrency() throws SQLException { + return stmt.getResultSetConcurrency(); + } + + public int getResultSetType() throws SQLException { + return stmt.getResultSetType(); + } + + public void addBatch(String sql) throws SQLException { + stmt.addBatch(sql); + } + + public void clearBatch() throws SQLException { + stmt.clearBatch(); + } + + public int[] executeBatch() throws SQLException { + return stmt.executeBatch(); + } + + public Connection getConnection() throws SQLException { + return stmt.getConnection(); + } + + + + // BEGIN_COMMENT_FOR_JAVA_1.3 + // END_COMMENT_FOR_JAVA_1.3 + + public Array getArray(String arg0) throws SQLException + { + return null; + } + + public BigDecimal getBigDecimal(String arg0) throws SQLException + { + return stmt.getBigDecimal(arg0); + } + + public Blob getBlob(String arg0) throws SQLException + { + return stmt.getBlob(arg0); + } + + public boolean getBoolean(String arg0) throws SQLException + { + return stmt.getBoolean(arg0); + } + + public byte getByte(String arg0) throws SQLException + { + return stmt.getByte(arg0); + } + + public byte[] getBytes(String arg0) throws SQLException + { + return stmt.getBytes(arg0); + } + + public Clob getClob(String arg0) throws SQLException + { + return stmt.getClob(arg0); + } + + public Date getDate(String arg0) throws SQLException + { + return stmt.getDate(arg0); + } + + public Date getDate(String arg0, Calendar arg1) throws SQLException + { + return stmt.getDate(arg0,arg1); + } + + public double getDouble(String arg0) throws SQLException + { + return stmt.getDouble(arg0); + } + + public float getFloat(String arg0) throws SQLException + { + return stmt.getFloat(arg0); + } + + public int getInt(String arg0) throws SQLException + { + return stmt.getInt(arg0); + } + + public long getLong(String arg0) throws SQLException + { + return stmt.getLong(arg0); + } + + public Object getObject(String arg0) throws SQLException + { + return stmt.getObject(arg0); + } + +// public Object getObject(String arg0, Map arg1) throws SQLException +// { +// return stmt.getObject(arg0,arg1); +// } + + public Ref getRef(String arg0) throws SQLException + { + return stmt.getRef(arg0); + } + + public short getShort(String arg0) throws SQLException + { + return stmt.getShort(arg0); + } + + public String getString(String arg0) throws SQLException + { + return stmt.getString(arg0); + } + + public Time getTime(String arg0) throws SQLException + { + return stmt.getTime(arg0); + } + + public Time getTime(String arg0, Calendar arg1) throws SQLException + { + return stmt.getTime(arg0,arg1); + } + + public Timestamp getTimestamp(String arg0) throws SQLException + { + return stmt.getTimestamp(arg0); + } + + public Timestamp getTimestamp(String arg0, Calendar arg1) throws SQLException + { + return stmt.getTimestamp(arg0,arg1); + } + + public URL getURL(String arg0) throws SQLException + { + return stmt.getURL(arg0); + } + + public URL getURL(int arg0) throws SQLException + { + return stmt.getURL(arg0); + } + + public void registerOutParameter(String arg0, int arg1) throws SQLException + { + stmt.registerOutParameter(arg0,arg1); + } + + public void registerOutParameter(String arg0, int arg1, String arg2) throws SQLException + { + stmt.registerOutParameter(arg0,arg1,arg2); + } + + public void registerOutParameter(String arg0, int arg1, int arg2) throws SQLException + { + stmt.registerOutParameter(arg0,arg1,arg2); + } + + public void setAsciiStream(String arg0, InputStream arg1, int arg2) throws SQLException + { + stmt.setAsciiStream(arg0,arg1,arg2); + } + + public void setBigDecimal(String arg0, BigDecimal arg1) throws SQLException + { + stmt.setBigDecimal(arg0,arg1); + } + + public void setBinaryStream(String arg0, InputStream arg1, int arg2) throws SQLException + { + stmt.setBinaryStream(arg0,arg1,arg2); + } + + public void setBoolean(String arg0, boolean arg1) throws SQLException + { + stmt.setBoolean(arg0,arg1); + } + + public void setByte(String arg0, byte arg1) throws SQLException + { + stmt.setByte(arg0,arg1); + } + + public void setBytes(String arg0, byte[] arg1) throws SQLException + { + stmt.setBytes(arg0,arg1); + } + + public void setCharacterStream(String arg0, Reader arg1, int arg2) throws SQLException + { + stmt.setCharacterStream(arg0,arg1,arg2); + } + + public void setDate(String arg0, Date arg1) throws SQLException + { + stmt.setDate(arg0,arg1); + } + + public void setDate(String arg0, Date arg1, Calendar arg2) throws SQLException + { + stmt.setDate(arg0,arg1,arg2); + } + + public void setDouble(String arg0, double arg1) throws SQLException + { + stmt.setDouble(arg0,arg1); + } + + public void setFloat(String arg0, float arg1) throws SQLException + { + stmt.setFloat(arg0,arg1); + } + + public void setInt(String arg0, int arg1) throws SQLException + { + stmt.setInt(arg0,arg1); + } + + public void setLong(String arg0, long arg1) throws SQLException + { + stmt.setLong(arg0,arg1); + } + + public void setNull(String arg0, int arg1) throws SQLException + { + stmt.setNull(arg0,arg1); + } + + public void setNull(String arg0, int arg1, String arg2) throws SQLException + { + stmt.setNull(arg0,arg1,arg2); + } + + public void setObject(String arg0, Object arg1) throws SQLException + { + stmt.setObject(arg0,arg1); + } + + public void setObject(String arg0, Object arg1, int arg2) throws SQLException + { + stmt.setObject(arg0,arg1,arg2); + } + + public void setObject(String arg0, Object arg1, int arg2, int arg3) throws SQLException + { + stmt.setObject(arg0,arg1,arg2,arg3); + } + + public void setShort(String arg0, short arg1) throws SQLException + { + stmt.setShort(arg0,arg1); + } + + public void setString(String arg0, String arg1) throws SQLException + { + stmt.setString(arg0,arg1); + } + + public void setTime(String arg0, Time arg1) throws SQLException + { + stmt.setTime(arg0,arg1); + } + + public void setTime(String arg0, Time arg1, Calendar arg2) throws SQLException + { + stmt.setTime(arg0,arg1,arg2); + } + + public void setTimestamp(String arg0, Timestamp arg1) throws SQLException + { + stmt.setTimestamp(arg0,arg1); + } + + public void setTimestamp(String arg0, Timestamp arg1, Calendar arg2) throws SQLException + { + stmt.setTimestamp(arg0,arg1,arg2); + } + + public void setURL(String arg0, URL arg1) throws SQLException + { + stmt.setURL(arg0,arg1); + } + + public ParameterMetaData getParameterMetaData() throws SQLException + { + return stmt.getParameterMetaData(); + } + + public void setURL(int arg0, URL arg1) throws SQLException + { + stmt.setURL(arg0,arg1); + } + + public boolean execute(String arg0, String[] arg1) throws SQLException + { + return stmt.execute(arg0,arg1); + } + + public boolean execute(String arg0, int arg1) throws SQLException + { + return stmt.execute(arg0,arg1); + } + + public boolean execute(String arg0, int[] arg1) throws SQLException + { + return stmt.execute(arg0,arg1); + } + + public int executeUpdate(String arg0, String[] arg1) throws SQLException + { + return stmt.executeUpdate(arg0,arg1); + } + + public int executeUpdate(String arg0, int arg1) throws SQLException + { + return stmt.executeUpdate(arg0,arg1); + } + + public int executeUpdate(String arg0, int[] arg1) throws SQLException + { + return stmt.executeUpdate(arg0,arg1); + } + + public ResultSet getGeneratedKeys() throws SQLException + { + return stmt.getGeneratedKeys(); + } + + public boolean getMoreResults(int arg0) throws SQLException + { + return stmt.getMoreResults(arg0); + } + + public int getResultSetHoldability() throws SQLException + { + return stmt.getResultSetHoldability(); + } + + public void setRowId(int parameterIndex, RowId x) throws SQLException { + + + } + + public void setNString(int parameterIndex, String value) + throws SQLException { + + + } + + public void setNCharacterStream(int parameterIndex, Reader value, + long length) throws SQLException { + + + } + + public void setNClob(int parameterIndex, NClob value) throws SQLException { + + + } + + public void setClob(int parameterIndex, Reader reader, long length) + throws SQLException { + + + } + + public void setBlob(int parameterIndex, InputStream inputStream, long length) + throws SQLException { + + + } + + + public void setNClob(int parameterIndex, Reader reader, long length) + throws SQLException { + + + } + + + public void setSQLXML(int parameterIndex, SQLXML xmlObject) + throws SQLException { + + + } + + + public void setAsciiStream(int parameterIndex, InputStream x, long length) + throws SQLException { + + + } + + + public void setBinaryStream(int parameterIndex, InputStream x, long length) + throws SQLException { + + + } + + + public void setCharacterStream(int parameterIndex, Reader reader, + long length) throws SQLException { + + + } + + + public void setAsciiStream(int parameterIndex, InputStream x) + throws SQLException { + + + } + + + public void setBinaryStream(int parameterIndex, InputStream x) + throws SQLException { + + + } + + + public void setCharacterStream(int parameterIndex, Reader reader) + throws SQLException { + + + } + + + public void setNCharacterStream(int parameterIndex, Reader value) + throws SQLException { + + + } + + + public void setClob(int parameterIndex, Reader reader) throws SQLException { + + + } + + + public void setBlob(int parameterIndex, InputStream inputStream) + throws SQLException { + + + } + + + public void setNClob(int parameterIndex, Reader reader) throws SQLException { + + + } + + + public boolean isClosed() throws SQLException { + + return false; + } + + + public void setPoolable(boolean poolable) throws SQLException { + + + } + + + public boolean isPoolable() throws SQLException { + + return false; + } + + + public T unwrap(Class iface) throws SQLException { + + return null; + } + + + public boolean isWrapperFor(Class iface) throws SQLException { + + return false; + } + +// +// public Object getObject(int parameterIndex, Map> map) +// throws SQLException { +// +// return null; +// } + +// +// public Object getObject(String parameterName, Map> map) +// throws SQLException { +// +// return null; +// } + + + public RowId getRowId(int parameterIndex) throws SQLException { + + return null; + } + + + public RowId getRowId(String parameterName) throws SQLException { + + return null; + } + + + public void setRowId(String parameterName, RowId x) throws SQLException { + + + } + + + public void setNString(String parameterName, String value) + throws SQLException { + + + } + + + public void setNCharacterStream(String parameterName, Reader value, + long length) throws SQLException { + + + } + + + public void setNClob(String parameterName, NClob value) throws SQLException { + + + } + + + public void setClob(String parameterName, Reader reader, long length) + throws SQLException { + + + } + + + public void setBlob(String parameterName, InputStream inputStream, + long length) throws SQLException { + + + } + + + public void setNClob(String parameterName, Reader reader, long length) + throws SQLException { + + + } + + + public NClob getNClob(int parameterIndex) throws SQLException { + + return null; + } + + + public NClob getNClob(String parameterName) throws SQLException { + + return null; + } + + + public void setSQLXML(String parameterName, SQLXML xmlObject) + throws SQLException { + + + } + + + public SQLXML getSQLXML(int parameterIndex) throws SQLException { + + return null; + } + + + public SQLXML getSQLXML(String parameterName) throws SQLException { + + return null; + } + + + public String getNString(int parameterIndex) throws SQLException { + + return null; + } + + + public String getNString(String parameterName) throws SQLException { + + return null; + } + + + public Reader getNCharacterStream(int parameterIndex) throws SQLException { + + return null; + } + + + public Reader getNCharacterStream(String parameterName) throws SQLException { + + return null; + } + + + public Reader getCharacterStream(int parameterIndex) throws SQLException { + + return null; + } + + + public Reader getCharacterStream(String parameterName) throws SQLException { + + return null; + } + + + public void setBlob(String parameterName, Blob x) throws SQLException { + + + } + + + public void setClob(String parameterName, Clob x) throws SQLException { + + + } + + + public void setAsciiStream(String parameterName, InputStream x, long length) + throws SQLException { + + + } + + + public void setBinaryStream(String parameterName, InputStream x, long length) + throws SQLException { + + + } + + + public void setCharacterStream(String parameterName, Reader reader, + long length) throws SQLException { + + + } + + + public void setAsciiStream(String parameterName, InputStream x) + throws SQLException { + + + } + + + public void setBinaryStream(String parameterName, InputStream x) + throws SQLException { + + + } + + + public void setCharacterStream(String parameterName, Reader reader) + throws SQLException { + + + } + + + public void setNCharacterStream(String parameterName, Reader value) + throws SQLException { + + + } + + + public void setClob(String parameterName, Reader reader) + throws SQLException { + + + } + + + public void setBlob(String parameterName, InputStream inputStream) + throws SQLException { + + + } + + + public void setNClob(String parameterName, Reader reader) + throws SQLException { + + + } + + public void closeOnCompletion() throws SQLException { + + } + + public boolean isCloseOnCompletion() throws SQLException { + return false; + } + + @Override + public Object getObject(int parameterIndex, Map> map) + throws SQLException { + return null; + } + + @Override + public Object getObject(String parameterName, Map> map) + throws SQLException { + return null; + } + + public T getObject(int parameterIndex, Class type) + throws SQLException { + return null; + } + + public T getObject(String parameterName, Class type) + throws SQLException { + return null; + } +} diff --git a/src/com/eactive/eai/common/jdbc/ConnectionProxy.java b/src/com/eactive/eai/common/jdbc/ConnectionProxy.java new file mode 100644 index 0000000..f63349e --- /dev/null +++ b/src/com/eactive/eai/common/jdbc/ConnectionProxy.java @@ -0,0 +1,340 @@ +package com.eactive.eai.common.jdbc; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.NClob; +import java.sql.PreparedStatement; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Struct; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Executor; + +import javax.sql.DataSource; + +@SuppressWarnings({"rawtypes","unchecked"}) +public class ConnectionProxy implements Connection { + //static Logger logger = Logger.getLogger("trace.db"); + //StopWatch stopWatch = new StopWatch(); + private Connection con; + + public ConnectionProxy(Connection con) { + // stopWatch.start(); + + this.con = con; + } + + public ConnectionProxy(DataSource ds) throws SQLException { + this.con = ds.getConnection(); + } + + public ConnectionProxy(DataSource ds, String username, String password) + throws SQLException { + this.con = ds.getConnection(username, password); + } + + public Statement createStatement() throws SQLException { + return new StatementProxy(this, con.createStatement()); + } + + public PreparedStatement prepareStatement(String sql) + throws SQLException { + return new PreparedStatementProxy(this, sql, con.prepareStatement(sql)); + } + + public CallableStatement prepareCall(String sql) throws SQLException { + return new CallableStatementProxy(this, sql, con.prepareCall(sql)); + } + + public String nativeSQL(String sql) throws SQLException { + return con.nativeSQL(sql); + } + + public void setAutoCommit(boolean autoCommit) throws SQLException { + con.setAutoCommit(autoCommit); + } + + public boolean getAutoCommit() throws SQLException { + return con.getAutoCommit(); + } + + public void commit() throws SQLException { + con.commit(); + } + + public void rollback() throws SQLException { + con.rollback(); + } + + public void close() throws SQLException { + //con.setAutoCommit(true); + //con.commit(); + con.close(); + System.out.println("[ConnectionProxy] "+ toString()); + +/* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_CONN_TIMEOUT) { + logger.warn("[ConnectionProxy] CONN-TOO-LONG : " + stopWatch); + } + if (DBPool.TRACE_CONN_DUMP) { + logger.warn("[ConnectionProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } +*/ + } + + public boolean isClosed() throws SQLException { + return con.isClosed(); + } + + public DatabaseMetaData getMetaData() throws SQLException { + return con.getMetaData(); + } + + public void setReadOnly(boolean readOnly) throws SQLException { + con.setReadOnly(readOnly); + } + + public boolean isReadOnly() throws SQLException { + return con.isReadOnly(); + } + + public void setCatalog(String catalog) throws SQLException { + con.setCatalog(catalog); + } + + public String getCatalog() throws SQLException { + return con.getCatalog(); + } + + public void setTransactionIsolation(int level) throws SQLException { + con.setTransactionIsolation(level); + } + + public int getTransactionIsolation() throws SQLException { + return con.getTransactionIsolation(); + } + + public SQLWarning getWarnings() throws SQLException { + return con.getWarnings(); + } + + public void clearWarnings() throws SQLException { + con.clearWarnings(); + } + + public Statement createStatement(int resultSetType, int resultSetConcurrency) + throws SQLException { + return new StatementProxy(this, + con.createStatement(resultSetType, resultSetConcurrency)); + } + + public PreparedStatement prepareStatement(String sql, int resultSetType, + int resultSetConcurrency) throws SQLException { + return new PreparedStatementProxy(this, sql, + con.prepareStatement(sql, resultSetType, resultSetConcurrency)); + } + + public CallableStatement prepareCall(String sql, int resultSetType, + int resultSetConcurrency) throws SQLException { + return new CallableStatementProxy(this, sql, + con.prepareCall(sql, resultSetType, resultSetConcurrency)); + } + + public Map getTypeMap() throws SQLException { + return con.getTypeMap(); + } + +// public void setTypeMap(Map map) throws SQLException { +// con.setTypeMap(map); +// } + + + + // BEGIN_COMMENT_FOR_JAVA_1.3 + // END_COMMENT_FOR_JAVA_1.3 + + public Statement createStatement(int arg0, int arg1, int arg2) throws SQLException + { + return con.createStatement(arg0,arg1,arg2); + } + + public int getHoldability() throws SQLException + { + return con.getHoldability(); + } + + public CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3) throws SQLException + { + return con.prepareCall(arg0,arg1,arg2,arg3); + } + + public PreparedStatement prepareStatement(String arg0, String[] arg1) throws SQLException + { + return con.prepareStatement(arg0,arg1); + } + + public PreparedStatement prepareStatement(String arg0, int arg1) throws SQLException + { + return con.prepareStatement(arg0,arg1); + } + + public PreparedStatement prepareStatement(String arg0, int arg1, int arg2, int arg3) throws SQLException + { + return con.prepareStatement(arg0,arg1,arg2,arg3); + } + + public PreparedStatement prepareStatement(String arg0, int[] arg1) throws SQLException + { + return con.prepareStatement(arg0,arg1); + } + + public void releaseSavepoint(Savepoint arg0) throws SQLException + { + con.releaseSavepoint(arg0); + } + + public void rollback(Savepoint arg0) throws SQLException + { + con.rollback(arg0); + } + + public void setHoldability(int arg0) throws SQLException + { + con.setHoldability(arg0); + } + + public Savepoint setSavepoint() throws SQLException + { + return con.setSavepoint(); + } + + public Savepoint setSavepoint(String arg0) throws SQLException + { + return con.setSavepoint(arg0); + } + + + public T unwrap(Class iface) throws SQLException { + + return null; + } + + + public boolean isWrapperFor(Class iface) throws SQLException { + + return false; + } + +// +// public void setTypeMap(Map> map) throws SQLException { +// +// +// } + + + public Clob createClob() throws SQLException { + + return null; + } + + + public Blob createBlob() throws SQLException { + + return null; + } + + + public NClob createNClob() throws SQLException { + + return null; + } + + + public SQLXML createSQLXML() throws SQLException { + + return null; + } + + + public boolean isValid(int timeout) throws SQLException { + + return false; + } + + + public void setClientInfo(String name, String value) + throws SQLClientInfoException { + + + } + + + public void setClientInfo(Properties properties) + throws SQLClientInfoException { + + + } + + + public String getClientInfo(String name) throws SQLException { + + return null; + } + + + public Properties getClientInfo() throws SQLException { + + return null; + } + + + public Array createArrayOf(String typeName, Object[] elements) + throws SQLException { + + return null; + } + + + public Struct createStruct(String typeName, Object[] attributes) + throws SQLException { + + return null; + } + + @Override + public void setTypeMap(Map> map) throws SQLException { + + } + + public void setSchema(String schema) throws SQLException { + + } + + public String getSchema() throws SQLException { + return null; + } + + public void abort(Executor executor) throws SQLException { + + } + + public void setNetworkTimeout(Executor executor, int milliseconds) + throws SQLException { + + } + + public int getNetworkTimeout() throws SQLException { + return 0; + } +} diff --git a/src/com/eactive/eai/common/jdbc/DataSourceProxy.java b/src/com/eactive/eai/common/jdbc/DataSourceProxy.java new file mode 100644 index 0000000..65b75ec --- /dev/null +++ b/src/com/eactive/eai/common/jdbc/DataSourceProxy.java @@ -0,0 +1,82 @@ +package com.eactive.eai.common.jdbc; + +import java.io.Serializable; + +import java.sql.*; + +import java.util.*; +import java.util.logging.Logger; + +import javax.naming.*; + +import javax.sql.*; + + +public class DataSourceProxy implements DataSource, Serializable { + private static final long serialVersionUID = 1L; + final static String WEBLOGIC_INITIAL_CONTEXT_FACTORY = "weblogic.jndi.WLInitialContextFactory"; + private DataSource ds; + + public DataSourceProxy() { + } + + public DataSourceProxy(String t3URL, String jndiName) { + try { + Hashtable env = new Hashtable(); + env.put(Context.INITIAL_CONTEXT_FACTORY, + WEBLOGIC_INITIAL_CONTEXT_FACTORY); + env.put(Context.PROVIDER_URL, t3URL); + + Context ctx = new InitialContext(env); + ds = (DataSource) ctx.lookup(jndiName); + /* + if (!(ds instanceof com.hicall.framework.db.jdbc.DataSourceProxy)) { + ctx.rebind(jndiName, this); + System.out.println( + "com.hicall.framework.db.jdbc.DataSourceProxy is rebined. - " + + jndiName); + } + */ + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Connection getConnection() throws SQLException { + return new ConnectionProxy(ds); + } + + public Connection getConnection(String username, String password) + throws SQLException { + return new ConnectionProxy(ds, username, password); + } + + public java.io.PrintWriter getLogWriter() throws SQLException { + return ds.getLogWriter(); + } + + public void setLogWriter(java.io.PrintWriter out) throws SQLException { + ds.setLogWriter(out); + } + + public void setLoginTimeout(int seconds) throws SQLException { + ds.setLoginTimeout(seconds); + } + + public int getLoginTimeout() throws SQLException { + return ds.getLoginTimeout(); + } + + public T unwrap(Class iface) throws SQLException { + return null; + } + + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null; + } + +} diff --git a/src/com/eactive/eai/common/jdbc/PreparedStatementProxy.java b/src/com/eactive/eai/common/jdbc/PreparedStatementProxy.java new file mode 100644 index 0000000..11e6169 --- /dev/null +++ b/src/com/eactive/eai/common/jdbc/PreparedStatementProxy.java @@ -0,0 +1,808 @@ +package com.eactive.eai.common.jdbc; + +import java.io.InputStream; +import java.io.Reader; +import java.io.Serializable; +import java.math.BigDecimal; +import java.net.URL; + +import java.sql.*; + +import java.util.*; + + +public class PreparedStatementProxy implements PreparedStatement { + //static Logger logger = Logger.getLogger(""); + //static Logger loggerDB = Logger.getLogger("trace.db"); + //StopWatch stopWatch = new StopWatch(); + + private Connection con; + private PreparedStatement ps; + private String sql; + private Hashtable hashtable; + + public PreparedStatementProxy(Connection con, String sql, + PreparedStatement ps) { + this.con = con; + this.sql = sql; + this.ps = ps; + + hashtable = new Hashtable(); + } + + public void setNull(int parameterIndex, int sqlType) + throws SQLException { + ps.setNull(parameterIndex, sqlType); + } + + public void setBoolean(int parameterIndex, boolean x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), new Boolean(x)); + ps.setBoolean(parameterIndex, x); + } + + public void setByte(int parameterIndex, byte x) throws SQLException { + hashtable.put(new Integer(parameterIndex), new Byte(x)); + ps.setByte(parameterIndex, x); + } + + public void setShort(int parameterIndex, short x) throws SQLException { + hashtable.put(new Integer(parameterIndex), new Short(x)); + ps.setShort(parameterIndex, x); + } + + public void setInt(int parameterIndex, int x) throws SQLException { + hashtable.put(new Integer(parameterIndex), new Integer(x)); + ps.setInt(parameterIndex, x); + } + + public void setLong(int parameterIndex, long x) throws SQLException { + hashtable.put(new Integer(parameterIndex), new Long(x)); + ps.setLong(parameterIndex, x); + } + + public void setFloat(int parameterIndex, float x) throws SQLException { + hashtable.put(new Integer(parameterIndex), new Float(x)); + ps.setFloat(parameterIndex, x); + } + + public void setDouble(int parameterIndex, double x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), new Double(x)); + ps.setDouble(parameterIndex, x); + } + + public void setBigDecimal(int parameterIndex, BigDecimal x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), x); + ps.setBigDecimal(parameterIndex, x); + } + + public void setString(int parameterIndex, String x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), "'" + x + "'"); + ps.setString(parameterIndex, x); + } + + public void setBytes(int parameterIndex, byte[] x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), new String(x)); + ps.setBytes(parameterIndex, x); + } + + public void setDate(int parameterIndex, java.sql.Date x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), x); + ps.setDate(parameterIndex, x); + } + + public void setTime(int parameterIndex, java.sql.Time x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), x); + ps.setTime(parameterIndex, x); + } + + public void setTimestamp(int parameterIndex, java.sql.Timestamp x) + throws SQLException { + hashtable.put(new Integer(parameterIndex), x); + ps.setTimestamp(parameterIndex, x); + } + + public void setAsciiStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + ps.setAsciiStream(parameterIndex, x, length); + } + + @SuppressWarnings("deprecation") + public void setUnicodeStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + ps.setUnicodeStream(parameterIndex, x, length); + } + + public void setBinaryStream(int parameterIndex, java.io.InputStream x, + int length) throws SQLException { + ps.setBinaryStream(parameterIndex, x, length); + } + + public void clearParameters() throws SQLException { + ps.clearParameters(); + } + + public void setObject(int parameterIndex, Object x, int targetSqlType, + int scale) throws SQLException { + ps.setObject(parameterIndex, x, targetSqlType, scale); + } + + public void setObject(int parameterIndex, Object x, int targetSqlType) + throws SQLException { + ps.setObject(parameterIndex, x, targetSqlType); + } + + public void setObject(int parameterIndex, Object x) + throws SQLException { + ps.setObject(parameterIndex, x); + } + + public void addBatch() throws SQLException { + ps.addBatch(); + } + + public void setCharacterStream(int parameterIndex, java.io.Reader reader, + int length) throws SQLException { + ps.setCharacterStream(parameterIndex, reader, length); + } + + public void setRef(int i, Ref x) throws SQLException { + ps.setRef(i, x); + } + + public void setBlob(int i, Blob x) throws SQLException { + ps.setBlob(i, x); + } + + public void setClob(int i, Clob x) throws SQLException { + ps.setClob(i, x); + } + + public void setArray(int i, Array x) throws SQLException { + ps.setArray(i, x); + } + + public ResultSetMetaData getMetaData() throws SQLException { + return ps.getMetaData(); + } + + public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) + throws SQLException { + ps.setDate(parameterIndex, x, cal); + } + + public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) + throws SQLException { + ps.setTime(parameterIndex, x, cal); + } + + public void setTimestamp(int parameterIndex, java.sql.Timestamp x, + Calendar cal) throws SQLException { + ps.setTimestamp(parameterIndex, x, cal); + } + + public void setNull(int paramIndex, int sqlType, String typeName) + throws SQLException { + ps.setNull(paramIndex, sqlType, typeName); + } + + //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + /* + try { + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + + this.updateCount = pstmt.executeUpdate(); + + if (stopWatch.getTime() > 1000L && loggerDB.isWarnEnabled() && !loggerDB.isInfoEnabled() && pstmt instanceof sscard.fds.startup.fw.jdbc.PreparedStatementProxy) + loggerDB.warn("[" + this.getClass().getName() + ": Update time too long] " + stopWatch.getTime() + " : \n" + pstmt.toString()); + stopWatch.stop(); + } catch (SQLException e) { + throw e; + } + */ + public ResultSet executeQuery() throws SQLException { + try { + //stopWatch.start(); + + ResultSet result = new ResultSetProxy(this, ps.executeQuery()); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() >= DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate() throws SQLException { + try { + //stopWatch.start(); + + int result = ps.executeUpdate(); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public boolean execute() throws SQLException { + try { + //stopWatch.start(); + + boolean result = ps.execute(); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public ResultSet executeQuery(String sql) throws SQLException { + try { + //stopWatch.start(); + + ResultSet result = new ResultSetProxy(this, ps.executeQuery(sql)); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String sql) throws SQLException { + try { + //stopWatch.start(); + + int result = ps.executeUpdate(sql); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public boolean execute(String sql) throws SQLException { + try { + //stopWatch.start(); + + boolean result = ps.execute(sql); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public void close() throws SQLException { + ps.close(); + } + + public int getMaxFieldSize() throws SQLException { + return ps.getMaxFieldSize(); + } + + public void setMaxFieldSize(int max) throws SQLException { + ps.setMaxFieldSize(max); + } + + public int getMaxRows() throws SQLException { + return ps.getMaxRows(); + } + + public void setMaxRows(int max) throws SQLException { + ps.setMaxRows(max); + } + + public void setEscapeProcessing(boolean enable) throws SQLException { + ps.setEscapeProcessing(enable); + } + + public int getQueryTimeout() throws SQLException { + return ps.getQueryTimeout(); + } + + public void setQueryTimeout(int seconds) throws SQLException { + ps.setQueryTimeout(seconds); + } + + public void cancel() throws SQLException { + ps.cancel(); + } + + public SQLWarning getWarnings() throws SQLException { + return ps.getWarnings(); + } + + public void clearWarnings() throws SQLException { + ps.clearWarnings(); + } + + public void setCursorName(String name) throws SQLException { + ps.setCursorName(name); + } + + public ResultSet getResultSet() throws SQLException { + return new ResultSetProxy(this, ps.getResultSet()); + } + + public int getUpdateCount() throws SQLException { + return ps.getUpdateCount(); + } + + public boolean getMoreResults() throws SQLException { + return ps.getMoreResults(); + } + + public void setFetchDirection(int direction) throws SQLException { + ps.setFetchDirection(direction); + } + + public int getFetchDirection() throws SQLException { + return ps.getFetchDirection(); + } + + public void setFetchSize(int rows) throws SQLException { + ps.setFetchSize(rows); + } + + public int getFetchSize() throws SQLException { + return ps.getFetchSize(); + } + + public int getResultSetConcurrency() throws SQLException { + return ps.getResultSetConcurrency(); + } + + public int getResultSetType() throws SQLException { + return ps.getResultSetType(); + } + + public void addBatch(String sql) throws SQLException { + ps.addBatch(sql); + } + + public void clearBatch() throws SQLException { + ps.clearBatch(); + } + + public int[] executeBatch() throws SQLException { + return ps.executeBatch(); + } + + public Connection getConnection() throws SQLException { + return this.con; + } + + public String toString() { + String str; + int index; + + String sqlTmp = new String(sql); + for (int i = 1; i < (hashtable.size() + 1); i++) { + str = hashtable.get(new Integer(i)).toString(); + index = sqlTmp.indexOf("?"); + sqlTmp = sqlTmp.substring(0, index) + str + + sqlTmp.substring(index + 1, sqlTmp.length()); + } + + return sqlTmp; + } + + + // BEGIN_COMMENT_FOR_JAVA_1.3 + // END_COMMENT_FOR_JAVA_1.3 + + public ParameterMetaData getParameterMetaData() throws SQLException + { + return ps.getParameterMetaData(); + } + + public void setURL(int arg0, URL arg1) throws SQLException + { + ps.setURL(arg0,arg1); + } + + public boolean execute(String arg0, String[] arg1) throws SQLException + { + try { + //stopWatch.start(); + + boolean result = ps.execute(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public boolean execute(String arg0, int arg1) throws SQLException + { + try { + //stopWatch.start(); + + boolean result = ps.execute(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public boolean execute(String arg0, int[] arg1) throws SQLException + { + try { + //stopWatch.start(); + + boolean result = ps.execute(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String arg0, String[] arg1) throws SQLException + { + try { + //stopWatch.start(); + + int result = ps.executeUpdate(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String arg0, int arg1) throws SQLException + { + try { + //stopWatch.start(); + + int result = ps.executeUpdate(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String arg0, int[] arg1) throws SQLException + { + try { + //stopWatch.start(); + + int result = ps.executeUpdate(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[PstmtProxy] SQL-FAIL : " + e.toString() + "\n" + toString()); + throw e; + } finally { + System.out.println("[PstmtProxy] "+ toString()); + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[PstmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + toString()); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[PstmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public ResultSet getGeneratedKeys() throws SQLException + { + return ps.getGeneratedKeys(); + + } + + public boolean getMoreResults(int arg0) throws SQLException + { + return ps.getMoreResults(arg0); + } + + public int getResultSetHoldability() throws SQLException + { + return ps.getResultSetHoldability(); + } + + + public boolean isClosed() throws SQLException { + + return false; + } + + + public void setPoolable(boolean poolable) throws SQLException { + + + } + + + public boolean isPoolable() throws SQLException { + + return false; + } + + + public T unwrap(Class iface) throws SQLException { + + return null; + } + + + public boolean isWrapperFor(Class iface) throws SQLException { + + return false; + } + + + public void setRowId(int parameterIndex, RowId x) throws SQLException { + + + } + + + public void setNString(int parameterIndex, String value) + throws SQLException { + + + } + + + public void setNCharacterStream(int parameterIndex, Reader value, + long length) throws SQLException { + + + } + + + public void setNClob(int parameterIndex, NClob value) throws SQLException { + + + } + + + public void setClob(int parameterIndex, Reader reader, long length) + throws SQLException { + + + } + + + public void setBlob(int parameterIndex, InputStream inputStream, long length) + throws SQLException { + + + } + + + public void setNClob(int parameterIndex, Reader reader, long length) + throws SQLException { + + + } + + + public void setSQLXML(int parameterIndex, SQLXML xmlObject) + throws SQLException { + + + } + + + public void setAsciiStream(int parameterIndex, InputStream x, long length) + throws SQLException { + + + } + + + public void setBinaryStream(int parameterIndex, InputStream x, long length) + throws SQLException { + + + } + + + public void setCharacterStream(int parameterIndex, Reader reader, + long length) throws SQLException { + + + } + + + public void setAsciiStream(int parameterIndex, InputStream x) + throws SQLException { + + + } + + + public void setBinaryStream(int parameterIndex, InputStream x) + throws SQLException { + + + } + + + public void setCharacterStream(int parameterIndex, Reader reader) + throws SQLException { + + + } + + + public void setNCharacterStream(int parameterIndex, Reader value) + throws SQLException { + + + } + + + public void setClob(int parameterIndex, Reader reader) throws SQLException { + + + } + + + public void setBlob(int parameterIndex, InputStream inputStream) + throws SQLException { + + + } + + + public void setNClob(int parameterIndex, Reader reader) throws SQLException { + + + } + + public void closeOnCompletion() throws SQLException { + + } + + public boolean isCloseOnCompletion() throws SQLException { + return false; + } +} diff --git a/src/com/eactive/eai/common/jdbc/ResultSetProxy.java b/src/com/eactive/eai/common/jdbc/ResultSetProxy.java new file mode 100644 index 0000000..f44e899 --- /dev/null +++ b/src/com/eactive/eai/common/jdbc/ResultSetProxy.java @@ -0,0 +1,1000 @@ +package com.eactive.eai.common.jdbc; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; + +import java.sql.*; + +import java.util.*; + +@SuppressWarnings("deprecation") +public class ResultSetProxy implements ResultSet { + //private Statement stmt; + private ResultSet rs; + + public ResultSetProxy(Statement stmt, ResultSet rs) { + this.rs = rs; + //this.stmt = stmt; + } + + public boolean next() throws SQLException { + return rs.next(); + } + + public void close() throws SQLException { + rs.close(); + } + + public boolean wasNull() throws SQLException { + return rs.wasNull(); + } + + public String getString(int columnIndex) throws SQLException { + return rs.getString(columnIndex); + } + + public boolean getBoolean(int columnIndex) throws SQLException { + return rs.getBoolean(columnIndex); + } + + public byte getByte(int columnIndex) throws SQLException { + return rs.getByte(columnIndex); + } + + public short getShort(int columnIndex) throws SQLException { + return rs.getShort(columnIndex); + } + + public int getInt(int columnIndex) throws SQLException { + return rs.getInt(columnIndex); + } + + public long getLong(int columnIndex) throws SQLException { + return rs.getInt(columnIndex); + } + + public float getFloat(int columnIndex) throws SQLException { + return rs.getFloat(columnIndex); + } + + public double getDouble(int columnIndex) throws SQLException { + return rs.getDouble(columnIndex); + } + + public BigDecimal getBigDecimal(int columnIndex, int scale) + throws SQLException { + return rs.getBigDecimal(columnIndex, scale); + } + + public byte[] getBytes(int columnIndex) throws SQLException { + return rs.getBytes(columnIndex); + } + + public java.sql.Date getDate(int columnIndex) throws SQLException { + return rs.getDate(columnIndex); + } + + public java.sql.Time getTime(int columnIndex) throws SQLException { + return rs.getTime(columnIndex); + } + + public java.sql.Timestamp getTimestamp(int columnIndex) + throws SQLException { + return rs.getTimestamp(columnIndex); + } + + public java.io.InputStream getAsciiStream(int columnIndex) + throws SQLException { + return rs.getAsciiStream(columnIndex); + } + + public java.io.InputStream getUnicodeStream(int columnIndex) + throws SQLException { + return rs.getUnicodeStream(columnIndex); + } + + public java.io.InputStream getBinaryStream(int columnIndex) + throws SQLException { + return rs.getBinaryStream(columnIndex); + } + + public String getString(String columnName) throws SQLException { + return rs.getString(columnName); + } + + public boolean getBoolean(String columnName) throws SQLException { + return rs.getBoolean(columnName); + } + + public byte getByte(String columnName) throws SQLException { + return rs.getByte(columnName); + } + + public short getShort(String columnName) throws SQLException { + return rs.getShort(columnName); + } + + public int getInt(String columnName) throws SQLException { + return rs.getInt(columnName); + } + + public long getLong(String columnName) throws SQLException { + return rs.getLong(columnName); + } + + public float getFloat(String columnName) throws SQLException { + return rs.getFloat(columnName); + } + + public double getDouble(String columnName) throws SQLException { + return rs.getDouble(columnName); + } + + public BigDecimal getBigDecimal(String columnName, int scale) + throws SQLException { + return rs.getBigDecimal(columnName); + } + + public byte[] getBytes(String columnName) throws SQLException { + return rs.getBytes(columnName); + } + + public java.sql.Date getDate(String columnName) throws SQLException { + return rs.getDate(columnName); + } + + public java.sql.Time getTime(String columnName) throws SQLException { + return rs.getTime(columnName); + } + + public java.sql.Timestamp getTimestamp(String columnName) + throws SQLException { + return rs.getTimestamp(columnName); + } + + public java.io.InputStream getAsciiStream(String columnName) + throws SQLException { + return rs.getAsciiStream(columnName); + } + + public java.io.InputStream getUnicodeStream(String columnName) + throws SQLException { + return rs.getUnicodeStream(columnName); + } + + public java.io.InputStream getBinaryStream(String columnName) + throws SQLException { + return rs.getBinaryStream(columnName); + } + + public SQLWarning getWarnings() throws SQLException { + return rs.getWarnings(); + } + + public void clearWarnings() throws SQLException { + rs.clearWarnings(); + } + + public String getCursorName() throws SQLException { + return rs.getCursorName(); + } + + public ResultSetMetaData getMetaData() throws SQLException { + return rs.getMetaData(); + } + + public Object getObject(int columnIndex) throws SQLException { + return rs.getObject(columnIndex); + } + + public Object getObject(String columnName) throws SQLException { + return rs.getObject(columnName); + } + + public int findColumn(String columnName) throws SQLException { + return rs.findColumn(columnName); + } + + public java.io.Reader getCharacterStream(int columnIndex) + throws SQLException { + return rs.getCharacterStream(columnIndex); + } + + public java.io.Reader getCharacterStream(String columnName) + throws SQLException { + return rs.getCharacterStream(columnName); + } + + public BigDecimal getBigDecimal(int columnIndex) throws SQLException { + return rs.getBigDecimal(columnIndex); + } + + public BigDecimal getBigDecimal(String columnName) + throws SQLException { + return rs.getBigDecimal(columnName); + } + + public boolean isBeforeFirst() throws SQLException { + return rs.isBeforeFirst(); + } + + public boolean isAfterLast() throws SQLException { + return rs.isAfterLast(); + } + + public boolean isFirst() throws SQLException { + return rs.isFirst(); + } + + public boolean isLast() throws SQLException { + return rs.isLast(); + } + + public void beforeFirst() throws SQLException { + rs.beforeFirst(); + } + + public void afterLast() throws SQLException { + rs.afterLast(); + } + + public boolean first() throws SQLException { + return rs.first(); + } + + public boolean last() throws SQLException { + return rs.last(); + } + + public int getRow() throws SQLException { + return rs.getRow(); + } + + public boolean absolute(int row) throws SQLException { + return rs.absolute(row); + } + + public boolean relative(int rows) throws SQLException { + return rs.relative(rows); + } + + public boolean previous() throws SQLException { + return rs.previous(); + } + + public void setFetchDirection(int direction) throws SQLException { + rs.setFetchDirection(direction); + } + + public int getFetchDirection() throws SQLException { + return rs.getFetchDirection(); + } + + public void setFetchSize(int rows) throws SQLException { + rs.setFetchSize(rows); + } + + public int getFetchSize() throws SQLException { + return rs.getFetchSize(); + } + + public int getType() throws SQLException { + return rs.getType(); + } + + public int getConcurrency() throws SQLException { + return rs.getConcurrency(); + } + + public boolean rowUpdated() throws SQLException { + return rs.rowUpdated(); + } + + public boolean rowInserted() throws SQLException { + return rs.rowInserted(); + } + + public boolean rowDeleted() throws SQLException { + return rs.rowDeleted(); + } + + public void updateNull(int columnIndex) throws SQLException { + rs.updateNull(columnIndex); + } + + public void updateBoolean(int columnIndex, boolean x) + throws SQLException { + rs.updateBoolean(columnIndex, x); + } + + public void updateByte(int columnIndex, byte x) throws SQLException { + rs.updateByte(columnIndex, x); + } + + public void updateShort(int columnIndex, short x) throws SQLException { + rs.updateShort(columnIndex, x); + } + + public void updateInt(int columnIndex, int x) throws SQLException { + rs.updateInt(columnIndex, x); + } + + public void updateLong(int columnIndex, long x) throws SQLException { + rs.updateLong(columnIndex, x); + } + + public void updateFloat(int columnIndex, float x) throws SQLException { + rs.updateFloat(columnIndex, x); + } + + public void updateDouble(int columnIndex, double x) + throws SQLException { + rs.updateDouble(columnIndex, x); + } + + public void updateBigDecimal(int columnIndex, BigDecimal x) + throws SQLException { + rs.updateBigDecimal(columnIndex, x); + } + + public void updateString(int columnIndex, String x) + throws SQLException { + rs.updateString(columnIndex, x); + } + + public void updateBytes(int columnIndex, byte[] x) + throws SQLException { + rs.updateBytes(columnIndex, x); + } + + public void updateDate(int columnIndex, java.sql.Date x) + throws SQLException { + rs.updateDate(columnIndex, x); + } + + public void updateTime(int columnIndex, java.sql.Time x) + throws SQLException { + rs.updateTime(columnIndex, x); + } + + public void updateTimestamp(int columnIndex, java.sql.Timestamp x) + throws SQLException { + rs.updateTimestamp(columnIndex, x); + } + + public void updateAsciiStream(int columnIndex, java.io.InputStream x, + int length) throws SQLException { + rs.updateAsciiStream(columnIndex, x, length); + } + + public void updateBinaryStream(int columnIndex, java.io.InputStream x, + int length) throws SQLException { + rs.updateBinaryStream(columnIndex, x, length); + } + + public void updateCharacterStream(int columnIndex, java.io.Reader x, + int length) throws SQLException { + rs.updateCharacterStream(columnIndex, x, length); + } + + public void updateObject(int columnIndex, Object x, int scale) + throws SQLException { + rs.updateObject(columnIndex, x, scale); + } + + public void updateObject(int columnIndex, Object x) + throws SQLException { + rs.updateObject(columnIndex, x); + } + + public void updateNull(String columnName) throws SQLException { + rs.updateNull(columnName); + } + + public void updateBoolean(String columnName, boolean x) + throws SQLException { + rs.updateBoolean(columnName, x); + } + + public void updateByte(String columnName, byte x) throws SQLException { + rs.updateByte(columnName, x); + } + + public void updateShort(String columnName, short x) + throws SQLException { + rs.updateShort(columnName, x); + } + + public void updateInt(String columnName, int x) throws SQLException { + rs.updateInt(columnName, x); + } + + public void updateLong(String columnName, long x) throws SQLException { + rs.updateLong(columnName, x); + } + + public void updateFloat(String columnName, float x) + throws SQLException { + rs.updateFloat(columnName, x); + } + + public void updateDouble(String columnName, double x) + throws SQLException { + rs.updateDouble(columnName, x); + } + + public void updateBigDecimal(String columnName, BigDecimal x) + throws SQLException { + rs.updateBigDecimal(columnName, x); + } + + public void updateString(String columnName, String x) + throws SQLException { + rs.updateString(columnName, x); + } + + public void updateBytes(String columnName, byte[] x) + throws SQLException { + rs.updateBytes(columnName, x); + } + + public void updateDate(String columnName, java.sql.Date x) + throws SQLException { + rs.updateDate(columnName, x); + } + + public void updateTime(String columnName, java.sql.Time x) + throws SQLException { + rs.updateTime(columnName, x); + } + + public void updateTimestamp(String columnName, java.sql.Timestamp x) + throws SQLException { + rs.updateTimestamp(columnName, x); + } + + public void updateAsciiStream(String columnName, java.io.InputStream x, + int length) throws SQLException { + rs.updateAsciiStream(columnName, x, length); + } + + public void updateBinaryStream(String columnName, java.io.InputStream x, + int length) throws SQLException { + rs.updateBinaryStream(columnName, x, length); + } + + public void updateCharacterStream(String columnName, java.io.Reader reader, + int length) throws SQLException { + rs.updateCharacterStream(columnName, reader, length); + } + + public void updateObject(String columnName, Object x, int scale) + throws SQLException { + rs.updateObject(columnName, x, scale); + } + + public void updateObject(String columnName, Object x) + throws SQLException { + rs.updateObject(columnName, x); + } + + public void insertRow() throws SQLException { + rs.insertRow(); + } + + public void updateRow() throws SQLException { + rs.updateRow(); + } + + public void deleteRow() throws SQLException { + rs.deleteRow(); + } + + public void refreshRow() throws SQLException { + rs.refreshRow(); + } + + public void cancelRowUpdates() throws SQLException { + rs.cancelRowUpdates(); + } + + public void moveToInsertRow() throws SQLException { + rs.moveToInsertRow(); + } + + public void moveToCurrentRow() throws SQLException { + rs.moveToCurrentRow(); + } + + public Statement getStatement() throws SQLException { + return rs.getStatement(); + } + +// public Object getObject(int i, Map map) throws SQLException { +// return rs.getObject(i, map); +// } + + public Ref getRef(int i) throws SQLException { + return rs.getRef(i); + } + + public Blob getBlob(int i) throws SQLException { + return rs.getBlob(i); + } + + public Clob getClob(int i) throws SQLException { + return rs.getClob(i); + } + + public Array getArray(int i) throws SQLException { + return rs.getArray(i); + } + +// public Object getObject(String colName, java.util.Map map) +// throws SQLException { +// return rs.getObject(colName, map); +// } + + public Ref getRef(String colName) throws SQLException { + return rs.getRef(colName); + } + + public Blob getBlob(String colName) throws SQLException { + return rs.getBlob(colName); + } + + public Clob getClob(String colName) throws SQLException { + return rs.getClob(colName); + } + + public Array getArray(String colName) throws SQLException { + return rs.getArray(colName); + } + + public java.sql.Date getDate(int columnIndex, Calendar cal) + throws SQLException { + return rs.getDate(columnIndex, cal); + } + + public java.sql.Date getDate(String columnName, Calendar cal) + throws SQLException { + return rs.getDate(columnName, cal); + } + + public java.sql.Time getTime(int columnIndex, Calendar cal) + throws SQLException { + return rs.getTime(columnIndex, cal); + } + + public java.sql.Time getTime(String columnName, Calendar cal) + throws SQLException { + return rs.getTime(columnName, cal); + } + + public java.sql.Timestamp getTimestamp(int columnIndex, Calendar cal) + throws SQLException { + return rs.getTimestamp(columnIndex, cal); + } + + public java.sql.Timestamp getTimestamp(String columnName, Calendar cal) + throws SQLException { + return rs.getTimestamp(columnName, cal); + } + + public java.net.URL getURL(String arg0) + throws SQLException { + return rs.getURL(arg0); + } + public java.net.URL getURL(int arg0) + throws SQLException { + return rs.getURL(arg0); + } + public void updateArray(int arg0 ,java.sql.Array arg1) + throws SQLException { + rs.updateArray(arg0,arg1); + } + public void updateBlob(int arg0 ,java.sql.Blob arg1) + throws SQLException { + rs.updateBlob(arg0,arg1); + } + public void updateClob(int arg0 ,java.sql.Clob arg1) + throws SQLException { + rs.updateClob(arg0,arg1); + } + + // BEGIN_COMMENT_FOR_JAVA_1.3 + // END_COMMENT_FOR_JAVA_1.3 + + public void updateArray(String arg0, Array arg1) throws SQLException + { + rs.updateArray(arg0,arg1); + } + + public void updateBlob(String arg0, Blob arg1) throws SQLException + { + rs.updateBlob(arg0,arg1); + } + + public void updateClob(String arg0, Clob arg1) throws SQLException + { + rs.updateClob(arg0,arg1); + } + + public void updateRef(String arg0, Ref arg1) throws SQLException + { + rs.updateRef(arg0,arg1); + + } + + public void updateRef(int arg0, Ref arg1) throws SQLException + { + rs.updateRef(arg0,arg1); + } + + + public T unwrap(Class iface) throws SQLException { + + return null; + } + + + public boolean isWrapperFor(Class iface) throws SQLException { + + return false; + } + +// +// public Object getObject(int columnIndex, Map> map) +// throws SQLException { +// +// return null; +// } +// +// +// public Object getObject(String columnLabel, Map> map) +// throws SQLException { +// +// return null; +// } + + + public RowId getRowId(int columnIndex) throws SQLException { + + return null; + } + + + public RowId getRowId(String columnLabel) throws SQLException { + + return null; + } + + + public void updateRowId(int columnIndex, RowId x) throws SQLException { + + + } + + + public void updateRowId(String columnLabel, RowId x) throws SQLException { + + + } + + + public int getHoldability() throws SQLException { + + return 0; + } + + + public boolean isClosed() throws SQLException { + + return false; + } + + + public void updateNString(int columnIndex, String nString) + throws SQLException { + + + } + + + public void updateNString(String columnLabel, String nString) + throws SQLException { + + + } + + + public void updateNClob(int columnIndex, NClob nClob) throws SQLException { + + + } + + + public void updateNClob(String columnLabel, NClob nClob) + throws SQLException { + + + } + + + public NClob getNClob(int columnIndex) throws SQLException { + + return null; + } + + + public NClob getNClob(String columnLabel) throws SQLException { + + return null; + } + + + public SQLXML getSQLXML(int columnIndex) throws SQLException { + + return null; + } + + + public SQLXML getSQLXML(String columnLabel) throws SQLException { + + return null; + } + + + public void updateSQLXML(int columnIndex, SQLXML xmlObject) + throws SQLException { + + + } + + + public void updateSQLXML(String columnLabel, SQLXML xmlObject) + throws SQLException { + + + } + + + public String getNString(int columnIndex) throws SQLException { + + return null; + } + + + public String getNString(String columnLabel) throws SQLException { + + return null; + } + + + public Reader getNCharacterStream(int columnIndex) throws SQLException { + + return null; + } + + + public Reader getNCharacterStream(String columnLabel) throws SQLException { + + return null; + } + + + public void updateNCharacterStream(int columnIndex, Reader x, long length) + throws SQLException { + + + } + + + public void updateNCharacterStream(String columnLabel, Reader reader, + long length) throws SQLException { + + + } + + + public void updateAsciiStream(int columnIndex, InputStream x, long length) + throws SQLException { + + + } + + + public void updateBinaryStream(int columnIndex, InputStream x, long length) + throws SQLException { + + + } + + + public void updateCharacterStream(int columnIndex, Reader x, long length) + throws SQLException { + + + } + + + public void updateAsciiStream(String columnLabel, InputStream x, long length) + throws SQLException { + + + } + + + public void updateBinaryStream(String columnLabel, InputStream x, + long length) throws SQLException { + + + } + + + public void updateCharacterStream(String columnLabel, Reader reader, + long length) throws SQLException { + + + } + + + public void updateBlob(int columnIndex, InputStream inputStream, long length) + throws SQLException { + + + } + + + public void updateBlob(String columnLabel, InputStream inputStream, + long length) throws SQLException { + + + } + + + public void updateClob(int columnIndex, Reader reader, long length) + throws SQLException { + + + } + + + public void updateClob(String columnLabel, Reader reader, long length) + throws SQLException { + + + } + + + public void updateNClob(int columnIndex, Reader reader, long length) + throws SQLException { + + + } + + + public void updateNClob(String columnLabel, Reader reader, long length) + throws SQLException { + + + } + + + public void updateNCharacterStream(int columnIndex, Reader x) + throws SQLException { + + + } + + + public void updateNCharacterStream(String columnLabel, Reader reader) + throws SQLException { + + + } + + + public void updateAsciiStream(int columnIndex, InputStream x) + throws SQLException { + + + } + + + public void updateBinaryStream(int columnIndex, InputStream x) + throws SQLException { + + + } + + + public void updateCharacterStream(int columnIndex, Reader x) + throws SQLException { + + + } + + + public void updateAsciiStream(String columnLabel, InputStream x) + throws SQLException { + + + } + + + public void updateBinaryStream(String columnLabel, InputStream x) + throws SQLException { + + + } + + + public void updateCharacterStream(String columnLabel, Reader reader) + throws SQLException { + + + } + + + public void updateBlob(int columnIndex, InputStream inputStream) + throws SQLException { + + + } + + + public void updateBlob(String columnLabel, InputStream inputStream) + throws SQLException { + + + } + + + public void updateClob(int columnIndex, Reader reader) throws SQLException { + + + } + + + public void updateClob(String columnLabel, Reader reader) + throws SQLException { + + + } + + + public void updateNClob(int columnIndex, Reader reader) throws SQLException { + + + } + + + public void updateNClob(String columnLabel, Reader reader) + throws SQLException { + + + } + + @Override + public Object getObject(int columnIndex, Map> map) + throws SQLException { + return null; + } + + @Override + public Object getObject(String columnLabel, Map> map) + throws SQLException { + return null; + } + + public T getObject(int columnIndex, Class type) throws SQLException { + return null; + } + + public T getObject(String columnLabel, Class type) + throws SQLException { + return null; + } +} diff --git a/src/com/eactive/eai/common/jdbc/StatementProxy.java b/src/com/eactive/eai/common/jdbc/StatementProxy.java new file mode 100644 index 0000000..20c512e --- /dev/null +++ b/src/com/eactive/eai/common/jdbc/StatementProxy.java @@ -0,0 +1,399 @@ +package com.eactive.eai.common.jdbc; + + +import java.sql.Connection; +import java.sql.Statement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; + +public class StatementProxy implements Statement { + //static Logger logger = Logger.getLogger(""); + //static Logger loggerDB = Logger.getLogger("trace.db"); + //StopWatch stopWatch = new StopWatch(); + + private String sql; + private Connection con; + private Statement stmt; + + public StatementProxy(Connection con, Statement stmt) { + this.con = con; + this.stmt = stmt; + } + + public ResultSet executeQuery(String sql) throws SQLException { + try { + this.sql = sql; + + //stopWatch.start(); + + ResultSet rs = stmt.executeQuery(sql); + + return new ResultSetProxy(this, rs); + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() >= DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String sql) throws SQLException { + try { + this.sql = sql; + //stopWatch.start(); + + int result = stmt.executeUpdate(sql); + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public void close() throws SQLException { + stmt.close(); + } + + public int getMaxFieldSize() throws SQLException { + return stmt.getMaxFieldSize(); + } + + public void setMaxFieldSize(int max) throws SQLException { + stmt.setMaxFieldSize(max); + } + + public int getMaxRows() throws SQLException { + return stmt.getMaxRows(); + } + + public void setMaxRows(int max) throws SQLException { + stmt.setMaxRows(max); + } + + public void setEscapeProcessing(boolean enable) throws SQLException { + stmt.setEscapeProcessing(enable); + } + + public int getQueryTimeout() throws SQLException { + return stmt.getQueryTimeout(); + } + + public void setQueryTimeout(int seconds) throws SQLException { + stmt.setQueryTimeout(seconds); + } + + public void cancel() throws SQLException { + stmt.cancel(); + } + + public SQLWarning getWarnings() throws SQLException { + return stmt.getWarnings(); + } + + public void clearWarnings() throws SQLException { + stmt.clearWarnings(); + } + + public void setCursorName(String name) throws SQLException { + stmt.setCursorName(name); + } + + public boolean execute(String sql) throws SQLException { + try { + this.sql = sql; + //stopWatch.start(); + + boolean result = stmt.execute(sql); + + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public ResultSet getResultSet() throws SQLException { + return new ResultSetProxy(this, stmt.getResultSet()); + } + + public int getUpdateCount() throws SQLException { + return stmt.getUpdateCount(); + } + + public boolean getMoreResults() throws SQLException { + return stmt.getMoreResults(); + } + + public void setFetchDirection(int direction) throws SQLException { + stmt.setFetchDirection(direction); + } + + public int getFetchDirection() throws SQLException { + return stmt.getFetchDirection(); + } + + public void setFetchSize(int rows) throws SQLException { + stmt.setFetchSize(rows); + } + + public int getFetchSize() throws SQLException { + return stmt.getFetchSize(); + } + + public int getResultSetConcurrency() throws SQLException { + return stmt.getResultSetConcurrency(); + } + + public int getResultSetType() throws SQLException { + return stmt.getResultSetType(); + } + + public void addBatch(String sql) throws SQLException { + stmt.addBatch(sql); + } + + public void clearBatch() throws SQLException { + stmt.clearBatch(); + } + + public int[] executeBatch() throws SQLException { + return stmt.executeBatch(); + } + + public Connection getConnection() throws SQLException { + return this.con; + } + + public String toString() { + return sql; + } + + + // BEGIN_COMMENT_FOR_JAVA_1.3 + // END_COMMENT_FOR_JAVA_1.3 + + public boolean execute(String arg0, String[] arg1) throws SQLException + { + try { + this.sql = arg0; + //stopWatch.start(); + + boolean result = stmt.execute(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public boolean execute(String arg0, int arg1) throws SQLException + { + try { + this.sql = arg0; + //stopWatch.start(); + + boolean result = stmt.execute(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public boolean execute(String arg0, int[] arg1) throws SQLException + { + try { + this.sql = arg0; + //stopWatch.start(); + + boolean result = stmt.execute(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String arg0, String[] arg1) throws SQLException + { + try { + this.sql = arg0; + //stopWatch.start(); + + int result = stmt.executeUpdate(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String arg0, int arg1) throws SQLException + { + try { + this.sql = arg0; + //stopWatch.start(); + + int result = stmt.executeUpdate(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public int executeUpdate(String arg0, int[] arg1) throws SQLException + { + try { + this.sql = arg0; + //stopWatch.start(); + + int result = stmt.executeUpdate(arg0,arg1); + return result; + } catch(SQLException e) { + //logger.error("[StmtProxy] SQL-FAIL : " + e.toString() + "\n" + sql); + throw e; + } finally { + /* + stopWatch.stop(); + if (stopWatch.getTime() > DBPool.TRACE_SQL_TIMEOUT) { + loggerDB.warn("[StmtProxy] SQL-TOO-LONG : " + stopWatch + "\n" + sql); + } + if (DBPool.TRACE_SQL_DUMP) { + loggerDB.warn("[StmtProxy] Thread Dump (NOT ERROR!) -----"); + Thread.dumpStack(); + } + */ + } + } + + public ResultSet getGeneratedKeys() throws SQLException + { + return stmt.getGeneratedKeys(); + } + + public boolean getMoreResults(int arg0) throws SQLException + { + return stmt.getMoreResults(arg0); + } + + public int getResultSetHoldability() throws SQLException + { + return stmt.getResultSetHoldability(); + } + + public T unwrap(Class iface) throws SQLException { + return null; + } + + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public boolean isClosed() throws SQLException { + return false; + } + + public void setPoolable(boolean poolable) throws SQLException { + + } + + public boolean isPoolable() throws SQLException { + return false; + } + + public void closeOnCompletion() throws SQLException { + + } + + public boolean isCloseOnCompletion() throws SQLException { + return false; + } +} diff --git a/src/com/eactive/eai/common/lifecycle/DefaultLifecycleListener.java b/src/com/eactive/eai/common/lifecycle/DefaultLifecycleListener.java new file mode 100644 index 0000000..b344e9b --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/DefaultLifecycleListener.java @@ -0,0 +1,53 @@ +package com.eactive.eai.common.lifecycle; + +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : LifecyclEvent를 수신 처리하는 기본 리스너 클래스 +* 2. 처리 개요 : LifecycleEvent를 받아 로깅한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class DefaultLifecycleListener implements LifecycleListener +{ + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * 1. 기능 : LifecycleEvent를 수신하여 로깅하는 메서드 + * 2. 처리 개요 : LifecycleEvent를 받아 약속된 포맷으로 Logger를 통해 로깅한다. + * - + * 3. 주의사항 + * + * @param event Lifecycle의 start, stop Event 정보를 표현한 Value Object + **/ + public void lifecycleEvent(LifecycleEvent event) + { + Object data = event.getData(); + if(data==null) { + logger.warn(ExceptionUtil.make("BWCEAIMCL001")); + return; + } + + String type = event.getType(); + String name = data.getClass().getName(); + int idx = name.lastIndexOf("."); + StringBuffer sb = new StringBuffer(); + sb.append("["); + sb.append((idx==-1)? name : name.substring(idx+1)).append("] "); + sb.append("It is ").append(type).append("."); + if(data instanceof AdapterGroupVO) { + sb.append(" >> ").append(((AdapterGroupVO)data).getName()); + } else if(data instanceof AdapterVO) { + sb.append(" >> ").append(((AdapterVO)data).getName()); + } + logger.info(sb.toString()); + } +} diff --git a/src/com/eactive/eai/common/lifecycle/Lifecycle.java b/src/com/eactive/eai/common/lifecycle/Lifecycle.java new file mode 100644 index 0000000..0ea9459 --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/Lifecycle.java @@ -0,0 +1,108 @@ + + + +package com.eactive.eai.common.lifecycle; + + + +/** +* 1. 기능 : 어플리케이션 기동/종료에 따른 비즈니스 로직 처리를 위해 정의한 인터페이스 +* 2. 처리 개요 : 어플리케이션 기동/종료 및 이벤트 처리를 위한 메서드를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public interface Lifecycle { + + + + + /** + * The LifecycleEvent type for the "component start" event. + */ + public static final String STARTING_EVENT = "starting"; + + + /** + * The LifecycleEvent type for the "component before start" event. + */ + public static final String STARTED_EVENT = "started"; + + + /** + * The LifecycleEvent type for the "component stop" event. + */ + public static final String STOPING_EVENT = "stoping"; + + + + /** + * The LifecycleEvent type for the "component after stop" event. + */ + public static final String STOPPED_EVENT = "stopped"; + + + + + /** + * 1. 기능 : Add a LifecycleEvent listener to this component. + * + * @param listener The listener to add + */ + public void addLifecycleListener(LifecycleListener listener); + + + /** + * 1. 기능 : Get the lifecycle listeners associated with this lifecycle. If this + * Lifecycle has no listeners registered, a zero-length array is returned. + */ + public LifecycleListener[] findLifecycleListeners(); + + + /** + * 1. 기능 : Remove a LifecycleEvent listener from this component. + * + * @param listener The listener to remove + */ + public void removeLifecycleListener(LifecycleListener listener); + + + /** + * 1. 기능 : Prepare for the beginning of active use of the public methods of this + * component. This method should be called before any of the public + * methods of this component are utilized. It should also send a + * LifecycleEvent of type START_EVENT to any registered listeners. + * + * @exception LifecycleException if this component detects a fatal error + * that prevents this component from being used + */ + public void start() throws LifecycleException; + + + /** + * 1. 기능 : Gracefully terminate the active use of the public methods of this + * component. This method should be the last one called on a given + * instance of this component. It should also send a LifecycleEvent + * of type STOP_EVENT to any registered listeners. + * + * @exception LifecycleException if this component detects a fatal error + * that needs to be reported + */ + public void stop() throws LifecycleException; + + + /** + * 1. 기능 : 기동 여부를 반환하느 메서드 + * 2. 처리 개요 : 기동 여부 변수를 반환한다. + * - + * 3. 주의사항 + * + * @return 기동 여부 + **/ + public boolean isStarted(); + +} diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleDAO.java b/src/com/eactive/eai/common/lifecycle/LifecycleDAO.java new file mode 100644 index 0000000..a23d698 --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleDAO.java @@ -0,0 +1,61 @@ +package com.eactive.eai.common.lifecycle; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; + +/** +* 1. 기능 : Lifecycle 관련 Rule 정보에 대한 Data Access Object 클래스 +* 2. 처리 개요 : Lifcycle관련 Rule 정보에 대한 DB Access 로직을 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class LifecycleDAO extends BaseDAO implements LifecycleQuery +{ + + /** + * 1. 기능 : 전체 Lifecycle Rule 정보를 SELECT하는 메서드 + * 2. 처리 개요 : 전체 Lifecycle Rule 정보를 SELECT하여 List에 담아 반환한다. + * - + * 3. 주의사항 + * + * @return 전체 Lifecycle Rule 정보 + * @exception DAOException SQLException 발생 시 + **/ + public List getAllLifecycles() throws DAOException { + + List list = new ArrayList(); + ResultSet rs = null; + String lifecycleClass = null; + int loadSequence = 0; + String lifeCyclUseDstcd = null; // Migration - 추가 + try { + this.connect(SELECT_ALL); + rs = this.executeQuery(); + while(rs.next()) { + lifecycleClass = rs.getString(1); + loadSequence = rs.getInt(2); + lifeCyclUseDstcd = rs.getString(3); // Migration - 추가 + LifecycleVO vo = new LifecycleVO(); + vo.setLifecycleClass(lifecycleClass); + vo.setLoadSequence(loadSequence); + vo.setLifeCyclUseDstcd(lifeCyclUseDstcd); + list.add(vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMLC101")); + } finally { + this.disconnect(); + } + return list; + } +} diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleEvent.java b/src/com/eactive/eai/common/lifecycle/LifecycleEvent.java new file mode 100644 index 0000000..ccb854e --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleEvent.java @@ -0,0 +1,118 @@ +package com.eactive.eai.common.lifecycle; + +import java.util.EventObject; + +/** +* 1. 기능 : Lifecycle Event 를 정의한 클래스 +* 2. 처리 개요 : Lifecycle Event를 표현한 Event 클래스 +* General event for notifying listeners of significant changes on a component +* that implements the Lifecycle interface. In particular, this will be useful +* on Containers, where these events replace the ContextInterceptor concept in +* Tomcat 3.x. +* 3. 주의사항 +* +*/ + +public final class LifecycleEvent + extends EventObject { + + /** + * + */ + private static final long serialVersionUID = 1L; + + + /** + * 1. 기능 : Construct a new LifecycleEvent with the specified parameters. + * 2. 처리 개요 : + * - Construct a new LifecycleEvent with the specified parameters. + * 3. 주의사항 + * + * @param lifecycle Component on which this event occurred + * @param type Event type (required) + **/ + public LifecycleEvent(Lifecycle lifecycle, String type) { + + this(lifecycle, type, null); + + } + + + /** + * 1. 기능 : Construct a new LifecycleEvent with the specified parameters. + * 2. 처리 개요 : + * - Construct a new LifecycleEvent with the specified parameters. + * 3. 주의사항 + * + * @param lifecycle Component on which this event occurred + * @param type Event type (required) + * @param data Event data (if any) + **/ + public LifecycleEvent(Lifecycle lifecycle, String type, Object data) { + + super(lifecycle); + this.lifecycle = lifecycle; + this.type = type; + this.data = data; + + } + + /** + * The event data associated with this event. + */ + private Object data = null; + + + /** + * The Lifecycle on which this event occurred. + */ + private Lifecycle lifecycle = null; + + + /** + * The event type this instance represents. + */ + private String type = null; + + + /** + * 1. 기능 : Return the event data of this event. + * 2. 처리 개요 : + * - Return the event data of this event. + * 3. 주의사항 + * + **/ + public Object getData() { + + return (this.data); + + } + + + /** + * 1. 기능 : Return the Lifecycle on which this event occurred. + * 2. 처리 개요 : + * - Return the Lifecycle on which this event occurred. + * 3. 주의사항 + * + **/ + public Lifecycle getLifecycle() { + + return (this.lifecycle); + + } + + /** + * 1. 기능 : Return the event type of this event. + * 2. 처리 개요 : + * - Return the event type of this event. + * 3. 주의사항 + **/ + public String getType() { + + return (this.type); + + } + + +} diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleException.java b/src/com/eactive/eai/common/lifecycle/LifecycleException.java new file mode 100644 index 0000000..771e10d --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleException.java @@ -0,0 +1,160 @@ + +package com.eactive.eai.common.lifecycle; + +/** +* 1. 기능 : Lifecycle 예외 처리를 위한 Exception 클래스 +* 2. 처리 개요 : Lifecycle 예외 처리를 위한 Exception 클래스 +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public final class LifecycleException extends Exception { + + + //------------------------------------------------------------ Constructors + + + /** + * + */ + private static final long serialVersionUID = 1L; + + + /** + * 1. 기능 : Construct a new LifecycleException with no other information. + * 2. 처리 개요 : Default Constructor + * - + * 3. 주의사항 + * + **/ + public LifecycleException() { + + this(null, null); + + } + + + /** + * 1. 기능 : Construct a new LifecycleException for the specified message. + * 2. 처리 개요 : 파라미터의 예외 발생 원인을 초기화한다. + * - + * 3. 주의사항 + * + * @param message Message describing this exception + **/ + public LifecycleException(String message) { + + this(message, null); + + } + + /** + * 1. 기능 : Construct a new LifecycleException for the specified throwable. + * 2. 처리 개요 : 파라미터의 오류(Throwable)을 Wrapper하기 위해 멤버에 초기화 한다. + * - + * 3. 주의사항 + * + * @param throwable Throwable that caused this exception + **/ + public LifecycleException(Throwable throwable) { + + this(null, throwable); + + } + + /** + * 1. 기능 : Construct a new LifecycleException for the specified message and throwable. + * 2. 처리 개요 : 파라미터의 값을 멤버 변수에 초기화 한다. + * - + * 3. 주의사항 + * + * @param message Message describing this exception + * @param throwable Throwable that caused this exception + **/ + public LifecycleException(String message, Throwable throwable) { + + super(); + this.message = message; + this.throwable = throwable; + + } + + + //------------------------------------------------------ Instance Variables + + + /** + * The error message passed to our constructor (if any) + */ + protected String message = null; + + + /** + * The underlying exception or error passed to our constructor (if any) + */ + protected Throwable throwable = null; + + + //---------------------------------------------------------- Public Methods + + /** + * 1. 기능 : Returns the message associated with this exception, if any. + * 2. 처리 개요 : 오류 발생 원인을 반환한다. + * - + * 3. 주의사항 + * + * @return Exception 발생 원인 + **/ + /** + * + */ + public String getMessage() { + + return (message); + + } + + /** + * 1. 기능 : Returns the throwable that caused this exception, if any. + * 2. 처리 개요 : 발생한 오류를 표현하는 Throwable + * - + * 3. 주의사항 + * + * @return 발생한 오류를 표현하는 Throwable + **/ + public Throwable getThrowable() { + + return (throwable); + + } + + /** + * 1. 기능 : Return a formatted string that describes this exception. + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @return + **/ + public String toString() { + + StringBuffer sb = new StringBuffer("LifecycleException: "); + if (message != null) { + sb.append(message); + if (throwable != null) { + sb.append(": "); + } + } + if (throwable != null) { + sb.append(throwable.toString()); + } + return (sb.toString()); + + } + + +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleListener.java b/src/com/eactive/eai/common/lifecycle/LifecycleListener.java new file mode 100644 index 0000000..64cf041 --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleListener.java @@ -0,0 +1,31 @@ +package com.eactive.eai.common.lifecycle; + +/** +* 1. 기능 : LifecyclEvent를 수신하여 비즈니스 로직을 처리하기 위한 Listener 인터페이스 +* 2. 처리 개요 : LifecycleEvent를 수신하기 위한 Listener 인터페이스를 정의한다. +* - Interface defining a listener for significant events (including "component +* start" and "component stop" generated by a component that implements the +* Lifecycle interface. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ + +public interface LifecycleListener { + + + /** + * 1. 기능 : LifecycleEvent 발생 시 실행된느 메서드 + * 2. 처리 개요 : LifecycleEvent 발생 시 실행되는 메서드이다. + * - Acknowledge the occurrence of the specified event. + * 3. 주의사항 + * + * @param event LifecycleEvent that has occurred + **/ + public void lifecycleEvent(LifecycleEvent event); + + +} diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleManager.java b/src/com/eactive/eai/common/lifecycle/LifecycleManager.java new file mode 100644 index 0000000..1e62165 --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleManager.java @@ -0,0 +1,324 @@ +package com.eactive.eai.common.lifecycle; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +//import java.util.HashMap; +//import java.util.Iterator; +import java.util.List; + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +/** +* 1. 기능 : Lifecycle Rule 정보를 DB로 부터 로딩해 메모리에 관리하는 Manager 클래스 +* 2. 처리 개요 : Lifecycle Rule 정보를 메모리에 로딩해 관리한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class LifecycleManager implements Lifecycle +{ + /** + * Default File Logger + */ + static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + /** + * Lifecycle Sigleton Instance + */ + private static LifecycleManager instance; + /** + * 기동 여부 + */ + private boolean started=false; + /** + * LifecycleSupport Instance + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * Lifecyclce Instance를 저장하는 List + */ + private List lifecycles; + /** + * Lifecycle Rule 정보를 저장하는 List + */ + private List infos; + + /** + * LIfecycle Event를 수신 / 처리할 Listener 클래스 + */ + private LifecycleListener listener; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : Default Constructor + * - + * 3. 주의사항 + * + **/ + private LifecycleManager() { + + } + + /** + * 1. 기능 : LifecycleManager Singleton Instance를 반환하는 메서드 + * 2. 처리 개요 : LifecycleManager Singleton Instance를 반환한다. + * - + * 3. 주의사항 + * + * @return LifecycleManager Singleton Instance + **/ + public static LifecycleManager getInstance() { + if(instance==null) { + synchronized(LifecycleManager.class) { + if(instance==null) { + instance = new LifecycleManager(); + } + } + } + + return instance; + } + + /** + * 1. 기능 : LifecycleManager 기동 시 초기화 로직을 처리하는 메서드 + * 2. 처리 개요 : Lifecycle Rule 전체 정보를 로딩 초기화하고, 해당 Lifecycle 객체를 생성 초기화 한다. + * - + * 3. 주의사항 + * + * @exception LifecycleException 이미 기동된 경우 or 설정된 Rule이 Lifecycle 클래스가 아닌 경우 + **/ + @SuppressWarnings("unchecked") + public void start() throws LifecycleException { + + if (started) + throw new LifecycleException("BECEAIMLC201"); + + try { + + listener = new DefaultLifecycleListener(); + this.addLifecycleListener(listener); + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + lifecycles = new ArrayList(); + + // EAIMessage Table Initializing .... + LifecycleDAO dao = null; + try { + dao = (LifecycleDAO)DAOFactory.newInstance().create(LifecycleDAO.class); + + // LifecycleDAO를 이용하여 테이블에 등록된 값들을 가지고 온다. + infos = dao.getAllLifecycles(); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMLC202")); + } + + Collections.sort(infos); + + LifecycleVO vo = null; + Lifecycle lf = null; + + for(int i=0;i=0;i--) { + lf = (Lifecycle)lifecycles.get(i); + if(!lf.isStarted()) continue; + + String[] msgArgs = new String[1]; + msgArgs[0] = lf.getClass().getName(); + if (logger.isDebugEnabled()) logger.debug(ExceptionUtil.make("BDCEAIMLC208", msgArgs)); + + try { + lf.stop(); + lf.removeLifecycleListener(listener); + } catch(Exception e) { + logger.error(ExceptionUtil.getErrorCode(e, "BECEAIMLC209")); + } + } + + this.infos.clear(); + this.lifecycles.clear(); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + this.removeLifecycleListener(this.listener); + } + + /** + * 1. 기능 : 기동여부를 반환하는 메서드 + * 2. 처리 개요 : 기동 여부를 반환한다. + * - + * 3. 주의사항 + * + * @return 기동여부 + * @exception + **/ + public boolean isStarted() { + return this.started; + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : BizKeyManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : BizKeyManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public void addLifecycle(LifecycleVO vo) { + infos.add(vo); + } + + /** + * 1. 기능 : Lifecycle Rule 정보를 변경하는 메서드 + * 2. 처리 개요 : Lifecycle Rule 정보를 변경한다. + * - + * 3. 주의사항 + * + * @param vo Lifecycle Rule 정보 + **/ + public void updateLifecycle(LifecycleVO vo) { + LifecycleVO tmp = null; + + search: + for(int i=0;i getLifecycleVOList() { + return infos; + } +} diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleQuery.java b/src/com/eactive/eai/common/lifecycle/LifecycleQuery.java new file mode 100644 index 0000000..be05ab4 --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleQuery.java @@ -0,0 +1,23 @@ +package com.eactive.eai.common.lifecycle; + +import com.eactive.eai.common.dao.Keys; +/** +* 1. 기능 : LifecycleDAO에서 사용하는 SQL Query를 정의한 상수 인터페이스 +* 2. 처리 개요 : LifecycleDAO에서 사용하는 SQL Query를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public interface LifecycleQuery +{ + /** + * Lifecycle 전체 Rule 정보를 SELECT하는 QUERY + */ + public static final String SELECT_ALL = + "SELECT LifeCyclClsName, LodinSeq, LifeCyclUseDstcd FROM " + Keys.TABLE_OWNER + "TSEAIBP04"; + +} diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleSupport.java b/src/com/eactive/eai/common/lifecycle/LifecycleSupport.java new file mode 100644 index 0000000..06a229f --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleSupport.java @@ -0,0 +1,71 @@ +package com.eactive.eai.common.lifecycle; + +import java.io.Serializable; + +public final class LifecycleSupport implements Serializable { + + private static final long serialVersionUID = 1L; + + private Lifecycle lifecycle = null; + private LifecycleListener listeners[] = new LifecycleListener[0]; + + public LifecycleSupport(Lifecycle lifecycle) { + + super(); + this.lifecycle = lifecycle; + + } + + public void addLifecycleListener(LifecycleListener listener) { + + synchronized (listeners) { + LifecycleListener results[] = new LifecycleListener[listeners.length + 1]; + for (int i = 0; i < listeners.length; i++) + results[i] = listeners[i]; + results[listeners.length] = listener; + listeners = results; + } + + } + + public LifecycleListener[] findLifecycleListeners() { + + return listeners; + + } + + public void fireLifecycleEvent(String type, Object data) { + + LifecycleEvent event = new LifecycleEvent(lifecycle, type, data); + LifecycleListener interested[] = null; + synchronized (listeners) { + interested = (LifecycleListener[]) listeners.clone(); + } + for (int i = 0; i < interested.length; i++) + interested[i].lifecycleEvent(event); + + } + + public void removeLifecycleListener(LifecycleListener listener) { + + synchronized (listeners) { + int n = -1; + for (int i = 0; i < listeners.length; i++) { + if (listeners[i] == listener) { + n = i; + break; + } + } + if (n < 0) + return; + LifecycleListener results[] = + new LifecycleListener[listeners.length - 1]; + int j = 0; + for (int i = 0; i < listeners.length; i++) { + if (i != n) + results[j++] = listeners[i]; + } + listeners = results; + } + } +} diff --git a/src/com/eactive/eai/common/lifecycle/LifecycleVO.java b/src/com/eactive/eai/common/lifecycle/LifecycleVO.java new file mode 100644 index 0000000..cb5d8da --- /dev/null +++ b/src/com/eactive/eai/common/lifecycle/LifecycleVO.java @@ -0,0 +1,212 @@ +package com.eactive.eai.common.lifecycle; + +import java.io.Serializable; + +/** +* 1. 기능 : Lifecycle Rule 정보를 정의한 Java Value Object 클래스 +* 2. 처리 개요 : Lifecycle Rule 정보를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class LifecycleVO implements Serializable, Comparable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + /** + * Lifecycle 클래스 + */ + private String lifecycleClass; // 생명주기클래스명[TSEAIFR05.LifeCyclClsName] + /** + * 로딩 / 초기화 순서 + */ + private int loadSequence; // 로딩순서[TSEAIFR05.LodinSeq] + + /** + * 생명주기사용구분코드 + */ + private String lifeCyclUseDstcd; // Migration - 추가 생명주기사용구분코드[TSEAIFR05.LifeCyclUseDstcd] + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public LifecycleVO() { + this("", -1); + } + + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public LifecycleVO(String lifecycleClass, int loadSequence) { + this.lifecycleClass = lifecycleClass; + this.loadSequence = loadSequence; + } + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public LifecycleVO(String lifecycleClass, int loadSequence, String lifeCyclUseDstcd) { + this.lifecycleClass = lifecycleClass; + this.loadSequence = loadSequence; + this.lifeCyclUseDstcd = lifeCyclUseDstcd; + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public void setLifecycleClass(String lifecycleClass) { + this.lifecycleClass = lifecycleClass; + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public String getLifecycleClass() { + return this.lifecycleClass; + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public void setLoadSequence(int loadSequence) { + this.loadSequence = loadSequence; + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public int getLoadSequence() { + return this.loadSequence; + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public int compareTo(Object obj) + { + if( !(obj instanceof LifecycleVO) ) { + return -1; + } + LifecycleVO l = (LifecycleVO)obj; + return this.getLoadSequence() - l.getLoadSequence(); + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public boolean equals(Object obj) { + if(obj instanceof LifecycleVO) { + LifecycleVO l = (LifecycleVO)obj; + return ( l.getLifecycleClass().equals(this.getLifecycleClass()) && (l.getLoadSequence()== this.getLoadSequence()) && (l.getLifeCyclUseDstcd()== this.getLifeCyclUseDstcd()) ); + } else { + return false; + } + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("LifecycleVO[ lifecycleClass=").append(lifecycleClass); + sb.append(", loadSequence=").append(loadSequence); + sb.append(", lifeCyclUseDstcd=").append(lifeCyclUseDstcd); + sb.append(" ]"); + return sb.toString(); + } + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public void setLifeCyclUseDstcd(String lifeCyclUseDstcd) { + this.lifeCyclUseDstcd = lifeCyclUseDstcd; + } + + + + /** + * 1. 기능 : + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public String getLifeCyclUseDstcd() { + return this.lifeCyclUseDstcd; + } +} diff --git a/src/com/eactive/eai/common/property/FileLoggerPropertyChangeListener.java b/src/com/eactive/eai/common/property/FileLoggerPropertyChangeListener.java new file mode 100644 index 0000000..131cb3a --- /dev/null +++ b/src/com/eactive/eai/common/property/FileLoggerPropertyChangeListener.java @@ -0,0 +1,35 @@ +package com.eactive.eai.common.property; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +import com.eactive.eai.common.util.LogKeys; +import com.eactive.eai.common.util.Logger; + +public class FileLoggerPropertyChangeListener implements PropertyChangeListener { + + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + @Override + public void propertyChange(PropertyChangeEvent evt) { + + PropManager prptManager = PropManager.getInstance(); + PropGroupVO propGroupVO = (PropGroupVO)evt.getSource(); + String loggerNames = prptManager.getProperty(LogKeys.LOGGER_INFO, LogKeys.INITIAL_LOGGER_LIST); + + if ( loggerNames != null && + loggerNames.contains( propGroupVO.getName() ) ) { + + if ( logger.isDebugEnabled() ) { + logger.debug("FileLoggerPropertyChangeListener propertyChange() " + propGroupVO.getName() ); + } + Logger.setLoggerLevel(propGroupVO.getName()); + } + } + + @Override + public boolean equals(Object obj) { + return obj instanceof FileLoggerPropertyChangeListener; + } + +} diff --git a/src/com/eactive/eai/common/property/PropGroupVO.java b/src/com/eactive/eai/common/property/PropGroupVO.java new file mode 100644 index 0000000..456bc4b --- /dev/null +++ b/src/com/eactive/eai/common/property/PropGroupVO.java @@ -0,0 +1,122 @@ +package com.eactive.eai.common.property; + +import com.eactive.eai.common.util.NullControl; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Properties; + +/** +* 1. 기능 : 프라퍼티 정보를 를 정의한 Java Value Object 클래스 +* 2. 처리 개요 : 프라퍼티 정보를 정의한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class PropGroupVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String name; //프라퍼티 그룹명[TSEAICM02.PrptyGroupName] + //private String eaiServer; // Migration + private String description; //프라퍼티 그룹설명[TSEAICM02.PrptyGroupDesc] + private Properties props; //프라퍼티 명, 프라퍼티2값[TSEAICM02.PrptyName, TSEAICM02.Prpty2Val] + + public PropGroupVO() { + this(""); + } + + public PropGroupVO(String name) { + this(name,""); + } + + public PropGroupVO(String name, String description) { + this.name = name; + this.description = description; + this.props = new Properties(); + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDescription() { + return NullControl.trimSpace(this.description); + } + + public String getProperty(String key) { + return (String)props.get(key); + } + + public String getProperty(String key, String defaultValue) { + String value = (String)props.get(key); + return (value==null) ? defaultValue : value; + } + + public void addProperty(String key, String value) { + props.put(key, value); + } + + public void setProperty(String key, String value) { + props.put(key,value); + } + + public void removeProperty(String key) { + props.remove(key); + } + + public String[] keys() { + @SuppressWarnings("rawtypes") + Iterator it = this.props.keySet().iterator(); + String[] propKeys = new String[this.props.size()]; + for(int i = 0; it.hasNext(); i++){ + propKeys[i] = (String)it.next(); + } + Arrays.sort(propKeys); + return propKeys; + } + + public Properties getProperties() { + return props; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("PropGroupVO [ name=").append(name); +// sb.append(", eaiServer=").append(eaiServer); + sb.append(", description=").append(description); + sb.append(", Properties=").append(props); + sb.append(" ]"); + + return sb.toString(); + } + + public void setProperties(Properties prop){ + this.props = prop; + } +// Migration - Start +// public void setEaiServer(String eaiServer) { +// this.eaiServer = eaiServer; +// } +// +// public String getEaiServer() { +// return this.eaiServer; +// } +// Migration - End + +} diff --git a/src/com/eactive/eai/common/property/PropManager.java b/src/com/eactive/eai/common/property/PropManager.java new file mode 100644 index 0000000..ca8c8cb --- /dev/null +++ b/src/com/eactive/eai/common/property/PropManager.java @@ -0,0 +1,414 @@ +package com.eactive.eai.common.property; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Properties; + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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.Logger; + +/** +* 1. 기능 : Property Rule 정보를 DB로 부터 로딩해 메모리에 관리하는 Manager 클래스 +* 2. 처리 개요 : DB Rule 정보에 저장된 Property Rule 정보를 메모리에 로딩 관리한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class PropManager implements Lifecycle +{ + + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + /** + * PropManager Single Instance + */ + private static PropManager instance = new PropManager(); + + /** + * LifecyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * PropertyChangeSupport object + */ + private PropertyChangeSupport property = new PropertyChangeSupport(this); + + + /** + * Property 정보를 저장하는 collection + */ + private HashMap groups = new HashMap(); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + **/ + private PropManager() {} + + /** + * 1. 기능 : PropManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : PropManager Singleton Object를 반환한다. + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public static PropManager getInstance() { + return instance; + } + + // ================================================================================= + // 이 부분은 PorpertyChangeListener용으로 제공되는 메소드이다. + + /** + * 1. 기능 : PropertyChangeListener를 등록하는 메서드 + * 2. 처리 개요 : PropertyChangeListener를 등록하는 메서드 + * - + * 3. 주의사항 + * + * @param listener PropertyChangeListener + * @exception + **/ + public void addPropertyChangeListener(PropertyChangeListener listener) { + property.addPropertyChangeListener(listener); + } + + /** + * 1. 기능 : PropertyChangeListener를 삭제하는 메서드 + * 2. 처리 개요 : PropertyChangeListener를 삭제하는 메서드 + * - + * 3. 주의사항 + * + * @param listener PropertyChangeListener + * @exception + **/ + public void removePropertyChangeListener(PropertyChangeListener listener) { + property.removePropertyChangeListener(listener); + } + + /** + * 1. 기능 : PropertyChangeEvent를 생성하는 메소드 + * 2. 처리 개요 : PropertyChangeEvent를 생성하는 메소드 + * - + * 3. 주의사항 + * + * @param source PropGroupVO + * @param propertyName 프라퍼티명 + * @param oldValue 변경 이전값 + * @param newValue 변경 값 + * @return PropertyChangeEvent + * @exception + **/ +// private PropertyChangeEvent createEvent(PropGroupVO source, String propertyName, Object oldValue, Object newValue) { +// return new PropertyChangeEvent(source, propertyName, oldValue, newValue); +// } + + /** + * 1. 기능 : PropManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : PropManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + + + // ================================================================================= + // 이 부분은 Lifecycle용으로 제공되는 메소드이다. + /** + * 1. 기능 : Lifecycle의 start 메서드로 PropManager를 초기화하는 메서드 + * 2. 처리 개요 : PropertyDAO를 이용해 추출 Rule 정보 모두를 가져와 초기화한다. + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public void start() throws LifecycleException { + if (started) + throw new LifecycleException("BECEAIMPT201"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, null); + + PropertyDAO dao = null; + try { + DAOFactory factory = DAOFactory.newInstance(); + dao = (PropertyDAO)factory.create(PropertyDAO.class); + this.groups = dao.getAllProperties(); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMPT201")); + } + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, null); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 PropManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱한 프라퍼티 Rule 정보를 clear한다. + * - + * 3. 주의사항 + * + * @param + * @return + * @exception + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMPT203"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, null); + + + + started = false; + logger.debug("PropManager] It is stopped."); + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, null); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : Property 그룹정보를 등록하는 메서드 + * 2. 처리 개요 : Property 그룹정보를 등록하는 메서드. + * - + * 3. 주의사항 + * + * @param name 프라퍼티 그룹명 + * @param description 프라퍼티 그룹설명 + **/ +// public void addPropGroupVO(String name, String description) { +// groups.put(name, new PropGroupVO(name,description)); +// } + + /** + * 1. 기능 : EAI 서비스 코드에 대한 Property 정보를 반환하는 메서드 + * 2. 처리 개요 : 파라미터의 프라퍼티 그룹명에 대한 Property 정보를 반환한다. + * - + * 3. 주의사항 + * + * @param name 프라퍼티 그룹명 + * @return Property Rule 정보 + **/ + public PropGroupVO getPropGroupVO(String name) { + return groups.get(name); + } + + + public PropGroupVO getPropGroupVOinDB(String name) { + try { + PropertyDAO dao = (PropertyDAO)DAOFactory.newInstance().create(PropertyDAO.class); + PropGroupVO vo = dao.getProperties(name); + if(vo==null) throw new RuntimeException("Cannot find the Property Group in PropManager. - ["+name+"]"); + return vo; + } catch (Exception e) { + logger.error( e.getMessage(), e); + return null; + } + } + + + + /** + * 1. 기능 : 프라퍼티 키에 대한 Property 값를 반환하는 메서드 + * 2. 처리 개요 : 파라미터의 프라퍼티 키에 대한 Property 값를 반환한다. + * - + * 3. 주의사항 + * + * @param key 프라퍼티 키 + * @return Property 값 + **/ +// public String getProperty(String key) { +// +// return getProperty(com.eactive.eai.common.server.Keys.DEFAULT_SERVER, key); +// } + + + + + + /** + * 1. 기능 : 프라퍼티 키에 대한 Property 값를 반환하는 메서드 + * 2. 처리 개요 : 파라미터의 프라퍼티 키에 대한 Property 값를 반환한다. + * - + * 3. 주의사항 + * + * @param group 프라퍼티 그룹명 + * @param key 프라퍼티 키 + * @return Property 값 + **/ + public String getProperty(String group, String key) { + if (!started) { + try { + PropertyDAO dao = (PropertyDAO)DAOFactory.newInstance().create(PropertyDAO.class); + return dao.getProgertyValue(group, key); + } catch (Exception e) { + logger.error( e.getMessage(), e); + return null; + } + } + + PropGroupVO vo = (PropGroupVO) groups.get(group); + if (vo == null) return null; + return vo.getProperty(key); + } + + /** + * 1. 기능 : 프라퍼티 그룹명에 대한 Property 리스트를 반환하는 메서드 + * 2. 처리 개요 :프라퍼티 그룹명에 대한 Property 리스트를 반환한다. + * - + * 3. 주의사항 + * + * @param group 프라퍼티 그룹명 + * @return Property 값 + **/ + public Properties getProperties(String group) { + if (!started) { + try { + PropertyDAO dao = (PropertyDAO)DAOFactory.newInstance().create(PropertyDAO.class); + PropGroupVO vo = dao.getProperties(group); + if(vo==null) throw new RuntimeException("Cannot find the Property Group in PropManager. - ["+group+"]"); + return vo.getProperties(); + } catch (Exception e) { + logger.error( e.getMessage(), e); + return null; + } + } + + PropGroupVO vo = (PropGroupVO) groups.get(group); + if(vo==null) throw new RuntimeException("Cannot find the Property Group in PropManager. - ["+group+"]"); + return vo.getProperties(); + } + + /** + * 1. 기능 : 프라퍼티 정보를 등록하는 메서드 + * 2. 처리 개요 : 프라퍼티 정보를 등록한다. + * - + * 3. 주의사항 + * + * @param group 프라퍼티 그룹명 + * @param key 프라퍼티 키 + * @param value 프라퍼티 값 + **/ +// public void setProperty(String group, String key, String value) { +// PropGroupVO gvo = (PropGroupVO)groups.get(group); +// String oldValue = gvo.getProperty(key); +// gvo.setProperty(key,value); +// // EVENET 발생!! +// if (!oldValue.equals(value)) { +// property.firePropertyChange(createEvent(gvo, key, oldValue, value)); +// } +// } + + /** + * 1. 기능 : 프라퍼티 정보를 등록하는 메서드 + * 2. 처리 개요 : 프라퍼티 정보를 등록한다. + * - + * 3. 주의사항 + * + * @param group 프라퍼티 그룹명 + * @param vo PropGroupVO + **/ + public void setPropGroupVO(String group, PropGroupVO vo){ + groups.put(group, vo); + } + + /** + * 1. 기능 : 프라퍼티 정보를 삭제하는 메서드 + * 2. 처리 개요 : 프라퍼티 정보를 삭제한다. + * - + * 3. 주의사항 + * + * @param name 프라퍼티 그룹명 + * @param vo PropGroupVO + **/ + public void removePropGroupVO(String name){ + groups.remove(name); + } + + /** + * 1. 기능 : 프라퍼티 그룹명 리스트를 반환하는 메서드 + * 2. 처리 개요 : 프라퍼티 그룹명 리스트를를 반환한다. + * - + * 3. 주의사항 + * + * @return String[] 프라퍼티 그룹명 리스트 + **/ + public String[] getAllPropGroupNames() { + Iterator it = this.groups.keySet().iterator(); + String[] name = new String[this.groups.size()]; + for(int i=0;it.hasNext();i++) { + name[i] = (String)it.next(); + } + + Arrays.sort(name); + return name; + } +} diff --git a/src/com/eactive/eai/common/property/PropertyDAO.java b/src/com/eactive/eai/common/property/PropertyDAO.java new file mode 100644 index 0000000..8f551c9 --- /dev/null +++ b/src/com/eactive/eai/common/property/PropertyDAO.java @@ -0,0 +1,133 @@ +package com.eactive.eai.common.property; + +import java.sql.ResultSet; +import java.util.HashMap; + +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +/** +* 1. 기능 : 프라퍼티 정보에 대한 Data Access Object 클래스 +* 2. 처리 개요 : 프라퍼티 Rule 정보에 대한 DB Access 로직을 처리한다. +* * - +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class PropertyDAO extends BaseDAO implements PropertyQuery +{ + + + /** + * 1. 기능 : 프라퍼티 Rule 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서 + * PropGroupVO 객체 리스트로 생성 반환하는 메서드. + * 2. 처리 개요 : 프라퍼티Rule정보 전체를 SELECT해서 한 레코드를 PropGroupVO로 생성 HashMap에 + * 저장하여 반환한다. + * 3. 주의사항 + * + * @return HashMap 프라퍼티Rule 정보 전체데이터로 PropGroupVO Collection + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 프라퍼티 Rule정보를 가져오다 발생되는 모든 에러[BECEAIMPT101] + **/ + public HashMap getAllProperties() throws DAOException { + + HashMap groups = new HashMap(); + ResultSet rs = null; + try { + this.connect(GET_ALL_PROPERTIES); + + rs = executeQuery(); + + String current = null, previous = ""; + PropGroupVO group = null; + + while (rs.next()) { + current = rs.getString(1); + if (!current.equals(previous)) { + if (group!=null) logger.debug(" - "+ group.toString()); + group = new PropGroupVO(current); + groups.put(current, group); + previous = current; + } + + group.addProperty(rs.getString(2),rs.getString(3)); + } + + return groups; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMPT101")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : 특정 Property 공통 정보를 가져오는 메소드 + * 2. 처리 개요 : 파라미터의 EAI서버명과 프라퍼티그룹명에 따른 프라퍼티 상세정보를 조회 + * 3. 주의사항 + * + * @param svrNm EAI서버명 + * @param grpNm 프라퍼티그룹명 + * @return 프라퍼티 Rule 정보를 표현한 PropGroupVO 객체들을 담는 HashMap을 반환 + * @exception DAOException DB SELECT 시 발생하는 SQLException을 포함한 프라퍼티 Rule 상세정보 생성 시 발생하는 모든 에러 + **/ + public PropGroupVO getProperties(String grpNm) throws DAOException { + + ResultSet rs = null; + try { + + this.connect(GET_PROPERTIES_LIST); + this.preparedStatement.setString(1, grpNm); + rs = executeQuery(); + + PropGroupVO vo = new PropGroupVO(); + vo.setName(grpNm); + while(rs.next()) { + vo.addProperty(rs.getString(1), rs.getString(2)); + } + return vo; + } catch(Exception e) { + String errorText = ExceptionUtil.make("BECEAIMPT103", grpNm); + if (logger.isError()) logger.error(errorText); + throw new DAOException(errorText); + + } finally { + this.disconnect(); + } + + } + + public String getProgertyValue(String propGroupName, String propName) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + this.connect(SELECT_PROPERTY_VALUE); + + index = 1; + this.preparedStatement.setString(index++, propGroupName); + this.preparedStatement.setString(index++, propName ); + + rs = executeQuery(); + + if (rs.next()) { + return StringUtil.nvlTrim(rs.getString("Prpty2Val")); + } else { + return null; + } + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINED_CD"); + throw new DAOException(errMsg); + } finally { + disconnect(); + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/property/PropertyQuery.java b/src/com/eactive/eai/common/property/PropertyQuery.java new file mode 100644 index 0000000..57fb62b --- /dev/null +++ b/src/com/eactive/eai/common/property/PropertyQuery.java @@ -0,0 +1,46 @@ +package com.eactive.eai.common.property; + +import com.eactive.eai.common.dao.Keys; + +/** +* 1. 기능 : PropertyDAO에서 사용하는 SQL Query문을 정의한 상수 인터페이스 +* 2. 처리 개요 : PropertyDAO에서 사용하는 SQL Query문을 상수로 정의한다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public interface PropertyQuery +{ + + /** + * 프라퍼티 Rule 정보 리스트를 SELECT하는 QUERY + */ + public static final String GET_ALL_PROPERTIES = + "select a.PrptyGroupName, b.PrptyName, b.Prpty2Val "+ + "from " + Keys.TABLE_OWNER + "TSEAIBP01 a, " + Keys.TABLE_OWNER + "TSEAIBP02 b "+ + "where a.PrptyGroupName = b.PrptyGroupName "+ + "order by a.PrptyGroupName "; + + /** + * 프라퍼티 공통 정보 리스트를 조회하는 QUERY + */ + public static final String GET_PROPERTIES_LIST = "select PrptyName, Prpty2Val from " + Keys.TABLE_OWNER + "TSEAIBP02 " + + "where PrptyGroupName = ? " + + "order by PrptyName "; + /** + * 프라퍼티 Group 리스트 조희 + * + */ + public static final String SELECT_ALL_PROPERTY_GROUPS = + "SELECT PrptyGroupName FROM " + Keys.TABLE_OWNER + "TSEAIBP01 WHERE PrptyGroupName!='ALL' ORDER BY PrptyGroupName"; + + //특정 프라퍼티 값 조회 + public static final String SELECT_PROPERTY_VALUE = + "SELECT Prpty2Val \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBP02 \n" + + "WHERE PrptyGroupName = ? \n" + + "AND PrptyName = ?"; +} diff --git a/src/com/eactive/eai/common/routing/JMSQueueSender.java b/src/com/eactive/eai/common/routing/JMSQueueSender.java new file mode 100644 index 0000000..d5aa882 --- /dev/null +++ b/src/com/eactive/eai/common/routing/JMSQueueSender.java @@ -0,0 +1,76 @@ +package com.eactive.eai.common.routing; + +import javax.jms.TextMessage; +import javax.jms.ObjectMessage; +import javax.jms.JMSException; +import javax.jms.Queue; +import javax.jms.QueueConnection; +import javax.jms.QueueConnectionFactory; +import javax.jms.QueueSender; +import javax.jms.QueueSession; + +import com.eactive.eai.common.util.ServiceLocator; + +public class JMSQueueSender { + private QueueConnectionFactory factory; + private QueueConnection con = null; + private QueueSession ses = null; + private QueueSender qsender; + private Queue queue = null; + private TextMessage msg; + private ObjectMessage objmsg; + + private String jms_connectionfactory; + private String queue_name; + + public void send(String queueConnectionFactory, String queueName, String message, String id) throws JMSException { + init(queueConnectionFactory, queueName); + msg = ses.createTextMessage(); + if(id!=null) msg.setJMSCorrelationID(id); + msg.setText(message); + qsender.send(msg); + closeQueueConnection(); + } + + public void sendObject(String queueConnectionFactory, String queueName, java.io.Serializable message, String id) throws JMSException { + + init(queueConnectionFactory, queueName); + objmsg = ses.createObjectMessage(); + if(id!=null) objmsg.setJMSCorrelationID(id); + objmsg.setObject(message); + qsender.send(objmsg); + closeQueueConnection(); + } + + public void init(String queueConnectionFactory, String queueName) { + jms_connectionfactory = queueConnectionFactory; + queue_name = queueName; + startQueueConnection(); + } + + + public void close() { + closeQueueConnection(); + } + + private void startQueueConnection() { + try { + ServiceLocator locator = ServiceLocator.getInstance(); + + factory = locator.getQueueConnectionFactory(jms_connectionfactory); + con = factory.createQueueConnection(); + ses = con.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); + queue = (Queue)locator.getQueue(queue_name); + qsender = ses.createSender(queue); + con.start(); + } catch (Throwable e) { + e.printStackTrace(); + closeQueueConnection(); + } + } + private void closeQueueConnection() { + if (ses != null) try { ses.close(); ses = null; } catch (Throwable e) {}; + if (con != null) try { con.stop(); } catch (Throwable e) {}; + if (con != null) try { con.close(); con = null; } catch (Throwable e) {}; + } +} diff --git a/src/com/eactive/eai/common/routing/JobHandlerConsumer.java b/src/com/eactive/eai/common/routing/JobHandlerConsumer.java new file mode 100644 index 0000000..f1ad16a --- /dev/null +++ b/src/com/eactive/eai/common/routing/JobHandlerConsumer.java @@ -0,0 +1,139 @@ +package com.eactive.eai.common.routing; + +import javax.jms.Connection; +import javax.jms.Destination; +import javax.jms.ExceptionListener; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.ObjectMessage; +import javax.jms.Session; + +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.job.jobComm.OutboundFTPHandle; +import com.eactive.eai.batch.job.jobComm.OutboundSocketHandle; +import com.eactive.eai.batch.job.jobHandle.JobFinishHandler; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class JobHandlerConsumer implements Runnable, ExceptionListener { + + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + Connection connection = null; + Session session = null; + MessageConsumer consumer = null; + String name = null; + String queue = null; + boolean run = true; + + public JobHandlerConsumer(String name, Connection con, String queue) { + this.connection = con; + try { + this.name = name; + this.queue = queue; + connection.start(); + connection.setExceptionListener(this); + + // Create a Session + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Create the destination (Topic or Queue) + Destination destination = session.createQueue(queue); + consumer = session.createConsumer(destination); + } catch (JMSException e) { + logger.error(e.getMessage(), e); + } + } + + @Override + public void run() { + BatchDoc batchDoc = null; + while(run) { + try { + Message message = consumer.receive(2000); + + ObjectMessage omsg = null; + + if(message == null) { +// logger.warn(name + " -> EMPTY MESSAGE..."); + continue; + } + + if(message instanceof ObjectMessage) { + omsg = (ObjectMessage)message; + } else { + throw new RuntimeException(name+" Invlid JMS Message Type. - "+message); + } + + try { + batchDoc = (BatchDoc)omsg.getObject(); + } catch(Exception e) { + throw new RuntimeException(name+" Invlid value object in ObjectMessage. - "+e.getMessage() ); + } + + //LayerCode, SubLayerCode 설정 + EAIBatchMsgManager.updateBatchMsg(batchDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis()); + + try { + if ( batchDoc.getBatchMsg().getHeader().getRuleCode().startsWith("FTP") ){ + OutboundFTPHandle handle = new OutboundFTPHandle(); + handle.proc(batchDoc); + }else{ + OutboundSocketHandle handle = new OutboundSocketHandle(); + handle.proc(batchDoc); + } + } catch (Exception ex) { + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJH007"); + logger.error(errMsg, ex); + + // DB로그 처리 + new JobFinishHandler(batchDoc).handleErrorEnd(errMsg); + + } catch (Exception e2) { + logger.error("★★★★★ JobHandler JPD 예외 처리 중 에러 !! ★★★★★", e2); + } + } + } + catch(IllegalStateException ise) { + logger.error(name+" IllegalStateException = " + ise.getMessage(), ise); + + } + catch(JMSException e) { + logger.error(name+" JMSException = " + e.getMessage(), e); + run = false; + } + catch(RuntimeException e) { + logger.error(name+" RuntimeException = " + e.getMessage(), e); + } + } + } + + public void stop() { + run = false; + if(consumer != null) + try { + consumer.close(); + } catch (JMSException e) { } + if(session != null) + try { + session.close(); + } catch (JMSException e) { } + if(connection != null) + try { + connection.close(); + } catch (JMSException e) { } + } + + @Override + public void onException(JMSException arg0) { + logger.error("JMS Exception occured. Shutting down client."); + stop(); + } +} diff --git a/src/com/eactive/eai/common/routing/JobHandlerConsumerService.java b/src/com/eactive/eai/common/routing/JobHandlerConsumerService.java new file mode 100644 index 0000000..d4256e5 --- /dev/null +++ b/src/com/eactive/eai/common/routing/JobHandlerConsumerService.java @@ -0,0 +1,119 @@ +package com.eactive.eai.common.routing; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.jms.Connection; +import javax.jms.Session; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; + +import com.eactive.eai.common.util.Logger; + +public class JobHandlerConsumerService implements InitializingBean, DisposableBean { + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + // uri = "vm://localhost?broker.persistent=false&broker.useJmx=false" + // uri = "tcp://localhost:61617"" + private String uri; + private String queue; + private int maxThread; + + Connection connection = null; + Session[] sessions = null; + JobHandlerConsumer[] consumers = null; + + ExecutorService es = null; + + public String geturi() { + return uri; + } + + public void seturi(String uri) { + this.uri = uri; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + this.queue = queue; + } + + public int getMaxThread() { + return maxThread; + } + + public void setMaxThread(int maxThread) { + this.maxThread = maxThread; + } + + @Override + public void afterPropertiesSet() throws Exception { + startConsumer(); + } + + @Override + public void destroy() throws Exception { + stopConsumer(); + } + + public void startConsumer() { + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri); + connectionFactory.setTrustAllPackages(true); + + es = Executors.newFixedThreadPool(maxThread); + + connection = connectionFactory.createConnection(); + connection.start(); + + consumers = new JobHandlerConsumer[maxThread]; + + for(int i=0; i EMPTY MESSAGE..."); + continue; + } + + if (message instanceof ObjectMessage) { + omsg = (ObjectMessage) message; + } else { + throw new RuntimeException(name + " Invlid JMS Message Type. - " + message); + } + + try { + messageStr = (String) omsg.getObject(); + } catch (Exception e) { + throw new RuntimeException(name + " Invlid value object in ObjectMessage. - " + e.getMessage()); + } + + try { + if (messageStr.equals(PROC_JOB)) { + ScheduleHandlerProcess process = new ScheduleHandlerProcess(); + process.clientRequest(); + } else if (messageStr.equals(REG_JOB)) { + ScheduleRecvProcess process = new ScheduleRecvProcess(); + process.clientRequest(); + } else { + logger.error(this.getClass().getName() + "[messageStr]:" + messageStr + "[Message]:" + message); + } + } catch (Exception e) { + logger.error("프로세스 수행 중 에러 발생. [" + message + "]- " + e.getMessage()); + } + + } catch (IllegalStateException ise) { + logger.error(name + " IllegalStateException = " + ise.getMessage(), ise); + + } catch (JMSException e) { + logger.error(name + " JMSException = " + e.getMessage(), e); + run = false; + } catch (RuntimeException e) { + logger.error(name + " RuntimeException = " + e.getMessage(), e); + } + } + } + + public void stop() { + run = false; + if (consumer != null) + try { + consumer.close(); + } catch (JMSException e) { + } + if (session != null) + try { + session.close(); + } catch (JMSException e) { + } + if (connection != null) + try { + connection.close(); + } catch (JMSException e) { + } + } + + @Override + public void onException(JMSException arg0) { + logger.error("JMS Exception occured. Shutting down client."); + stop(); + } +} diff --git a/src/com/eactive/eai/common/routing/TimerEventListenerConsumerService.java b/src/com/eactive/eai/common/routing/TimerEventListenerConsumerService.java new file mode 100644 index 0000000..f7c710b --- /dev/null +++ b/src/com/eactive/eai/common/routing/TimerEventListenerConsumerService.java @@ -0,0 +1,117 @@ +package com.eactive.eai.common.routing; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.jms.Connection; +import javax.jms.Session; +import org.apache.activemq.ActiveMQConnectionFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; + +import com.eactive.eai.common.util.Logger; + +public class TimerEventListenerConsumerService implements InitializingBean, DisposableBean { + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + // uri = "vm://localhost?broker.persistent=false&broker.useJmx=false" + // uri = "tcp://localhost:61617"" + private String uri; + private String queue; + private int maxThread; + + Connection connection = null; + Session[] sessions = null; + TimerEventListener[] consumers = null; + + ExecutorService es = null; + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + this.queue = queue; + } + + public int getMaxThread() { + return maxThread; + } + + public void setMaxThread(int maxThread) { + this.maxThread = maxThread; + } + + @Override + public void afterPropertiesSet() throws Exception { + startConsumer(); + } + + @Override + public void destroy() throws Exception { + stopConsumer(); + } + + public void startConsumer() { + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri); + connectionFactory.setTrustAllPackages(true); + + es = Executors.newFixedThreadPool(maxThread); + + connection = connectionFactory.createConnection(); + connection.start(); + + consumers = new TimerEventListener[maxThread]; + + for(int i=0; i EMPTY MESSAGE..."); + return; + } + + if(message instanceof ObjectMessage) { + omsg = (ObjectMessage)message; + } else { + throw new RuntimeException(name+" Invlid JMS Message Type. - "+message); + } + + try { + batchDoc = (BatchDoc)omsg.getObject(); + } catch(Exception e) { + throw new RuntimeException(name+" Invlid value object in ObjectMessage. - "+e.getMessage() ); + } + + //LayerCode, SubLayerCode 설정 + EAIBatchMsgManager.updateBatchMsg(batchDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER); + batchDoc.getBatchMsg().getBody().setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis()); + + try { + if ( batchDoc.getBatchMsg().getHeader().getRuleCode().startsWith("FTP") ){ + OutboundFTPHandle handle = new OutboundFTPHandle(); + handle.proc(batchDoc); + }else{ + OutboundSocketHandle handle = new OutboundSocketHandle(); + handle.proc(batchDoc); + } + } catch (Exception ex) { + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJH007"); + logger.error(errMsg, ex); + + // DB로그 처리 + new JobFinishHandler(batchDoc).handleErrorEnd(errMsg); + + } catch (Exception e2) { + logger.error("★★★★★ JobHandler JPD 예외 처리 중 에러 !! ★★★★★", e2); + } + } + } + catch(IllegalStateException ise) { + logger.error(name+" IllegalStateException = " + ise.getMessage(), ise); + + } + catch(JMSException e) { + logger.error(name+" JMSException = " + e.getMessage(), e); + run = false; + } + catch(RuntimeException e) { + logger.error(name+" RuntimeException = " + e.getMessage(), e); + } + + } + +} diff --git a/src/com/eactive/eai/common/routing/jms/JobPolingHandlerQueueConsumerService.java b/src/com/eactive/eai/common/routing/jms/JobPolingHandlerQueueConsumerService.java new file mode 100644 index 0000000..8c2ed4a --- /dev/null +++ b/src/com/eactive/eai/common/routing/jms/JobPolingHandlerQueueConsumerService.java @@ -0,0 +1,133 @@ +package com.eactive.eai.common.routing.jms; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.jms.Connection; +import javax.jms.QueueConnectionFactory; +import javax.jms.Session; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; + +import com.eactive.eai.common.dao.Keys; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.ServiceLocator; + +public class JobPolingHandlerQueueConsumerService implements InitializingBean, DisposableBean { + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + // uri = "vm://localhost?broker.persistent=false&broker.useJmx=false" + // uri = "tcp://localhost:61617"" + private String uri; + private String queue; + private int maxThread; + + String serverName = System.getProperty(Keys.SERVER_KEY); + + Connection connection = null; + Session[] sessions = null; + AbstractQueueConsumer[] consumers = null; + + ExecutorService es = null; + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + if("fepBapSvr11".equals(serverName)) { + uri = uri.replace("21", "11"); + }else { + uri = uri.replace("11", "21"); + } + this.uri = uri; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + if("fepBapSvr11".equals(serverName)) { + queue = queue.replace("21", "11"); + }else { + queue = queue.replace("11", "21"); + } + this.queue = queue; + } + + public int getMaxThread() { + return maxThread; + } + + public void setMaxThread(int maxThread) { + this.maxThread = maxThread; + } + + @Override + public void afterPropertiesSet() throws Exception { + startConsumer(); + } + + @Override + public void destroy() throws Exception { + stopConsumer(); + } + + public void startConsumer() { + try { + es = Executors.newFixedThreadPool(maxThread); + + ServiceLocator locator = ServiceLocator.getInstance(); + + QueueConnectionFactory connectionFactory = locator.getQueueConnectionFactory(uri); + connection = connectionFactory.createQueueConnection(); + + consumers = new AbstractQueueConsumer[maxThread]; + + for(int i=0; i EMPTY MESSAGE..."); + return; + } + + if (message instanceof ObjectMessage) { + omsg = (ObjectMessage) message; + } else { + throw new RuntimeException(name + " Invlid JMS Message Type. - " + message); + } + + try { + messageStr = (String) omsg.getObject(); + } catch (Exception e) { + throw new RuntimeException(name + " Invlid value object in ObjectMessage. - " + e.getMessage()); + } + + try { + if (messageStr.equals(PROC_JOB)) { + ScheduleHandlerProcess process = new ScheduleHandlerProcess(); + process.clientRequest(); + } else if (messageStr.equals(REG_JOB)) { + ScheduleRecvProcess process = new ScheduleRecvProcess(); + process.clientRequest(); + } else { + logger.error(this.getClass().getName() + "[Message]:" + message); + } + } catch (Exception e) { + logger.error("프로세스 수행 중 에러 발생. [" + message + "]- " + e.getMessage()); + } + + } catch (IllegalStateException ise) { + logger.error(name + " IllegalStateException = " + ise.getMessage(), ise); + + } catch (JMSException e) { + logger.error(name + " JMSException = " + e.getMessage(), e); + run = false; + } catch (RuntimeException e) { + logger.error(name + " RuntimeException = " + e.getMessage(), e); + } + } + + +} diff --git a/src/com/eactive/eai/common/routing/jms/TimerEventListenerQueueConsumerService.java b/src/com/eactive/eai/common/routing/jms/TimerEventListenerQueueConsumerService.java new file mode 100644 index 0000000..6a2b140 --- /dev/null +++ b/src/com/eactive/eai/common/routing/jms/TimerEventListenerQueueConsumerService.java @@ -0,0 +1,133 @@ +package com.eactive.eai.common.routing.jms; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.jms.Connection; +import javax.jms.QueueConnectionFactory; +import javax.jms.Session; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; + +import com.eactive.eai.common.dao.Keys; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.ServiceLocator; + +public class TimerEventListenerQueueConsumerService implements InitializingBean, DisposableBean { + private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + // uri = "vm://localhost?broker.persistent=false&broker.useJmx=false" + // uri = "tcp://localhost:61617"" + private String uri; + private String queue; + private int maxThread; + + String serverName = System.getProperty(Keys.SERVER_KEY); + + Connection connection = null; + Session[] sessions = null; + AbstractQueueConsumer[] consumers = null; + + ExecutorService es = null; + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + if("fepBapSvr11".equals(serverName)) { + uri = uri.replace("21", "11"); + }else { + uri = uri.replace("11", "21"); + } + this.uri = uri; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + if("fepBapSvr11".equals(serverName)) { + queue = queue.replace("21", "11"); + }else { + queue = queue.replace("11", "21"); + } + this.queue = queue; + } + + public int getMaxThread() { + return maxThread; + } + + public void setMaxThread(int maxThread) { + this.maxThread = maxThread; + } + + @Override + public void afterPropertiesSet() throws Exception { + startConsumer(); + } + + @Override + public void destroy() throws Exception { + stopConsumer(); + } + + public void startConsumer() { + try { + es = Executors.newFixedThreadPool(maxThread); + + ServiceLocator locator = ServiceLocator.getInstance(); + + QueueConnectionFactory connectionFactory = locator.getQueueConnectionFactory(uri); + connection = connectionFactory.createQueueConnection(); + + consumers = new AbstractQueueConsumer[maxThread]; + + for(int i=0; i keys = quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(this.schedulerId)); + Iterator iter = keys.iterator(); + while (iter.hasNext()) { + JobKey key = iter.next(); + logger.warn(key + " deleted"); + quartzScheduler.deleteJob(key); + } + } + catch (SchedulerException se) { + logger.error( se.getMessage(), se); + } + } + + public static Scheduler create(String schedulerId) throws Exception { + + Scheduler scheduler = new Scheduler(); + + SchedulerFactory sf = new StdSchedulerFactory(); + org.quartz.Scheduler sch = sf.getScheduler(); + scheduler.setSchedulerId(schedulerId); + scheduler.setQuartzScheduler(sch); + scheduler.setStatus(SchedulerKeys.STATUS_CREATED); + return scheduler; + } + + public void start() { + + if(SchedulerKeys.STATUS_STOPPED.equals(this.status) + || SchedulerKeys.STATUS_CREATED.equals(this.status)) { + this.status = SchedulerKeys.STATUS_STARTING; + try { + this.quartzScheduler.start(); + } + catch(Exception ex) { + logger.error( ex.getMessage(), ex); + status = SchedulerKeys.STATUS_FAIL; + } + status = SchedulerKeys.STATUS_RUNNING; + } + else { + logger.warn("skip start : " + schedulerId + " status [" + this.status + "]"); + } + } + + public void stop() { + + if(SchedulerKeys.STATUS_RUNNING.equals(this.status)) { + this.status = SchedulerKeys.STATUS_STOPPING; + try { + this.quartzScheduler.shutdown(); + } + catch(Exception ex) { + logger.error( ex.getMessage(), ex); + status = SchedulerKeys.STATUS_FAIL; + } + this.status = SchedulerKeys.STATUS_STOPPED; + + } + else { + logger.warn("skip stop : " + schedulerId + " status [" + this.status + "]"); + } + } + + public void scheduleAllJobs() { + try { + + DAOFactory factory = DAOFactory.newInstance(); + + SchedulerDAO dao = (SchedulerDAO) factory.create(SchedulerDAO.class); + + HashMap map = dao.getAllSchedule(); + Iterator it = map.keySet().iterator(); + String key = ""; + ScheduleJobInfo info = null; + + while(it.hasNext()) { + key = it.next(); + info = map.get(key); + logger.info("Schedule this job :" + info); + scheduleJob( info ); + + } + } + catch(Exception ex) { + logger.error( ex.getMessage(), ex); + } + } + + public void scheduleJob( ScheduleJobInfo info ) throws Exception { + + String jobNm = info.getSchedulerId(); + // delete previous Job + deleteJob(jobNm); + + @SuppressWarnings("rawtypes") + Class jobClass = Class.forName(info.getJobClass()); + + @SuppressWarnings("unchecked") + JobDetail job = newJob(jobClass) + .withIdentity(jobNm, schedulerId) + .usingJobData("TYPE", info.getSchedDstcd()) + .usingJobData("DIR", info.getScanDirName()) + .usingJobData("MSG", info.getTimerMsg() ) + .build(); + + CronTrigger trigger = newTrigger() + .withIdentity(getTriggerName(jobNm), schedulerId) + .withSchedule(cronSchedule(info.getCronExp())) + .build(); + + Date ft = this.quartzScheduler.scheduleJob(job, trigger); + logger.warn(job.getKey() + " has been scheduled to run at: " + ft + + " and repeat based on expression: " + + trigger.getCronExpression()); + } + + public void deleteJob(String jobNm) { + try { + JobKey key = new JobKey(jobNm, schedulerId); + this.quartzScheduler.deleteJob(key); + } + catch(Exception ex) { + logger.error( ex.getMessage(), ex); + } + } + + public void triggerJob(String jobNm) { + try { + JobKey key = new JobKey(jobNm, schedulerId); + this.quartzScheduler.triggerJob(key); + } + catch(Exception ex) { + logger.error( ex.getMessage(), ex); + } + } + + public void pauseJob(String jobNm) { + try { + TriggerKey tkey = new TriggerKey(getTriggerName(jobNm), schedulerId); + this.quartzScheduler.pauseTrigger(tkey); + + JobKey key = new JobKey(jobNm, schedulerId); + this.quartzScheduler.pauseJob(key); + } + catch(Exception ex) { + logger.error( ex.getMessage(), ex); + } + } + + public void resumeJob(String jobNm) { + try { + + TriggerKey tkey = new TriggerKey(getTriggerName(jobNm), schedulerId); + this.quartzScheduler.resumeTrigger(tkey); + + JobKey key = new JobKey(jobNm, schedulerId); + this.quartzScheduler.resumeJob(key); + } + catch(Exception ex) { + logger.error( ex.getMessage(), ex); + } + } + + private String getTriggerName(String jobName) { + return jobName + "-trigger"; + } + + @Override + public String toString() { + return "Scheduler [schedulerId=" + schedulerId + ", status=" + status + + ", quartzScheduler=" + quartzScheduler + "]"; + } + +} diff --git a/src/com/eactive/eai/common/scheduler/SchedulerDAO.java b/src/com/eactive/eai/common/scheduler/SchedulerDAO.java new file mode 100644 index 0000000..57dd086 --- /dev/null +++ b/src/com/eactive/eai/common/scheduler/SchedulerDAO.java @@ -0,0 +1,48 @@ +package com.eactive.eai.common.scheduler; + +import java.sql.ResultSet; +import java.util.HashMap; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.util.Logger; + + +public class SchedulerDAO extends BaseDAO implements SchedulerQuery { + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public HashMap getAllSchedule() throws DAOException { + + HashMap infos = new HashMap(); + ResultSet rs = null; + try { + + this.connect(SELECT_SCHEDULE); + + rs = executeQuery(); + logger.debug("[ @@ Load ScheduleJobInfo Configuration - starting >>>>>>>>>>>>>>>>> ]"); + + ScheduleJobInfo info = null; + while(rs.next()) { + info = new ScheduleJobInfo( + rs.getString(1), + rs.getString(2), + rs.getString(3), + rs.getString(4), + rs.getString(5), + rs.getString(6) + ); + infos.put(rs.getString(1), info); + if(info!=null) logger.debug("@ "+info.toString()); + } + + logger.debug("[>>Load ScheduleJobInfo Configuration - ended ]"); + return infos; + } catch(Exception e) { + logger.error("SchedulerDAO Fail - " + e.getMessage(),e); + throw new DAOException(); + } finally { + this.disconnect(); + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/scheduler/SchedulerInitializer.java b/src/com/eactive/eai/common/scheduler/SchedulerInitializer.java new file mode 100644 index 0000000..1f109e2 --- /dev/null +++ b/src/com/eactive/eai/common/scheduler/SchedulerInitializer.java @@ -0,0 +1,27 @@ +package com.eactive.eai.common.scheduler; + +public class SchedulerInitializer { + //private static boolean isStarted = false; + +// public void init(String schedulerId) throws Exception { +// +// SchedulerManager scheduleManager = SchedulerManager.getInstance(); +// +// scheduleManager.create(schedulerId); +// +// scheduleManager.scheduleAllJobs(schedulerId); +// scheduleManager.start(schedulerId); +// //isStarted = true; +// } +// +// public static void main(String[] args) { +// SchedulerInitializer initializer = new SchedulerInitializer(); +// +// try { +// String schedulerId = SchedulerKeys.DEFAULT_SCHEDULER_ID; +// initializer.init(schedulerId); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +} diff --git a/src/com/eactive/eai/common/scheduler/SchedulerKeys.java b/src/com/eactive/eai/common/scheduler/SchedulerKeys.java new file mode 100644 index 0000000..9faa254 --- /dev/null +++ b/src/com/eactive/eai/common/scheduler/SchedulerKeys.java @@ -0,0 +1,15 @@ +package com.eactive.eai.common.scheduler; + +public interface SchedulerKeys { + // Cache Name List + public static final String STATUS_CREATED = "CREATED" ; + public static final String STATUS_STARTING = "STARTING"; + public static final String STATUS_RUNNING = "RUNNING" ; + public static final String STATUS_STOPPING = "STOPPING"; + public static final String STATUS_STOPPED = "STOPPED" ; + public static final String STATUS_FAIL = "FAIL" ; + + public static final String DEFAULT_SCHEDULER_ID = "EAI_BATCH_EVENT"; + + public static final String INTERNAL_SCHEDULER_ID = "EAI_INTERNAL_JOB"; +} diff --git a/src/com/eactive/eai/common/scheduler/SchedulerManager.java b/src/com/eactive/eai/common/scheduler/SchedulerManager.java new file mode 100644 index 0000000..c481053 --- /dev/null +++ b/src/com/eactive/eai/common/scheduler/SchedulerManager.java @@ -0,0 +1,185 @@ +package com.eactive.eai.common.scheduler; + +import java.util.HashMap; +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.Logger; + +public class SchedulerManager implements Lifecycle{ + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + private static SchedulerManager myInstance = new SchedulerManager(); + private LifecycleSupport lifecycle = new LifecycleSupport(this); + private boolean started; + + + private HashMap schedulers = new HashMap(); + + public static SchedulerManager getInstance() { + if(myInstance == null) { + myInstance = new SchedulerManager(); + } + return myInstance; + } + + public void create(String schedulerId) throws Exception { + Scheduler scheduler = Scheduler.create(schedulerId); + schedulers.put(schedulerId, scheduler); + } + + public void start(String schedulerId) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + scheduler.start(); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void stop(String schedulerId) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + scheduler.stop(); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public Scheduler getScheduler(String schedulerId) { + Scheduler scheduler = schedulers.get(schedulerId); + return scheduler; + } + + public void scheduleAllJobs(String schedulerId) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + scheduler.scheduleAllJobs(); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void deleteAllJobs(String schedulerId) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + scheduler.clear(); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void scheduleJob(String schedulerId, ScheduleJobInfo info) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + try { + scheduler.scheduleJob(info); + } + catch(Exception ex) { + logger.warn("Scheduler Error["+schedulerId+"] " + ex.toString()); + } + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void deleteJob(String schedulerId, String jobNm) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + logger.warn("Scheduler.deleteJob - " + jobNm); + scheduler.deleteJob(jobNm); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void triggerJob(String schedulerId, String jobNm) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + scheduler.triggerJob(jobNm); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void pauseJob(String schedulerId, String jobNm) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + scheduler.pauseJob(jobNm); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void resumeJob(String schedulerId, String jobNm) { + Scheduler scheduler = this.getScheduler(schedulerId); + if(scheduler != null) { + scheduler.resumeJob(jobNm); + } + else { + logger.warn("Scheduler is null - ");// 20250910 npe +scheduler 삭제 + } + } + + public void addLifecycleListener(LifecycleListener listener) { + lifecycle.addLifecycleListener(listener); + } + + public LifecycleListener[] findLifecycleListeners() { + return lifecycle.findLifecycleListeners(); + } + + public void removeLifecycleListener(LifecycleListener listener) { + lifecycle.removeLifecycleListener(listener); + } + + public void start() throws LifecycleException { + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + String schedulerId = SchedulerKeys.DEFAULT_SCHEDULER_ID; + SchedulerManager scheduleManager = SchedulerManager.getInstance(); + try { + scheduleManager.create(schedulerId); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + scheduleManager.scheduleAllJobs(schedulerId); + this.start(schedulerId); + + started = true; + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + + } + + public void stop() throws LifecycleException { + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + String schedulerId = SchedulerKeys.DEFAULT_SCHEDULER_ID; + this.stop(schedulerId); + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + + } + + public boolean isStarted() { + return this.started; + } + + +} diff --git a/src/com/eactive/eai/common/scheduler/SchedulerQuery.java b/src/com/eactive/eai/common/scheduler/SchedulerQuery.java new file mode 100644 index 0000000..47df088 --- /dev/null +++ b/src/com/eactive/eai/common/scheduler/SchedulerQuery.java @@ -0,0 +1,15 @@ +package com.eactive.eai.common.scheduler; + +import com.eactive.eai.common.dao.Keys; + +public interface SchedulerQuery { + public static final String SELECT_SCHEDULE = + "SELECT " + + " SchedID , " + + " CronExp , " + + " JobClassName , " + + " SchedDstcd , " + + " ScanDirName , " + + " TimerMsg " + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS06" ; +} diff --git a/src/com/eactive/eai/common/scheduler/TimerEventJob.java b/src/com/eactive/eai/common/scheduler/TimerEventJob.java new file mode 100644 index 0000000..e191267 --- /dev/null +++ b/src/com/eactive/eai/common/scheduler/TimerEventJob.java @@ -0,0 +1,37 @@ +package com.eactive.eai.common.scheduler; + +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.JobKey; + +import com.eactive.eai.common.dao.Keys; +import com.eactive.eai.common.util.JMSSender; +import com.eactive.eai.common.util.Logger; + +public class TimerEventJob implements Job { + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public void execute(JobExecutionContext context) throws JobExecutionException { + JobKey jobKey = context.getJobDetail().getKey(); + String msg = context.getJobDetail().getJobDataMap().getString("MSG"); + + try { + String instName = System.getProperty(Keys.SERVER_KEY); + String timerQueue = instName.equals("fepBapSvr11") ? Keys.BAP01_TIMER_QUEUE : Keys.BAP02_TIMER_QUEUE; + //sender.send(Keys.CONNECT_FACTORY, Keys.TIMER_QUEUE, msg, jobKey.getName()); + JMSSender.sendToQueue(msg, Keys.CONNECT_FACTORY, timerQueue); + } catch (Exception e) { + logger.error( e.getMessage(), e); + } + } + public void setDIR( String dir){ + return; + } + public void setMSG( String msg){ + return; + } + public void setTYPE( String type){ + return; + } +} diff --git a/src/com/eactive/eai/common/secure/inisafe/IniSafeManager.java b/src/com/eactive/eai/common/secure/inisafe/IniSafeManager.java new file mode 100644 index 0000000..d906fd7 --- /dev/null +++ b/src/com/eactive/eai/common/secure/inisafe/IniSafeManager.java @@ -0,0 +1,177 @@ +package com.eactive.eai.common.secure.inisafe; + +import java.util.HashMap; + +import com.eactive.eai.adapter.socket.common.CommonLib; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.Logger; +import com.initech.inisafenet.HandShakeManager; +import com.initech.inisafenet.exception.INISAFENetException; + +public class IniSafeManager { + + static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + private static IniSafeManager myInstance = new IniSafeManager(); + private HashMap map = new HashMap(); + + private static final String PROP_GROUP = "IniSafeManager"; + private static final String PROP_KEY1 = "INISAFENET_PROPERTIES"; + + private static final String INISAFENET_PROPERTIES = "D:/initech/inisafe/properties/INISAFENet.properties"; + + public static IniSafeManager getInstance() { + if(myInstance == null) { + myInstance = new IniSafeManager(); + } + return myInstance; + } + + public byte[] initHandShakeClient( BatchDoc batchDoc ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + hsm = new HandShakeManager( getProp()); + map.put(uuid, hsm); + } + return hsm.initHandShakeClient(null); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + public byte[] initHandShake( BatchDoc batchDoc ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + logger.debug("[initHandShake]getSendBuffer-->" + CommonLib.getDumpMessage(batchDoc.getBatchMsg().getBody().getSendBuffer())); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + hsm = new HandShakeManager( getProp()); + map.put(uuid, hsm); + } + return hsm.initHandShake(batchDoc.getBatchMsg().getBody().getSendBuffer()); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + public byte[] updateHandShakeClient( BatchDoc batchDoc ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + logger.debug("[updateHandShakeClient]getSendBuffer-->" + CommonLib.getDumpMessage(batchDoc.getBatchMsg().getBody().getSendBuffer())); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + hsm = new HandShakeManager( getProp()); + map.put(uuid, hsm); + } + return hsm.updateHandShakeClient(batchDoc.getBatchMsg().getBody().getSendBuffer()); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + public byte[] updateHandShake( BatchDoc batchDoc ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + logger.debug("[updateHandShake]getSendBuffer-->" + CommonLib.getDumpMessage(batchDoc.getBatchMsg().getBody().getSendBuffer())); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + hsm = new HandShakeManager( getProp()); + map.put(uuid, hsm); + } + return hsm.updateHandShake(batchDoc.getBatchMsg().getBody().getSendBuffer()); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + public byte[] finalHandShakeClient( BatchDoc batchDoc ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + logger.debug("[finalHandShakeClient]getSendBuffer-->" + CommonLib.getDumpMessage(batchDoc.getBatchMsg().getBody().getSendBuffer())); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + hsm = new HandShakeManager( getProp()); + map.put(uuid, hsm); + } + return hsm.finalHandShakeClient(batchDoc.getBatchMsg().getBody().getSendBuffer()); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + public int finalHandShake( BatchDoc batchDoc, byte[] finalPhase ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + logger.debug("[finalHandShake]getSendBuffer-->" + CommonLib.getDumpMessage(batchDoc.getBatchMsg().getBody().getSendBuffer())); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + hsm = new HandShakeManager( getProp()); + map.put(uuid, hsm); + } + return hsm.finalHandShake(finalPhase); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return -1; + } + + public void removeManager( BatchDoc batchDoc){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + map.remove(uuid); + return; + } + + public byte[] enc( BatchDoc batchDoc, byte[]data ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + return data; + } + return hsm.i_encrypt(data); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + public byte[] dec( BatchDoc batchDoc, byte[]data ){ + String uuid = batchDoc.getBatchMsg().getHeader().getUUID(); + try { + HandShakeManager hsm = map.get(uuid); + if ( hsm == null ){ + logger.debug("getProp()-->" + getProp()); + return data; + } + return hsm.i_decrypt(data); + } catch (INISAFENetException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + private String getProp(){ + String prop = null; + try{ + prop = PropManager.getInstance().getProperty(PROP_GROUP,PROP_KEY1); + }catch ( Exception e ){} + if ( prop != null ) + return prop; + return INISAFENET_PROPERTIES; + } + +} diff --git a/src/com/eactive/eai/common/server/EAIServerDAO.java b/src/com/eactive/eai/common/server/EAIServerDAO.java new file mode 100644 index 0000000..9ba5e4b --- /dev/null +++ b/src/com/eactive/eai/common/server/EAIServerDAO.java @@ -0,0 +1,278 @@ +package com.eactive.eai.common.server; + +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; + +/** +* 1. 기능 : EAI서버 정보 테이블에 대한 Data Access Object 이다. +* 2. 처리 개요 : EAI서버 정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다. +* +* 3. 주의사항 +*/ +public class EAIServerDAO extends BaseDAO implements EAIServerQuery +{ + + /** + * 1. 기능 : EAI서버 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서 + * EAIBatServerVO 객체 리스트로 생성 반환하는 메서드. + * 2. 처리 개요 : EAI서버 정보 전체를 SELECT해서 한 레코드를 EAIBatServerVO로 생성 List에 + * 저장하여 반환한다. + * 3. 주의사항 + * + * @return List EAI서버 정보 전체데이터로 EAIBatServerVO Collection + * @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 EAI서버 정보를 가져오다 발생되는 모든 에러[RECEAICSM101] + **/ + public HashMap getAllServers() throws DAOException { + HashMap all = new HashMap(); + ResultSet rs = null; + try { + this.connect(GET_ALL_SERVERS); + rs = executeQuery(); + EAIServerVO vo = null; + while(rs.next()) { + vo = new EAIServerVO(rs.getString(1)); + vo.setAddress(rs.getString(2)); + vo.setPort(rs.getString(3)); + vo.setFailoverSvr(rs.getString(4)); + vo.setHostName(rs.getString(5)); + all.put(vo.getName(), vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV001")); + } finally { + this.disconnect(); + } + return all; + } + + /** + *
+     * 1. 기능 : EAI서버정보 리스트를 조회 
+     * 2. 처리 개요 : 
+     *     - 
+     * 3. 주의사항 : 
+     * 
+ * @author : + * @since : rts 1.0 + * @return + * @throws DAOException + */ + public ArrayList getAllServerList() throws DAOException { + ArrayList arr = new ArrayList(); + ResultSet rs = null; + try { + this.connect(GET_ALL_SERVERS); + rs = executeQuery(); + EAIServerVO vo = null; + while(rs.next()) { + vo = new EAIServerVO(rs.getString(1)); + vo.setAddress(rs.getString(2)); + vo.setPort(rs.getString(3)); + vo.setFailoverSvr(rs.getString(4)); + vo.setHostName(rs.getString(5)); + arr.add(vo); + } + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV002")); + } finally { + this.disconnect(); + } + return arr; + } + + /** + * 1. 기능 : 관리 기능을 위해 EAI서버정보 리스트를 가져오는 메서드 + * 2. 처리 개요 : 특정 page에 대한 리스트 정보를 조회와 전체 레코드 수를 HashMap에 저장 반환한다. + * - Total Count를 SELECT 해서 HashMap에 "TOTCNT"로 저장한다. + * - 파라미터의 PageInfo에 저장된 page에 해당하는 추출정보리스트를 ArrayList로 만들어 HashMap에 + * "LIST"로 저장한다. + * 3. 주의사항 + * + * @param page 리스트 보기 기능에서 사용하는 페이지수, 검색 항목을 저장하기 위한 Value object + * @return TotalCount와 페이지 리스트 정보를 저장하고 있는 HashMap + * @exception DAOException DB SELECT 관련 SQLException을 포함한 페이지 리스트를 생성하다 발생하는 모든 에러 + **/ + + /* + public HashMap getServerPageList(PageInfo page,String likeKey) throws DAOException { + ResultSet rs = null; + try { + this.connect(SELECT_SERVER_TOTALCOUNT); + this.preparedStatement.setString(1, "%"+likeKey+"%"); + rs = this.executeQuery(); + rs.next(); + int totalCount = rs.getInt(1); + rs.close(); + + this.prepareStatement(SELECT_SERVER_PAGELIST); + this.preparedStatement.setString(1, "%"+likeKey+"%"); + this.preparedStatement.setInt(2, page.startrow()); + this.preparedStatement.setInt(3, page.endrow()); + rs = this.executeQuery(); + + ArrayList al = new ArrayList(); + EAIServerVO vo = null; + while(rs.next()) { + vo = new EAIServerVO(); + vo.setName(rs.getString(2)); + vo.setAddress(rs.getString(3)); + vo.setPort(rs.getString(4)); + vo.setFailoverSvr(rs.getString(5)); + vo.setHostName(rs.getString(6)); + al.add(vo); + } + + HashMap map = new HashMap(); + map.put("TOTCNT", new Integer(totalCount)); + map.put("LIST", al); + return (map); + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV003")); + + } finally { + this.disconnect(); + } + } + */ + + /** + * 1. 기능 : EAI서버 Rule 정보를 등록하는 메서드 + * 2. 처리 개요 : 파라미터의 EAI서버 Rule 정보를 DB 테이블에 INSERT한다. + * 3. 주의사항 + * + * @param EAIBatServerVO + * @exception DAOException DB INSERT 시 발생하는 SQLException을 포함한 EAI서버 저장시 발생되는 모든 에러 + **/ + public void addServer(EAIServerVO vo) throws DAOException { + try { + this.connect(ADD_SERVER); + this.preparedStatement.setString(1,vo.getName()); + this.preparedStatement.setString(2,vo.getAddress()); + this.preparedStatement.setString(3,vo.getPort()); + this.preparedStatement.setString(4,vo.getFailoverSvr()); + this.preparedStatement.setString(5,vo.getHostName()); + executeUpdate(); + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV004")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : 특정 EAI서버 Rule 상세 정보를 가져오는 메서드 + * 2. 처리 개요 : 파라미터의 bwkClsCd에 따른 EAI서버 상세정보를 + * 조회하여 EAIBatServerVO 객체를 생성 반환 + * 3. 주의사항 + * + * @param name EAI서버명 + * @return EAI서버 Rule 정보를 표현한 EAIBatServerVO 객체 반환 + * @exception DAOException DB SELECT 시 발생하는 SQLException을 포함한 EAI서버 Rule 상세정보 생성 시 발생하는 모든 에러(RECEAICBM205) + **/ + public EAIServerVO getServer(String name) throws DAOException { + try { + ResultSet rs = null; + EAIServerVO svr = new EAIServerVO(name); + this.connect(GET_SERVER); + this.preparedStatement.setString(1, name); + rs = executeQuery(); + if(!rs.next()) throw new DAOException("RECEAICSM104"); + svr.setAddress(rs.getString(1)); + svr.setPort(rs.getString(2)); + svr.setFailoverSvr(rs.getString(3)); + svr.setHostName(rs.getString(4)); + + return svr; + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV005")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : EAI서버 Rule 정보를 변경하는 메서드 + * 2. 처리 개요 : 파라미터의 해당하는 EAI서버 Rule 정보의 상세 정보를 변경한다. + * 3. 주의사항 + * + * @param EAIBatServerVO EAIBatServerVO + * @exception DAOException DB UPDATE 시 발생하는 SQLException을 포함한 EAI서버 정보 변경시 발생되는 모든 에러 + **/ + public void updateServer(EAIServerVO vo) throws DAOException { + try { + + this.connect(UPDATE_SERVER); + this.preparedStatement.setString(1,vo.getAddress()); + this.preparedStatement.setString(2,vo.getPort()); + this.preparedStatement.setString(3,vo.getFailoverSvr()); + this.preparedStatement.setString(4,vo.getHostName()); + this.preparedStatement.setString(5,vo.getName()); + + int result = executeUpdate(); + if(result!=1) throw new Exception("update fail"); + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV006")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : EAI서버 정보 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 EAI서버 Rule 정보를 DB 테이블에서 삭제한다. + * 3. 주의사항 + * + * @param bwkClsCd EAI서버코드 + * @exception DAOException DB DELETE 시 발생하는 SQLException을 포함한 추출정보 삭제시 발생되는 모든 에러 + **/ + public void removeServer(String name) throws DAOException { + try { + this.connect(REMOVE_SERVER); + this.preparedStatement.setString(1,name); + executeUpdate(); + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV007")); + } finally { + this.disconnect(); + } + } + + /** + * 1. 기능 : EAI서버 Rule 정보에서 EAI서버명 리스트를 조회 + * 2. 처리 개요 : EAI서버 Rule 정보에서 EAI서버명 리스트를 조회한다. + * 3. 주의사항 + * + * @return Vector EAI서버명 리스트 + * @exception DAOException DB DELETE 시 발생하는 SQLException을 포함한 추출정보 삭제시 발생되는 모든 에러 + **/ + + /* + public Vector getServerNm() throws DAOException { + Vector all = new Vector(); + ResultSet rs = null; + try { + this.connect(GET_SERVERS_NAME); + rs = executeQuery(); + EAIServerVO vo = null; + + while(rs.next()) { + vo = new EAIServerVO(); + vo.setName(rs.getString(1)); + all.addElement(vo); + } + + } catch(Exception e) { + throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIUSV008")); + } finally { + this.disconnect(); + } + + return all; + } + */ +} diff --git a/src/com/eactive/eai/common/server/EAIServerManager.java b/src/com/eactive/eai/common/server/EAIServerManager.java new file mode 100644 index 0000000..9d544cf --- /dev/null +++ b/src/com/eactive/eai/common/server/EAIServerManager.java @@ -0,0 +1,331 @@ +package com.eactive.eai.common.server; + +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.dao.DAOFactory; +import com.eactive.eai.common.exception.ExceptionUtil; +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 java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; + +/** +* 1. 기능 : EAI서버 Rule 정보를 DB로 부터 로딩해 메모리에 관리하는 Manager 클래스 +* 2. 처리 개요 : DB Rule 정보에 저장된 필드 추출 Rule 정보를 메모리에 로딩 관리한다. +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : 관련 기능을 참조 +* @since : +*/ +public class EAIServerManager implements Lifecycle +{ + /** + * EAIServerManager Single Instance + */ + private static EAIServerManager instance = new EAIServerManager(); + + /** + * LifeccyleSupport object + */ + private LifecycleSupport lifecycle = new LifecycleSupport(this); + + /** + * 기동 여부 + */ + private boolean started; + + /** + * EAIServer Rule 정보를 저장하는 collection + */ + private HashMap servers; + + /** + * 1. 기능 : Default Constructor + * 2. 처리 개요 : EAIServer Rule 정보를 저장하기 위한 HashMap을 초기화한다. + * 3. 주의사항 + * + **/ + private EAIServerManager() { + servers = new HashMap(); + + } + + /** + * 1. 기능 : EAIServerManager Singleton Object를 반환하는 getter method + * 2. 처리 개요 : EAIServerManager Singleton Object를 반환한다. + * 3. 주의사항 + * + * @return EAIServerManager Singleton object + **/ + public static EAIServerManager getInstance() { + + return instance; + } + + + public String getLocalServerName() { + String svrName = System.getProperty(Keys.WLI_SERVER_KEY); + return svrName; + } + + /** + * 1. 기능 : Manager가 동작하고 있는 서버의 HostName을 얻어내는 메소드 + * 2. 처리 개요 : + * - InetAddress를 통해 조회 + * 3. 주의사항 + * + * @exception UnknownHostException + **/ + public String getLocalServerHostName() throws java.net.UnknownHostException{ + + String hostname = java.net.InetAddress.getLocalHost().getHostName(); + return hostname; + } + + public EAIServerVO getLocalServer() { + return null; + } + + /** + * 1. 기능 : Lifecycle의 start 메서드로 EAIServerMangaer를 초기화하는 메서드 + * 2. 처리 개요 : EAIServerDAO를 이용해 추출 Rule 정보 모두를 가져와 초기화한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 시작되었거나, EAIServerDAO를 통해 Rule 정보를 가져오다 DAOExcepiton이 발생될 경우 + * + **/ + public void start() throws LifecycleException { + if (started) + throw new LifecycleException("BECEAIMSV201"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTING_EVENT, this); + + DAOFactory daoFactory = DAOFactory.newInstance(); + EAIServerDAO dao = null; + try { + dao = (EAIServerDAO)daoFactory.create(EAIServerDAO.class); + this.servers = dao.getAllServers(); + } catch(DAOException e) { + throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMSV202")); + } + + started = true; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STARTED_EVENT, this); + } + + /** + * 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드 + * 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다. + * 3. 주의사항 + * + * @exception LifecycleException 이미 종료된 경우 발생 + **/ + public void stop() throws LifecycleException { + // Validate and update our current component state + if (!started) + throw new LifecycleException("BECEAIMSV203"); + + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPING_EVENT, this); + + + started = false; + // Notify our interested LifecycleListeners + lifecycle.fireLifecycleEvent(STOPPED_EVENT, this); + } + + /** + * 1. 기능 : LifecycleListener를 등록하는 메서드 + * 2. 처리 개요 : LifecycleListener를 등록한다. + * 3. 주의사항 + * + * @param listener LifecycleEvent를 수신한 LifecycleListener + **/ + public void addLifecycleListener(LifecycleListener listener) + { + lifecycle.addLifecycleListener(listener); + } + + /** + * 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드 + * 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다. + * 3. 주의사항 + * + * @return 등록된 LifecycleListener 리스트 + **/ + public LifecycleListener[] findLifecycleListeners() + { + return lifecycle.findLifecycleListeners(); + } + + /** + * 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드 + * 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다. + * 3. 주의사항 + * + * @param listener 삭제할 LifecycleListener + **/ + public void removeLifecycleListener(LifecycleListener listener) + { + lifecycle.removeLifecycleListener(listener); + } + + /** + * 1. 기능 : EAIServer Rule 정보를 찾아 반환하는 메서드 + * 2. 처리 개요 : 파리미터의 이름에 대한 EAIServer Rule 정보를 찾아 반환한다. + * 3. 주의사항 + * + * @param name EAIServer Rule 정보를 관리하는 key 값(EAIServer 명) + * @return EAIServer Rule 정보 + **/ + public EAIServerVO getEAIServer(String name) { + return (EAIServerVO)this.servers.get(name); + } + + /** + * 1. 기능 : EAIServerManager의 초기화 여부를 반환하는 getter 메서드 + * 2. 처리 개요 : EAIServerManager의 초기화 여부를 반환한다. + * 3. 주의사항 + * + * @return 초기화 여부 + **/ + public boolean isStarted() { + return this.started; + } + + /** + * 1. 기능 : EAIServer Rule 정보를 저장하는 메서드 + * 2. 처리 개요 : 파라미터의 EAIServer Rule 정보를 멤버에 저장한다. + * 3. 주의사항 + * + * @param vo EAIServerVO + **/ + public void addEAIServer(EAIServerVO vo) { + this.servers.put(vo.getName(),vo); + } + + /** + * 1. 기능 : EAIServer Rule 정보를 삭제하는 메서드 + * 2. 처리 개요 : + * - 파라미터의 EAIServer 명의 Rule 정보를 멤버에서 삭제한다. + * 3. 주의사항 + * + * @param name EAIServer명 + * @exception + **/ + public void removeEAIServer(String name) { + this.servers.remove(name); + } + + /** + * 1. 기능 : EAIServer Rule 정보를 수정하는 메서드 + * 2. 처리 개요 : + * - 파라미터의 EAIServerVO의 Rule 정보를 멤버에서 수정한다. + * 3. 주의사항 + * + * @param EAIServerVO + * @exception + **/ + public void setEAIServer(EAIServerVO vo) { + this.servers.put(vo.getName(),vo); + } + + /** + * 1. 기능 : Rule에 저장된 EAIServerVO 리스트를 얻어내는 메소드 + * 2. 처리 개요 : + * - Rule에 저장된 EAIServerVO 리스트를 얻어낸다. + * 3. 주의사항 + * + * @return HashMap Manager의 Rule에 저장된 EAIServerVO 리스트 + * @exception + **/ + public HashMap getAllServer(){ + return this.servers; + } + + /** + * 1. 기능 : Rule에 저장된 EAIServerVO의 EAIServer명 리스트를 얻어내는 메소드 + * 2. 처리 개요 : + * - Rule에 저장된 EAIServerVO의 EAIServer명 리스트를 얻어낸다. + * 3. 주의사항 + * + * @return String[] Manager의 Rule에 저장된 EAIServerVO의 EAIServer명 리스트 + * @exception + **/ + public String[] getAllEaiSvrInstNm(){ + Iterator it = this.servers.keySet().iterator(); + + String[] eaiIns = new String[this.servers.size()]; + for(int i = 0; it.hasNext(); i++){ + eaiIns[i] = it.next(); + } + Arrays.sort(eaiIns); + return eaiIns; + } + + /** + * 1. 기능 : 현 EAI 서버가 운영(Prod) 환경인지 여부를 반환하는 메서드 + * 2. 처리 개요 : + * - 현 EAI 서버가 운영(Prod) 환경인지 여부를 반환한다. + * 3. 주의사항 + * + * @return 현 EAI 서버가 운영(Prod) 환경인지 여부 + **/ + public boolean isPEAIServer() { + + String SysOperEvirnDstcd = System.getProperty(Keys.EAI_SYSTEMMODE); + if(SysOperEvirnDstcd ==null || SysOperEvirnDstcd.equals(Keys.EAI_PRODUCT)) { + return true; + } + else { + return false; + } + + } + + /** + * 1. 기능 : 현 EAI 서버가 개발(Dev) 환경인지 여부를 반환하는 메서드 + * 2. 처리 개요 : + * - 현 EAI 서버가 개발(Dev) 환경인지 여부를 반환한다. + * 3. 주의사항 + * + * @return 현 EAI 서버가 개발(Dev) 환경인지 여부 + **/ + public boolean isDEAIServer() { + String SysOperEvirnDstcd = System.getProperty(Keys.EAI_SYSTEMMODE); + if( SysOperEvirnDstcd.equals(Keys.EAI_DEVELOP)) { + return true; + } + else { + return false; + } + + } + + /** + * 1. 기능 : 현 EAI 서버가 테스트(Test) 환경인지 여부를 반환하는 메서드 + * 2. 처리 개요 : + * - 현 EAI 서버가 테스트(Test) 환경인지 여부를 반환한다. + * 3. 주의사항 + * + * @return 현 EAI 서버가 테스트(Test) 환경인지 여부 + **/ + public boolean isTEAIServer() { + String SysOperEvirnDstcd = System.getProperty(Keys.EAI_SYSTEMMODE); + if( SysOperEvirnDstcd.equals(Keys.EAI_TEST)) { + return true; + } + else { + return false; + } + + } +} + diff --git a/src/com/eactive/eai/common/server/EAIServerQuery.java b/src/com/eactive/eai/common/server/EAIServerQuery.java new file mode 100644 index 0000000..2e1df68 --- /dev/null +++ b/src/com/eactive/eai/common/server/EAIServerQuery.java @@ -0,0 +1,79 @@ +package com.eactive.eai.common.server; + +import com.eactive.eai.common.dao.Keys; + +/** +* 1. 기능 : EAIServerDAO에서 사용하는 SQL Query를 정의한 Interface +* 2. 처리 개요 : +* - EAIServerDAO에서 사용하는 SQL Query를 정의한 Interface +* 3. 주의사항 +* +* @author : 전홍성(hsjeon70@dreamwiz.com) +* @see : TestCallRunner, TestCallManager +* @since :JDK v1.4.2 +*/ +public interface EAIServerQuery +{ + + + /** + * EAIServer List를 조회하는 Query + */ + + public static final String GET_ALL_SERVERS = "select EAISevrInstncName, EAISevrIP, SevrLsnPortName, FlovrSevrName, HostName \n"+ + "from " + Keys.TABLE_OWNER + "TSEAIBP03 \n" + + "order by EAISevrInstncName"; + + /** + * EAIBatServer를 등록하는 Query + */ + public static final String ADD_SERVER = "insert into " + Keys.TABLE_OWNER + "TSEAIBP03 "+ + "(EAISevrInstncName, EAISevrIP, SevrLsnPortName, FlovrSevrName, HostName) "+ + "values(?, ?, ?, ?, ?, ?)"; + + /** + * 특정 EAIBatServer 정보를 조회하는 Query + */ + public static final String GET_SERVER = "select EAISevrIP, SevrLsnPortName, FlovrSevrName, HostName \n"+ + "from " + Keys.TABLE_OWNER + "TSEAIBP03 where EAISevrInstncName=?"; + + /** + * 특정 EAIBatServer 정보를 등록하는 Query + */ + + public static final String UPDATE_SERVER = "update " + Keys.TABLE_OWNER + "TSEAIBP03 \n"+ + "set EAISevrIP=?, SevrLsnPortName=?, FlovrSevrName=?, HostName=? \n"+ + "where EAISevrInstncName=?"; + + /** + * 특정 EAIBatServer 정보를 삭제하는 Query + */ + public static final String REMOVE_SERVER = "delete from " + Keys.TABLE_OWNER + "TSEAIBP03 \n"+ + "where EAISevrInstncName=?"; + + /** + * EAIBatServer리스트를 생성하기 위한 Query + */ + public static final String GET_SERVERS_NAME = "select EAISevrInstncName from " + Keys.TABLE_OWNER + "TSEAIBP03"; + + /** + * EAIBatServer 페이지 리스트를 생성하기 위한 Query + */ +// public static final String SELECT_SERVER_PAGELIST = +// "SELECT ROWNO, EAISevrInstncName, EAISevrIP, SevrLsnPortName, FlovrSevrName, HostName \n" +// +"FROM ( \n" +// +" SELECT \n" +// +" ROW_NUMBER() OVER (ORDER BY EAISevrInstncName) ROWNO, EAISevrInstncName, EAISevrIP, SevrLsnPortName, FlovrSevrName, HostName \n" +// +" FROM " + Keys.TABLE_OWNER + "TSEAIBP03 \n" +// +" WHERE EAISevrInstncName like ? \n" +// +" ORDER BY EAISevrInstncName \n" +// +") AS TMP1 WHERE ROWNO BETWEEN ? AND ?"; + + /** + * EAIBatServer 페이지 총 갯수를 산정하기 위한 Query + */ + public static final String SELECT_SERVER_TOTALCOUNT = "SELECT COUNT(*) FROM " + Keys.TABLE_OWNER + "TSEAIBP03 WHERE EAISevrInstncName like ? "; + +} + + diff --git a/src/com/eactive/eai/common/server/EAIServerVO.java b/src/com/eactive/eai/common/server/EAIServerVO.java new file mode 100644 index 0000000..19a95f7 --- /dev/null +++ b/src/com/eactive/eai/common/server/EAIServerVO.java @@ -0,0 +1,233 @@ +package com.eactive.eai.common.server; + +import java.io.Serializable; + +/** +* 1. 기능 : 운영하는 EAI 엔진 서버 정보를 표현하는 Java Value object +* 관련 테이블 - TSEAISY02 +* 2. 처리 개요 : +* - 운영하는 EAI엔전 서버 정보를 표현하는 Java Value object +* 3. 주의사항 +*/ +public class EAIServerVO implements Serializable +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + /** + * T3 PROTOCOL PREFIX + */ + public static final String T3_PROTOCOL = "t3"; + /** + * HTTP PROTOCOL PREFIX + */ + public static final String HTTP_PROTOCOL = "http"; + /** + * IIOP PROTOCOL PREFIX + */ + public static final String IIOP_PROTOCOL = "iiop"; + + /** + * EAI 서버 이름 + */ + private String name; // EAI서버인스탄스명[TSEAISY02.EAISevrInstncName] + /** + * EAI 서버 ip 주소 + */ + private String address; // EAI서버IP주소[TSEAISY02.EAISevrIP] + + + /** + * EAI 서버 리스 포트 + */ + private String port; //서버리슨포트명 + /** + * EAI 서버 장애 시 FAILOVER 서버 + */ + private String failoverSvr; //장애극복서버명 + + /** + * EAI 서버가 운영되는 하드웨어 호스트이름 + */ + private String hostNm; //호스트명 + + /** + * 1. 기능 : Defualt Constructor + * 2. 처리 개요 : + * - Defualt Constructor + * 3. 주의사항 + * + **/ + public EAIServerVO() { + } + + /** + * 1. 기능 : EAI 서버 이름을 저장하는 생성자 함수 + * 2. 처리 개요 : + * - EAI 서버 이름을 저장하는 생성자 함수 + * 3. 주의사항 + * + * @param name EAI 서버 이름 + **/ + public EAIServerVO(String name) { + this.name = name; + } + + /** + * 1. 기능 : EAI 서버 이름을 저장하는 setter method + * 2. 처리 개요 : + * - EAI 서버 이름을 저장한다. + * 3. 주의사항 + * + * @param name EAI 서버 이름 + **/ + public void setName(String name) { + this.name = name; + } + + /** + * 1. 기능 : EAI 서버 이름을 반환하는 getter method + * 2. 처리 개요 : + * - EAI 서버 이름을 반환한다. + * 3. 주의사항 + * + * @return EAI 서버 이름 + **/ + public String getName() { + return this.name; + } + + /** + * 1. 기능 : EAI 서버 IP 주로을 저장하는 setter method + * 2. 처리 개요 : + * - EAI 서버 IP 주로를 저장한다. + * 3. 주의사항 + * + * @param address EAI 서버 IP 주소 + **/ + public void setAddress(String address) { + this.address = address; + } + + /** + * 1. 기능 : EAI 서버 IP주소를 반환하는 getter method + * 2. 처리 개요 : + * - EAI 서버 IP주소을 반환한다. + * 3. 주의사항 + * + * @return EAI 서버 IP주소 + **/ + public String getAddress() { + return this.address; + } + + /** + * 1. 기능 : EAI 서버 리슨 포트를 저장하는 setter method + * 2. 처리 개요 : + * - EAI 서버 리슨 포트호를 저장한다. + * 3. 주의사항 + * + * @param port EAI 서버 리슨 포트 + **/ + public void setPort(String port) { + this.port = port; + } + + /** + * 1. 기능 : EAI 서버 리슨 포트를 반환하는 getter method + * 2. 처리 개요 : + * - EAI 서버 리슨 포트를 반환한다. + * 3. 주의사항 + * + * @return EAI 서버 리슨 포트 + **/ + public String getPort() { + return this.port; + } + + /** + * 1. 기능 : EAI 서버 FailOver 서버를 저장하는 setter method + * 2. 처리 개요 : + * - EAI 서버 FailOver 서버호를 저장한다. + * 3. 주의사항 + * + * @param failoverSvr FailOver 서버 + **/ + public void setFailoverSvr(String failoverSvr) { + this.failoverSvr = failoverSvr; + } + + /** + * 1. 기능 : EAI 서버 FailOver 서버를 반환하는 getter method + * 2. 처리 개요 : + * - EAI 서버 FailOver 서버트를 반환한다. + * 3. 주의사항 + * + * @return EAI 서버 FailOver 서버 + **/ + public String getFailoverSvr() { + return this.failoverSvr; + } + + /** + * 1. 기능 : EAI 서버에 대한 URL을 반환하는 getter method + * 2. 처리 개요 : + * - EAI 서버에 대한 URL을 반환한다. + * 3. 주의사항 + * + * @return EAI 서버에 대한 URL + **/ + public String toURL(String protocol) { + StringBuffer sb = new StringBuffer(); + sb.append(protocol).append(":").append("//"); + sb.append(address).append(":").append(port); + + return sb.toString(); + } + + /** + * 1. 기능 : EAIServerVO의 정보를 반환하는 메서드 + * - EAIServerVO의 정보를 반환한다. + * 3. 주의사항 + * + * @return EAIServerVO의 정보 + **/ + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("EAIServerVO[ name=").append(name); + sb.append(", address=").append(address); + sb.append(", port=").append(port); + sb.append(", failoverSvr=").append(failoverSvr); + sb.append(" ]"); + + return sb.toString(); + } + + /** + * 1. 기능 : 호스트명을 저장하는 setter method + * 2. 처리 개요 : + * - 호스트명을 저장한다. + * 3. 주의사항 + * + * @param address EAI 서버 IP 주소 + **/ + // Migration - 추가 + public void setHostName(String hostNm) { + this.hostNm = hostNm; + } + + /** + * 1. 기능 : 호스트명을 반환하는 getter method + * 2. 처리 개요 : + * - 호스트명을 반환한다. + * 3. 주의사항 + * + * @return EAI 서버 IP주소 + **/ + // Migration - 추가 + public String getHostName() { + return this.hostNm; + } +} diff --git a/src/com/eactive/eai/common/server/Keys.java b/src/com/eactive/eai/common/server/Keys.java new file mode 100644 index 0000000..090eaee --- /dev/null +++ b/src/com/eactive/eai/common/server/Keys.java @@ -0,0 +1,29 @@ +package com.eactive.eai.common.server; + +/** +* 1. 기능 : server 패키지에서 사용하는 상수를 정의한 Interface +* 2. 처리 개요 : +* - server 패키지에서 사용하는 상수를 정의한 Interface +* 3. 주의사항 +*/ +public class Keys +{ + /** + * 모든 서버를 의미하는 Default Server 이름 + */ + public static final String DEFAULT_SERVER = "ALL"; + + /** + * WebLogic의 현 운영 서버 이름에 대한 Property Key + */ + public static final String WLI_SERVER_KEY = "weblogic.Name"; + + /** + * WebLogic의 현 운영 서버 이름에 대한 운영(P), 테스트(T), 개발(D), 뮬레이터(S) Property Key + */ + public static final String EAI_SYSTEMMODE = "eai.systemmode"; + public static final String EAI_PRODUCT = "P"; + public static final String EAI_TEST = "T"; + public static final String EAI_DEVELOP = "D"; + public static final String EAI_SIMULATOR = "S"; +} diff --git a/src/com/eactive/eai/common/util/AnsiX923Padding.java b/src/com/eactive/eai/common/util/AnsiX923Padding.java new file mode 100644 index 0000000..227c452 --- /dev/null +++ b/src/com/eactive/eai/common/util/AnsiX923Padding.java @@ -0,0 +1,91 @@ +package com.eactive.eai.common.util; + +/** + * + */ +public class AnsiX923Padding implements CryptoPaddingImpl { + + /** 패딩 규칙 이름 */ + private String name = "ANSI-X.923-Padding"; + + private final byte PADDING_VALUE = 0x00; + + /** + * 요청한 Block Size를 맞추기 위해 Padding을 추가한다. + * + * @param source + * byte[] 패딩을 추가할 bytes + * @param blockSize + * int block size + * @return byte[] 패딩이 추가 된 결과 bytes + */ + public byte[] addPadding(byte[] source, int blockSize) { + int paddingCnt = source.length % blockSize; + byte[] paddingResult = null; + + if(paddingCnt != 0) { + paddingResult = new byte[source.length + (blockSize - paddingCnt)]; + + System.arraycopy(source, 0, paddingResult, 0, source.length); + + // 패딩해야 할 갯수 - 1 (마지막을 제외)까지 0x00 값을 추가한다. + int addPaddingCnt = blockSize - paddingCnt; + for(int i=0;i +* This class is used to encode and decode data in Base64 format as described in RFC 1521. +* +*

+* This is "Open Source" software and released under the GNU/LGPL license.
+* It is provided "as is" without warranty of any kind.
+* Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.
+* Home page: www.source-code.biz
+* +*

+* Version history:
+* 2003-07-22 Christian d'Heureuse (chdh): Module created.
+* 2005-08-11 chdh: Lincense changed from GPL to LGPL.
+* 2006-11-21 chdh:
+*   Method encode(String) renamed to encodeString(String).
+*   Method decode(String) renamed to decodeString(String).
+*   New method encode(byte[],int) added.
+*   New method decode(String) added.
+*/ + +public class Base64Coder { + +// Mapping table from 6-bit nibbles to Base64 characters. +private static char[] map1 = new char[64]; + static { + int i=0; + for (char c='A'; c<='Z'; c++) map1[i++] = c; + for (char c='a'; c<='z'; c++) map1[i++] = c; + for (char c='0'; c<='9'; c++) map1[i++] = c; + map1[i++] = '+'; map1[i++] = '/'; } + +// Mapping table from Base64 characters to 6-bit nibbles. +private static byte[] map2 = new byte[128]; + static { + for (int i=0; iin. +* @return A character array with the Base64 encoded data. +*/ +public static char[] encode (byte[] in, int iLen) { + int oDataLen = (iLen*4+2)/3; // output length without padding + int oLen = ((iLen+2)/3)*4; // output length including padding + char[] out = new char[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++] & 0xff; + int i1 = ip < iLen ? in[ip++] & 0xff : 0; + int i2 = ip < iLen ? in[ip++] & 0xff : 0; + int o0 = i0 >>> 2; + int o1 = ((i0 & 3) << 4) | (i1 >>> 4); + int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); + int o3 = i2 & 0x3F; + out[op++] = map1[o0]; + out[op++] = map1[o1]; + out[op] = op < oDataLen ? map1[o2] : '='; op++; + out[op] = op < oDataLen ? map1[o3] : '='; op++; } + return out; } + +/** +* Decodes a string from Base64 format. +* @param s a Base64 String to be decoded. +* @return A String containing the decoded data. +* @throws IllegalArgumentException if the input is not valid Base64 encoded data. +*/ +public static String decodeString (String s) { + return new String(decode(s)); } + +/** +* Decodes a byte array from Base64 format. +* @param s a Base64 String to be decoded. +* @return An array containing the decoded data bytes. +* @throws IllegalArgumentException if the input is not valid Base64 encoded data. +*/ +public static byte[] decode (String s) { + return decode(s.toCharArray()); } + +/** +* Decodes a byte array from Base64 format. +* No blanks or line breaks are allowed within the Base64 encoded data. +* @param in a character array containing the Base64 encoded data. +* @return An array containing the decoded data bytes. +* @throws IllegalArgumentException if the input is not valid Base64 encoded data. +*/ +public static byte[] decode (char[] in) { + int iLen = in.length; + if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); + while (iLen > 0 && in[iLen-1] == '=') iLen--; + int oLen = (iLen*3) / 4; + byte[] out = new byte[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++]; + int i1 = in[ip++]; + int i2 = ip < iLen ? in[ip++] : 'A'; + int i3 = ip < iLen ? in[ip++] : 'A'; + if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) + throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); + int b0 = map2[i0]; + int b1 = map2[i1]; + int b2 = map2[i2]; + int b3 = map2[i3]; + if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) + throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); + int o0 = ( b0 <<2) | (b1>>>4); + int o1 = ((b1 & 0xf)<<4) | (b2>>>2); + int o2 = ((b2 & 3)<<6) | b3; + out[op++] = (byte)o0; + if (op SDF_YYYYMMDD = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "yyyyMMdd"); + } + }; + + private static final ThreadLocal SDF_YYYYMMDD_DASH = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "yyyy-MM-dd"); + } + }; + + private static final ThreadLocal SDF_YYYYMMDDHHMMSS = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "yyyyMMddHHmmss"); + } + }; + private static final ThreadLocal SDF_YYYYMMDDHHMMSS_NO_MARK = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "yyyyMMddHHmmss"); + } + }; + private static final ThreadLocal SDF_YYYYMMDDHHMMSSMS_NO_MARK = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "yyyyMMddHHmmssSSS" ); + } + }; + private static final ThreadLocal SDF_HHMMSS_NO_MARK = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "HHmmss" ); + } + }; + private static final ThreadLocal SDF_HHMMSSMS_CEMI_COL = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "HH:mm:ss.SSS" ); + } + }; + private static final ThreadLocal SDF_YYYYMMDDHHMMSSMS_DASH_CEMI_COL = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" ); + } + }; + private static final ThreadLocal SDF_YYYYMMDDHHMMSSSS_NO_MARK = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat( "yyyyMMddHHmmssSSS" ); + } + }; + + private static final String DATE_SEP = "-"; + private static String TIME_SEP = ":"; + private static final String DAY[] = { + "\uC77C", "\uC6D4", "\uD654", "\uC218", "\uBAA9", "\uAE08", "\uD1A0" + }; + + /** + * Private 생성자 + * Instance를 생성하지 못함 + */ + private DatetimeUtil() + { + + } + + /** + * 1. 기능 : 현재시간을 yyyyMMddHHmmssSS 형태로 변환 + * 2. 처리 개요 : + * - currentmilisec 를 입력받아 yyyyMMddHHmmssSS 형태로 변환한다. + * 3. 주의사항 + * + * @param timeLong 현재시간 Long + * @return String + * @exception + **/ + + public static String getCurrentTime(long timeLong) + { + // 1hour(ms) = 60s * 60m * 1000ms + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + sdf.setTimeZone(new SimpleTimeZone(9 * 60 * 60 * 1000, "KST")); + return sdf.format(new java.util.Date(timeLong)); + } // end of getCurrentTime() + + + /** + * 1. 기능 : 현재시간 스트링을 YYYYMMDDHHMMSSsss 형식으로 1/1000초까지 얻을 수 있는 Method + * 2. 처리 개요 : + * - 현재시간을 yyyyMMddHHmmssSS 형태로 변환한다. + * 3. 주의사항 + * + * @return 1/1000까지 표시한 현재 시간 스트링(예: 20040920162110999) + * @exception + **/ + + public static java.lang.String getCurrentTimeMillis() { // 1/1000 sec. + return (SDF_YYYYMMDDHHMMSSMS_NO_MARK.get()).format(new java.util.Date()); + } + + + /** + * 1. 기능 : 현재날짜 스트링을 YYYYMMDD 형식으로 얻는 Method + * 2. 처리 개요 : + * - 현재시간을 yyyyMMddHHmmssSS 형태로 변환한다. + * 3. 주의사항 + * + * @return 년월만 표시한 현재 날짜 스트링(예: 20040920) + * @exception + **/ + public static java.lang.String getCurrentDate() { + return (SDF_YYYYMMDD.get()).format(new java.util.Date()); + } + /** + * 1. 기능 : 현재날짜 스트링을 YYYY-MM-DD 형식으로 얻는 Method + * 2. 처리 개요 : + * - 현재시간을 yyyyMMddHHmmssSS 형태로 변환한다. + * 3. 주의사항 + * + * @return 년월만 표시한 현재 날짜 스트링(예: 20040920) + * @exception + **/ + public static java.lang.String getCurrentDateDash() { + return (SDF_YYYYMMDD_DASH.get()).format(new java.util.Date()); + } + + public static java.lang.String getCurrentDateDash(long timeLong) { + return (SDF_YYYYMMDD_DASH.get()).format(new java.util.Date(timeLong)); + } + + /** + * 1. 기능 : 현재시간을 시분초 형식의 스트링으로 얻는 Method + * 2. 처리 개요 : + * - 현재시간을 yyyyMMddHHmmssSS 형태로 변환한다. + * 3. 주의사항 + * + * @return 시분초만 표시한 현재 시간 스트링(예: 162027) + * @exception + **/ + public static java.lang.String getCurrentTime() { + return (SDF_HHMMSS_NO_MARK.get()).format(new java.util.Date()); + } + + /** + * 1. 기능 : 현재부터 n분후의 시간 스트링(HHMMSS)을 얻는 Method + * 2. 처리 개요 : + * - 현재의 시간에서 min분 후의 시간을 리턴한다. (HHMMSS) + * 3. 주의사항 + * + * @param min 리턴하게 될 다음시간까지의 간격(분) + * @return 시분초만 표시한 시간 스트링(예: 162027) + * @exception + **/ + public static java.lang.String getNextTime(int min) { + return (SDF_HHMMSS_NO_MARK.get()).format( new java.util.Date( System.currentTimeMillis() + min * 60 * 1000L ) ); + } + + /** + * 1. 기능 : 현재 날짜시간 스트링을 년월일시분초로 가져오는 Method + * 2. 처리 개요 : + * - 현재 날짜시간 스트링을 년월일시분초로 가져오는 Method + * 3. 주의사항 + * + * @return 년월일시분초 시간 스트링(예: 20040921194425) + * @exception + **/ + public static java.lang.String getCurrentDateTime() { + return (SDF_YYYYMMDDHHMMSS.get()).format(new java.util.Date()); + } + + /** + * 1. 기능 : 현재 날짜시간 스트링을 년월일시분초1/1000초로 가져오는 Method + * 2. 처리 개요 : + * - 현재 날짜시간 스트링을 년월일시분초1/1000초로 가져오는 Method + * 3. 주의사항 + * + * @return 년월일시분초1/100 시간 스트링(예: 20040921194425125) + * @exception + **/ + public static java.lang.String getCurrentTimeCenti() { + return (SDF_YYYYMMDDHHMMSSMS_NO_MARK.get()).format(new java.util.Date()).substring(0,16); + } + + /** + * 1. 기능 : 시:분:초.1/1000초형식으로 현재시간을 가져오는 Method + * 2. 처리 개요 : + * - 시:분:초.1/1000초형식으로 현재시간을 가져오는 Method + * 3. 주의사항 + * + * @return 시:분:초.1/1000초 스트링(예: 19:46:27.053) + * @exception + **/ + public static String getTimeStamp() { + return (SDF_HHMMSSMS_CEMI_COL.get()).format(new java.util.Date()); + } + + /** + * 1. 기능 : 로그시 쓰기위해 "년-월-일 시:분:초.1/1000초" 형식으로 현재시간을 가져오는 Method + * 2. 처리 개요 : + * - 로그시 쓰기위해 "년-월-일 시:분:초.1/1000초" 형식으로 현재시간을 가져오는 Method + * 3. 주의사항 + * + * @return "년-월-일 시:분:초.1/1000"초 스트링(예: 2004-09-21 19:46:27.053) + * @exception + **/ + public static String getLogTimeStamp() { + return (SDF_YYYYMMDDHHMMSSMS_DASH_CEMI_COL.get()).format(new java.util.Date()); + } + + public static long getTimeInMillis(String yyyymmdd) { + if ( yyyymmdd.length() != 8) return -1; + + Calendar calendar = Calendar.getInstance(); + calendar.set(Integer.parseInt(yyyymmdd.substring(0,4)),Integer.parseInt(yyyymmdd.substring(4,6))-1,Integer.parseInt(yyyymmdd.substring(6))); + + return calendar.getTimeInMillis(); + } + + /** + * 1. 기능 : mmdd, yyyymmdd 형식의 날짜가 올바른지 검사하는 Method + * 2. 처리 개요 : + * - mmdd, yyyymmdd 형식의 날짜가 올바른지 검사하는 Method + * 3. 주의사항 + * + * @param date 스트링형태의 날짜( mmdd 또는 yyyymmdd ) + * @return 올바른 날짜이면 true, 올바르지 않은 날짜이면 false + * @exception + **/ + public static boolean isRightDate(String date) { + int len = date.length(); + if( len != 4 && len != 8 ) return false; + String sdate = null; + if ( len == 4 ) { + sdate = getCurrentDate().substring(0, 4) + "-" + date.substring(0,2) + "-" + date.substring(2); + } else { + sdate = date.substring(0,4) + "-" + date.substring(4,6) + "-" + date.substring(6); + } + + java.sql.Date dt = null; + try { + dt = java.sql.Date.valueOf(sdate); + } catch (Exception e) { + return false; + } + + if ( dt.toString().equals(sdate) ) return true; + else return false; + } + + /** + * 1. 기능 : 현재일의 다음일자를 리턴하는 Method + * 2. 처리 개요 : + * - 현재시간을 yyyyMMddHHmmssSS 형태로 변환한다. + * 3. 주의사항 + * + * @return 현재일의 다음날짜 스트링 + * @exception + **/ + public static String getNextDate() { + return getDayAddedDate( getCurrentDate(), 1 ); + } + + /** + * 1. 기능 : 지정일의 day일 후 일자를 리턴하는 Method + * 2. 처리 개요 : + * - 지정일의 day일 후 일자를 리턴하는 Method + * 3. 주의사항 + * + * @param yyyymmdd 'yyyymmdd' 스트링형태의 지정일 + * @param day 지정일로부터 더할 날수 + * @return 지정일에 day일을 더한 날짜 스트링( yyyymmdd ) 8자리 날짜가 아니면 입력한 지정일 리턴 + * @exception + **/ + public static String getDayAddedDate(String yyyymmdd, int day) { + if ( yyyymmdd.length() != 8) return yyyymmdd; + + Calendar calendar = Calendar.getInstance(); + calendar.set(Integer.parseInt(yyyymmdd.substring(0,4)),Integer.parseInt(yyyymmdd.substring(4,6))-1,Integer.parseInt(yyyymmdd.substring(6))+day); + + return (SDF_YYYYMMDD.get()).format(calendar.getTime()); + } + + /** + * 1. 기능 : 지정일의 day일 후 일자를 리턴하는 Method2 + * 2. 처리 개요 : + * - 지정일의 day일 후 일자를 리턴하는 Method (기존 Method 보존하고 .add()로 신규 처리) + * 3. 주의사항 + * + * @param yyyymmdd 'yyyymmdd' 스트링형태의 지정일 + * @param day 지정일로부터 더할 날수 + * @return 지정일에 day일을 더한 날짜 스트링( yyyymmdd ) 8자리 날짜가 아니거나 날짜형식에 맞지 않으면 입력한 지정일 리턴 + * @exception + **/ + public static String getDayAddedDate2(String yyyymmdd, int day) { + if ( yyyymmdd.length() != 8) return yyyymmdd; + + Calendar calendar = Calendar.getInstance(); + //calendar.set(Integer.parseInt(yyyymmdd.substring(0,4)),Integer.parseInt(yyyymmdd.substring(4,6))-1,Integer.parseInt(yyyymmdd.substring(6))+day); + try { + Date dt = (SDF_YYYYMMDD.get()).parse(yyyymmdd); + calendar.setTime(dt); + calendar.add(Calendar.DATE, day); + } catch (ParseException e) { + return yyyymmdd; + } + return (SDF_YYYYMMDD.get()).format(calendar.getTime()); + } + + /** + * 1. 기능 : 지정일의 month월 후 일자를 리턴하는 Method + * 2. 처리 개요 : + * - 지정일의 month월 후 일자를 리턴하는 Method + * 3. 주의사항 + * + * @param yyyymmdd 'yyyymmdd' 스트링형태의 지정일 + * @param month 지정일로부터 더할 월수 + * @return 지정일에 month월을 더한 날짜 스트링( yyyymmdd ) 8자리 날짜가 아니거나 날짜형식에 맞지 않으면 입력한 지정일 리턴 + * @exception + **/ + public static String getMonthAddedDate(String yyyymmdd, int month) { + if ( yyyymmdd.length() != 8) return yyyymmdd; + + Calendar calendar = Calendar.getInstance(); + //calendar.set(Integer.parseInt(yyyymmdd.substring(0,4)),Integer.parseInt(yyyymmdd.substring(4,6))-1+month,Integer.parseInt(yyyymmdd.substring(6))); + try { + Date dt = (SDF_YYYYMMDD.get()).parse(yyyymmdd); + calendar.setTime(dt); + calendar.add(Calendar.MONTH, month); + } catch (ParseException e) { + return yyyymmdd; + } + + return (SDF_YYYYMMDD.get()).format(calendar.getTime()); + } + + /** + * 1. 기능 : 지정일의 year년 후 일자를 리턴하는 Method + * 2. 처리 개요 : + * - 지정일의 year년 후 일자를 리턴하는 Method + * 3. 주의사항 + * + * @param yyyymmdd 'yyyymmdd' 스트링형태의 지정일 + * @param year 지정일로부터 더할 년수 + * @return 지정일에 year년을 더한 날짜 스트링( yyyymmdd ) 8자리 날짜가 아니거나 날짜형식에 맞지 않으면 입력한 지정일 리턴 + * @exception + **/ + public static String getYearAddedDate(String yyyymmdd, int year) { + if ( yyyymmdd.length() != 8) return yyyymmdd; + + Calendar calendar = Calendar.getInstance(); + //calendar.set(Integer.parseInt(yyyymmdd.substring(0,4))+year,Integer.parseInt(yyyymmdd.substring(4,6))-1,Integer.parseInt(yyyymmdd.substring(6))); + try { + Date dt = (SDF_YYYYMMDD.get()).parse(yyyymmdd); + calendar.setTime(dt); + calendar.add(Calendar.YEAR, year); + } catch (ParseException e) { + return yyyymmdd; + } + + return (SDF_YYYYMMDD.get()).format(calendar.getTime()); + } + + /** + * 1. 기능 : 지정일의 year년month월day일 후 일자를 리턴하는 Method + * 2. 처리 개요 : + * - 지정일의 year년month월day일 후 일자를 리턴하는 Method + * 3. 주의사항 + * + * @param yyyymmdd 'yyyymmdd' 스트링형태의 지정일 + * @param year 지정일로부터 더할 년수 + * @param month 지정일로부터 더할 월수 + * @param day 지정일로부터 더할 날수 + * @return 지정일에 year년month월day일을 더한 날짜 스트링( yyyymmdd ) 8자리 날짜가 아니거나 날짜형식에 맞지 않으면 입력한 지정일 리턴 + * @exception + **/ + public static String getDateAddedDate(String yyyymmdd, int year, int month, int day) { + if ( yyyymmdd.length() != 8) return yyyymmdd; + + Calendar calendar = Calendar.getInstance(); + //calendar.set(Integer.parseInt(yyyymmdd.substring(0,4))+year,Integer.parseInt(yyyymmdd.substring(4,6))-1+month,Integer.parseInt(yyyymmdd.substring(6))+day); + try { + Date dt = (SDF_YYYYMMDD.get()).parse(yyyymmdd); + calendar.setTime(dt); + calendar.add(Calendar.YEAR, year); + calendar.add(Calendar.MONTH, month); + calendar.add(Calendar.DATE, day); + } catch (ParseException e) { + return yyyymmdd; + } + + return (SDF_YYYYMMDD.get()).format(calendar.getTime()); + } + + + + /** + * 1. 기능 : 형식화된 Date 문자열 리턴하는 메서드 + * 2. 처리 개요 : + * - format은 "YYYYMMDD" 등 자바에서 지원하는 date format을 사용.format의 길이만큼 잘라서 리턴함. + * 3. 주의사항 + * + * @param format "YYYY-MM-DD HH:mm:ss.SSS", SSS는 밀리세컨드 단위 + * @param day 변환 대상 일자 + * @return 형식화된 date 문자열 + * @exception + **/ + public static String getFormattedDate( String format, java.util.Date day ) + { + /* + Calendar labelDay = Calendar.getInstance(); + DateFormat df = DateFormat.getDateInstance(); + java.util.Date sDate = df.parse(startLabel); + labelDay.setTime(sDate); + */ + if ( day == null || format == null ) + return ""; + SimpleDateFormat formatter = new SimpleDateFormat (format); + String result = formatter.format(day); + if ( result.length() > format.length() ) + result = result.substring( 0, format.length() ); + return result; + } + + /** + * 1. 기능 : 문자열을 boolean으로 변환하는 메서드 + * 2. 처리 개요 : + * - 문자열을 boolean으로 변환하는 메서드 + * 3. 주의사항 + * + * @param booleanStr boolean을 뜻하는 문자 + * @return booleanStr이 나타내는 boolean 값 + * true : booleanStr이 "Y", "y", "1" 일 경우 + * false : booleanStr이 "N", "n", "0" 일 경우 + * @exception + **/ + public static boolean getBooleanValue( String booleanStr ) + { + if ( booleanStr.equalsIgnoreCase( "Y" ) || + booleanStr.equalsIgnoreCase( "1" ) ) + return true; + else if ( booleanStr.equalsIgnoreCase( "N" ) || + booleanStr.equalsIgnoreCase( "0" ) ) + return false; + else return false; + } + + /** + * 1. 기능 : 시작/끝 시간을 System.out.currentTimeMillis()의 결과로 세팅할 때 경과된 시간을 리턴하는 Method + * 2. 처리 개요 : + * - 시작/끝 시간을 System.out.currentTimeMillis()의 결과로 세팅할 때 경과된 시간을 리턴 + * 3. 주의사항 + * + * @param start 시작시간(milli second 단위) + * @param end 종료시간(milli second 단위) + * @return 경과 시간(second 단위) + * @exception + **/ + public static float getElapsedTime( long start, long end ) + { + return (float)(end - start)/(float)1000; + } + + /** + * 1. 기능 : 년, 월, 일을 숫자로 리턴하는 함수를 위해 주어진 패턴별로 날짜를 숫자로 리턴하는 Method + * 2. 처리 개요 : + * - 년, 월, 일을 숫자로 리턴하는 함수를 위해 주어진 패턴별로 날짜를 숫자로 리턴 + * 3. 주의사항 + * + * @param pattern 년(yyyy),월(MM),일(dd)에 해당하는 패턴 + * @return 해당 pattern에 맞는 숫자값 + * @exception + **/ + private static int getNumberByPattern(String pattern) + { + SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.KOREA); + String dateString = formatter.format(new Date()); + return Integer.parseInt(dateString); + } + + /** + * 1. 기능 : 현재 년도를 숫자로 리턴하는 Method + * 2. 처리 개요 : + * - 현재 년도를 숫자로 리턴 + * 3. 주의사항 + * + * @return 현재 년도 숫자 + * @exception + **/ + public static int getYear() + { + return getNumberByPattern("yyyy"); + } + + /** + * 1. 기능 : 현재 월을 숫자로 리턴하는 Method + * 2. 처리 개요 : + * - 현재 월을 숫자로 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 월 숫자 + * @exception + **/ + public static int getMonth() + { + return getNumberByPattern("MM"); + } + + /** + * 1. 기능 : 현재 일을 숫자로 리턴하는 Method + * 2. 처리 개요 : + * - 현재 일을 숫자로 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 일 숫자 + * @exception + **/ + public static int getDay() + { + return getNumberByPattern("dd"); + } + + /** + * 1. 기능 : 현재 요일을 문자로 리턴하는 Method + * 2. 처리 개요 : + * - 현재 요일을 문자로 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 요일 문자 + * @exception + **/ + public static String getDayOfWeek() + { + Calendar c = Calendar.getInstance(); + return DAY[c.get(7) - 1]; + } + + /** + * 1. 기능 : 현재 시간 중 시에 해당하는 숫자를 리턴하는 Method + * 2. 처리 개요 : + * - 현재 시간 중 시에 해당하는 숫자를 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 시 숫자 + * @exception + **/ + public static int getHour() + { + Calendar c = Calendar.getInstance(); + return c.get(11); + } + + /** + * 1. 기능 : 현재 시간 중 분에 해당하는 숫자를 리턴하는 Method + * 2. 처리 개요 : + * - 현재 시간 중 분에 해당하는 숫자를 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 분 숫자 + * @exception + **/ + public static int getMinute() + { + Calendar c = Calendar.getInstance(); + return c.get(12); + } + + /** + * 1. 기능 : 현재 시간 중 초에 해당하는 숫자를 리턴하는 Method + * 2. 처리 개요 : + * - 현재 시간 중 초에 해당하는 숫자를 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 초 숫자 + * @exception + **/ + public static int getSecond() + { + Calendar c = Calendar.getInstance(); + return c.get(13); + } + + /** + * 1. 기능 : 현재 날짜 스트링을 리턴하는 Method + * 2. 처리 개요 : + * - 현재 날짜 스트링을 리턴하는 Method + * 3. 주의사항 + * + * @return 날짜 스트링( YYYY-MM-DD ) + * @exception + **/ + public static String getDateString() + { + return getYear() + DATE_SEP + getMonth() + DATE_SEP + getDay(); + } + + /** + * 1. 기능 : 현재 날짜 스트링을 주어진 분리자를 이용하여 리턴하는 Method + * 2. 처리 개요 : + * - 현재 날짜 스트링을 주어진 분리자를 이용하여 리턴하는 Method + * 3. 주의사항 + * + * @param sep 분리자 + * @return 분리자가 포함된 날짜 스트링 + * @exception + **/ + public static String getDateString(String sep) + { + return getYear() + sep + getMonth() + sep + getDay(); + } + + /** + * 1. 기능 : 현재 시간 스트링을 리턴하는 Method + * 2. 처리 개요 : + * - 현재 시간 스트링을 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 시간 스트링( HH:mm:ss ) + * @exception + **/ + public static String getTimeString() + { + String hour = getHour() + ""; + String min = getMinute() + ""; + String sec = getSecond() + ""; + if(hour.length() == 1) + hour = "0" + hour; + if(min.length() == 1) + min = "0" + min; + if(sec.length() == 1) + sec = "0" + sec; + return hour + TIME_SEP + min + TIME_SEP + sec; + } + /** + * 1. 기능 : 현재 일시 스트링을 리턴하는 Method + * 2. 처리 개요 : + * - 현재 일시 스트링을 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 일시 스트링( YYYY-MM-DD HH:mm:ss ) + * @exception + **/ + public static String getTimeStampString() + { + return getDateString(DATE_SEP) + " " + getTimeString(); + } + + /** + * 1. 기능 : 현재 일시 스트링을 분까지 리턴하는 Method + * 2. 처리 개요 : + * - 현재 일시 스트링을 분까지 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 일시 스트링 ( YYYYMMDDHHmm ) + * @exception + **/ + public static String getDate_Time_Min() + { + String month = getMonth() + ""; + String day = getDay() + ""; + String hour = getHour() + ""; + String min = getMinute() + ""; + if(month.length() == 1) + month = "0" + month; + if(day.length() == 1) + day = "0" + day; + if(hour.length() == 1) + hour = "0" + hour; + if(min.length() == 1) + min = "0" + min; + return getYear() + "" + month + "" + day + "" + hour + "" + min; + } + + /** + * 1. 기능 : 현재 일시 스트링을 초까지 리턴하는 Method + * 2. 처리 개요 : + * - 현재 일시 스트링을 초까지 리턴하는 Method + * 3. 주의사항 + * + * @return 현재 일시 스트링 ( YYYYMMDDHHmmss ) + * @exception + **/ + public static String getDateTimeString() + { + String month = getMonth() + ""; + String day = getDay() + ""; + String hour = getHour() + ""; + String min = getMinute() + ""; + String sec = getSecond() + ""; + if(month.length() == 1) + month = "0" + month; + if(day.length() == 1) + day = "0" + day; + if(hour.length() == 1) + hour = "0" + hour; + if(min.length() == 1) + min = "0" + min; + if(sec.length() == 1) + sec = "0" + sec; + return getYear() + "" + month + "" + day + "" + hour + "" + min + sec; + } + + /** + * 1. 기능 : 14자리 일시 문자열을 분리자가 있는 날짜 스트링으로 바꾸어 리턴하는 Method + * 2. 처리 개요 : + * - 14자리 일시 문자열을 분리자가 있는 날짜 스트링으로 바꾸어 리턴하는 Method + * 3. 주의사항 + * + * @param dateTime 8자리 일시 문자열( YYYYMMDD ) + * @return "-" 분리자가 포함된 일시 문자열 ( YYYY-MM-DD ) + * @exception + **/ + public static String parseDate(String dateTime) + { + String year = dateTime.substring(0, 4); + String month = dateTime.substring(4, 6); + String day = dateTime.substring(6, 8); + return year + "-" + month + "-" + day; + } + + /** + * 1. 기능 : 주어진 년이 윤년인지 아닌지 리턴하는 Method + * 2. 처리 개요 : + * - 주어진 년이 윤년인지 아닌지 리턴하는 Method + * 3. 주의사항 + * + * @param year 검사 대상 년도 + * @return 유년 여부 + * true : 윤년 + * false : 윤년이 아님 + * @exception + **/ + public static boolean checkEmbolism(int year) + { + int remain = 0; + int remain_1 = 0; + int remain_2 = 0; + remain = year % 4; + remain_1 = year % 100; + remain_2 = year % 400; + if(remain == 0) + { + if(remain_1 == 0) + return remain_2 == 0; + else + return true; + } else + { + return false; + } + } + + /** + * 1. 기능 : 년도와 월로 입력한 월의 일수를 리턴하는 Method + * 2. 처리 개요 : + * - 년도와 월로 입력한 월의 일수를 리턴하는 Method + * 3. 주의사항 + * + * @param year 년도 + * @param month 월 + * @return 입력한 월에 해당하는 일수 + * @exception + **/ + public static int getMonthDate(String year, String month) + { + int dateMonth[] = new int[12]; + dateMonth[0] = 31; + dateMonth[1] = 28; + dateMonth[2] = 31; + dateMonth[3] = 30; + dateMonth[4] = 31; + dateMonth[5] = 30; + dateMonth[6] = 31; + dateMonth[7] = 31; + dateMonth[8] = 30; + dateMonth[9] = 31; + dateMonth[10] = 30; + dateMonth[11] = 31; + if(checkEmbolism(Integer.parseInt(year))) + dateMonth[1] = 29; + int day = dateMonth[Integer.parseInt(month) - 1]; + return day; + } + /** + * 1. 기능 : 년월일시분초를 넣으면 특정일 앞이나 뒤로 이동해서 리턴하는 Method + * 2. 처리 개요 : + * - 년월일시분초를 넣으면 특정일 앞이나 뒤로 이동해서 리턴하는 Method + * 3. 주의사항 + * + * @param sourceDate YYYYMMDDHHMMSS + * @param moveDay 몇일 + * @return YYYYMMDDHHMMSSSS + * @exception + **/ + public static String getDateMove(String sourceDate, int moveDay) + { + try{ + Date srcDate; + Date resultDate; + + srcDate= SDF_YYYYMMDDHHMMSS_NO_MARK.get().parse(sourceDate); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"),Locale.KOREA); + calendar.setTime (srcDate); + calendar.roll(Calendar.DATE , moveDay ); + resultDate = calendar.getTime(); + + return SDF_YYYYMMDDHHMMSSSS_NO_MARK.get().format(resultDate); + }catch(Exception e){ + return null; + } + } + + //static { SDF_YYYYMMDD.setLenient(false); } + public static boolean isDateValue(String srcValue) { + try { SDF_YYYYMMDD.get().parse(srcValue); } catch (Exception e) { return false; } + return true; + } + //static { SDF_HHMMSS_NO_MARK.setLenient(false); } + public static boolean isTimeValue(String srcValue) { + try { SDF_HHMMSS_NO_MARK.get().parse(srcValue); } catch (Exception e) { return false; } + return true; + } + + /** + * yyyyMMdd 형식의 날짜에 days 만큼 날짜를 더한 yyyyMMdd 문자열을 얻는다. + * + * calendar add 함수로 다시 구현 + * @param tempBaseDate yyyyMMdd + * @param days 추가할 일수. -1 인 경우 전일자 + * @return yyyyMMdd 형식 + * @throws ParseException + */ + public synchronized static String addDays(String tempBaseDate, int days) throws ParseException { + if ( tempBaseDate.length() != 8) return tempBaseDate; + + Calendar calendar = Calendar.getInstance(); + Date date = SDF_YYYYMMDD.get().parse(tempBaseDate); + calendar.setTime(date); + calendar.add(Calendar.DAY_OF_MONTH, days); + + return (SDF_YYYYMMDD.get()).format(calendar.getTime()); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/JMSSender.java b/src/com/eactive/eai/common/util/JMSSender.java new file mode 100644 index 0000000..af05773 --- /dev/null +++ b/src/com/eactive/eai/common/util/JMSSender.java @@ -0,0 +1,58 @@ +package com.eactive.eai.common.util; + +import com.eactive.eai.common.activemq.AmqQueueProducer; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.routing.JMSQueueSender; + +public class JMSSender +{ + private static int getMqType(String connectionUri) { + int type = 1; // rabbitmq + + if(connectionUri == null) return 0; + + if(connectionUri.startsWith("amqp:")) { + type = 1; + } + else if(connectionUri.startsWith("tcp:")) { + type = 2; + } + else if(connectionUri.startsWith("vm:")) { + type = 2; + } + else if(connectionUri.startsWith("jms/")) { + type = 3; + } + else { + type = 0; + } + + return type; + } + public static void sendToQueue(Object data, String connectionUri, String destination ) + throws Exception { + try { + switch(getMqType(connectionUri)) { + case 1 : +// QueueProducer producer = new QueueProducer(connectionUri, destination); +// producer.sendMessage((java.io.Serializable)data); +// break; + throw new Exception("not implemented connection type - " +connectionUri); + case 2: + AmqQueueProducer aproducer = new AmqQueueProducer(connectionUri, destination); + aproducer.sendMessage((java.io.Serializable)data); + break; + case 3 : + JMSQueueSender sender = new JMSQueueSender(); + sender.sendObject(connectionUri, destination, (java.io.Serializable) data, null); + break; + default : + throw new Exception("Unknown connectionUri - " +connectionUri + " / type - " + getMqType(connectionUri) ); + } + } catch(Exception e) { + throw new Exception(ExceptionUtil.getErrorCode(e,"RECEAICUL001")); + } finally { + + } + } +} diff --git a/src/com/eactive/eai/common/util/JndiObjectFactoryBeanForElink.java b/src/com/eactive/eai/common/util/JndiObjectFactoryBeanForElink.java new file mode 100644 index 0000000..78286f6 --- /dev/null +++ b/src/com/eactive/eai/common/util/JndiObjectFactoryBeanForElink.java @@ -0,0 +1,27 @@ +package com.eactive.eai.common.util; + +import org.springframework.jndi.JndiObjectFactoryBean; + +import com.eactive.eai.rms.client.util.ContainerUtil; + +public class JndiObjectFactoryBeanForElink extends JndiObjectFactoryBean { + public void setJndiName(String jndiName) { + super.setJndiName(jndiName); + + if (ContainerUtil.get() == ContainerUtil.TOMCAT) { + super.setResourceRef(true); + } else if (ContainerUtil.get() == ContainerUtil.WEBLOGIC) { + super.setResourceRef(false); + } else if (ContainerUtil.get() == ContainerUtil.JBOSS) { + super.setResourceRef(false); + } else if (ContainerUtil.get() == ContainerUtil.WEBSPHERE) { + super.setResourceRef(false); + } else { + super.setResourceRef(false); + } + } + public String getJndiName() { + return super.getJndiName(); + } + +} diff --git a/src/com/eactive/eai/common/util/LogKeys.java b/src/com/eactive/eai/common/util/LogKeys.java new file mode 100644 index 0000000..4307a8d --- /dev/null +++ b/src/com/eactive/eai/common/util/LogKeys.java @@ -0,0 +1,99 @@ +package com.eactive.eai.common.util; + +/** + * 1. 기능 : Log4j 환경을 위한 상수를 정의한 interface + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : + * @since : + */ + +public interface LogKeys +{ + + //파일로거 메인 프라퍼티 그룹 명 + public static final String LOGGER_INFO = "FileLoggerInfo"; + public static final String PATTERN_LAYOUT ="pattern.layout"; + public static final String ENCODING ="encong"; + + //초기화 시 생성할 파일로거 명들 + public static final String LOGGER_DEFAULT = "FileLogger{DEFAULT}"; + public static final String LOGGER_ADAPTER = "FileLogger{ADAPTER}"; + public static final String LOGGER_ADAPTER_ERR = "FileLogger{ADAPTER_ERR}"; + public static final String LOGGER_FILEEVENT = "FileLogger{FILEEVENT}"; + public static final String LOGGER_SCHEDULER = "FileLogger{SCHEDULER}"; + public static final String LOGGER_EXCEPTION = "FileLogger{EXCEPTION}"; + public static final String LOGGER_SMS = "FileLogger{SMS}"; + + public static final String LOGGER_DEFAULT_PREFIX = "FileLogger{DEFAULT}"; + public static final String LOGGER_ADAPTER_PREFIX = "FileLogger{ADAPTER}"; + public static final String LOGGER_ADAPTER_ERR_PREFIX = "FileLogger{ADAPTER_ERR}"; + public static final String LOGGER_FILEEVENT_PREFIX = "FileLogger{FILEEVENT}"; + public static final String LOGGER_SCHEDULER_PREFIX = "FileLogger{SCHEDULER}"; + public static final String LOGGER_EXCEPTION_PREFIX = "FileLogger{EXCEPTION}"; + public static final String LOGGER_SMS_PREFIX = "FileLogger{SMS}"; + + //FileLoggerInfo 프라퍼티 + public static final String INITIAL_LOGGER_LIST = "initial.logger.list"; //파일로거 Logger 프라퍼티 그룹명 리스트 (필수) + public static final String INITIAL_APPENDER_LIST = "initial.appender.list"; //파일로거 Appender 프라퍼티 그룹명 리스트 (필수) + public static final String INITIAL_LOGGER_CLIENT = "initial.logger.client"; //파일로거 Client Logger 프라퍼티 그룹명 (필수) + public static final String INITIAL_APPENDER_CLIENT = "initial.appender.client"; //파일로거 Client Appender 프라퍼티 그룹명 (필수) + + + //파일로거 log4j Logger 프라퍼티들 + public static final String LOGGER_LEVEL = "logger.level"; //log4j Logger 로그레벨 속성 (가질수있는 값 : debug, info, warn, error, fatal) (선택, 디폴트 debug) + public static final String LOGGER_APPENDER = "logger.appender"; //log4j Logger 에 설정할 Appender 프라퍼티 그룹명 리스트 (선택, 1개이상 권장) + public static final String LOGGER_APPENDER_LIST = "logger.appender.list"; //log4j Logger 에 설정할 Appender 프라퍼티 그룹명 리스트 (선택, 1개이상 권장) + public static final String LOGGER_CONSOLE = "logger.console"; //log4j Logger 콘솔 출력여부 (가질수있는 값 : on, off) (선택, 디폴트 on) + public static final String LOGGER_ADITIVITY = "logger.aditivity"; //log4j Logger aditivity 속성 (가질수있는 값 : true, false) (선택, 디폴트 false) + + + //파일로그 log4j Appender 프라퍼티들 + public static final String APPENDER_LOG_DIRECOTRY = "appender.log.directory"; //로그파일 저장 디렉토리 절대경로 (필수) + public static final String APPENDER_LOG_FILENAME = "appender.log.filename"; //로그파일 명 (필수) + public static final String APPENDER_DATE_PATTERN = "appender.date.pattern"; //로그파일 날자별 생성 규칙 (선택, 디폴트 "'.'yyyy-MM-dd") + public static final String APPENDER_PATTERN_LAYOUT = "appender.pattern.layout"; //로그 패턴 문자열 (선택, 디폴트 "[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5p %m%n") + public static final String APPENDER_FILE_APPEND = "appender.file.append"; //로그파일 로그Append 여부 (가질수있는 값 : true, false) (선택, 디폴트 true) + public static final String MAX_BACKUP_INDEX = "max.backup.index"; + public static final String LOG_FILE_COUNT = "log.file.count"; // 사이즈별로 만든 파일을 유지할 개수 + public static final String FILE_SIZE = "file.size"; // 이 용량보다 크면 파일을 분리함 + public static final String LOG_DIRECOTRY_PREFIX ="log.directory.prefix"; + + public static final String LOGGER_LIST ="logger.list"; + public static final String APPENDER_LIST ="appender.list"; + /** 기관별 로거 */ + String LOGGER_INST = "FileLogger{INST}"; + /** 기관별 appender */ + String APPENDER_INST = "FileAppender{INST}"; + /** 기관별 로그 프라퍼티 */ + String INST_LOG = "inst.log"; + + /** + * FileAppender + */ + public static final String LOG_FILE ="log.file"; + public static final String DATE_PATTERN ="date.pattern"; + public static final String APPEND ="append"; + + public static final String ADITIVITY ="aditivity"; + public static final String LOG_LEVEL ="log.level"; + public static final String CONSOLE ="console"; + public static final String APPENDER ="appender"; + public static final String SMS_INTERVAL = "sms.interval.mi"; // sms logging interval(minute) + + public static final String CONSOLE_APPENDER = "Appender{CONSOLE}"; + + public static final String LOG_ON = "on"; + public static final String LOG_OFF = "off"; + + public static final String TRACE = "trace"; + public static final String DEBUG = "debug"; + public static final String INFO = "info"; + public static final String WARN = "warn"; + public static final String ERROR = "error"; + public static final String FATAL = "fatal"; +} diff --git a/src/com/eactive/eai/common/util/Logger.java b/src/com/eactive/eai/common/util/Logger.java new file mode 100644 index 0000000..767b913 --- /dev/null +++ b/src/com/eactive/eai/common/util/Logger.java @@ -0,0 +1,951 @@ +package com.eactive.eai.common.util; + +import java.io.File; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Pattern; + +import java.io.File; +import java.io.Serializable; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Properties; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.LoggerFactory; + +import com.eactive.eai.common.util.logger.CustomPatternLayoutEncoder; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.property.FileLoggerPropertyChangeListener; +import com.eactive.eai.common.property.PropManager; + +//import com.eactive.eai.common.property.PropManager; +//import com.eactive.eai.common.server.EAIServerManager; + + +//import com.eactive.eai.common.property.FileLoggerPropertyChangeListener; +//import com.eactive.eai.common.property.PropManager; +//import com.eactive.eai.common.server.EAIServerManager; +//import com.eactive.eai.common.util.logger.CustomPatternLayoutEncoder; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.jul.LevelChangePropagator; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.ConsoleAppender; +import ch.qos.logback.core.rolling.RollingFileAppender; +import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.server.EAIServerManager; + +/** + * 1. 기능 : Log4j을 통한 화일로그를 관리하는 Utility Class 2. 처리 개요 : + * + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : + * @since : + */ +public class Logger implements LogKeys, Serializable { + //Logger list (프라퍼티에 설정된 Logger 및 Dafault Console Logger 를 담는다.) + protected static Hashtable loggers = new Hashtable(5); + + private org.slf4j.Logger loggerImpl; + private static Properties props; + + public static void initBatLoggers() { + Logger logger = null; + logger = new Logger(LOGGER_ADAPTER); + loggers.put(LOGGER_ADAPTER, logger); + logger = new Logger(LOGGER_FILEEVENT); + loggers.put(LOGGER_FILEEVENT, logger); + logger = new Logger(LOGGER_SCHEDULER); + loggers.put(LOGGER_SCHEDULER, logger); + } + public void setLoggerImpl(org.slf4j.Logger slf4jLogger) { + loggerImpl = slf4jLogger; + } + public org.slf4j.Logger getLoggerImpl() { + return loggerImpl; + } + /** + * 1. 기능 : Logger factory method + * 2. 처리 개요 : + * - Logger Factory를 생성한다. + * 3. 주의사항 + * + * @param name Logger name + * @return Logger object + **/ + static public synchronized Logger getLogger(String name) { + try { + Logger logger = null; + if(name == null) { + throw new Exception("Logger Name can not be null"); + } + else { + logger = loggers.get(name); + if (logger==null) { + logger = new Logger(name); + loggers.put(name, logger); + } + } + return logger; + } catch (Exception e) { + System.out.println(e.getMessage()); + } + return null; + } + + + + /** + * Constructor + */ + private Logger(String name) { + if(name == null || name.equals("") || name.equals("root")) { + this.loggerImpl = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + } else { + this.loggerImpl = LoggerFactory.getLogger(name); + } + + if(this.loggerImpl == null) { + this.loggerImpl = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + } + } + + public String getName() { + return this.loggerImpl.getName(); + } + + /** + * 1. 기능 : PropManager를 통해 Log4j의 환경을 설정 + * 2. 처리 개요 : + * - PropManager를 통해 Log4j의 환경을 설정 + * 3. 주의사항 + * + * @exception + **/ + public static void doConfigure() + { + try + { + System.out.println("@ Logger is initializing. ========================================"); + //======================================================== + //1. 파일 Logger 기본 프라퍼티 정보 체크 + //======================================================== + PropManager pmanager = PropManager.getInstance(); + Properties loggerInfo= pmanager.getProperties(LOGGER_INFO); + String defaultLayout = loggerInfo.getProperty(PATTERN_LAYOUT); + //초기화시 메모리에 적재할 Logger 이름 리스트 + String loggerList = loggerInfo.getProperty(INITIAL_LOGGER_LIST); + if(loggerList==null || loggerList.equals("")) throw new RuntimeException("BECEAICUL005"); + + //초기화시 Logger 에 설정해줄 파일 Appender 이름 리스트 + String appenderList = loggerInfo.getProperty(INITIAL_APPENDER_LIST); + if(appenderList==null || appenderList.equals("")) throw new RuntimeException("BECEAICUL006"); + + + //======================================================== + //2. 프라퍼티에 설정된 모든 Appender 생성 후 HashMap에 저장 + //======================================================== + //이후 Logger 생성시 필요한 Appender 찾아서 붙여줌 + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.reset(); + + LevelChangePropagator propagator = new LevelChangePropagator(); + propagator.setContext(lc); + propagator.setResetJUL(true); + propagator.start(); + + lc.addListener(propagator); + + CustomPatternLayoutEncoder ple = new CustomPatternLayoutEncoder(); + ple.setPattern( defaultLayout ); + ple.setContext(lc); + ple.start(); + + ConsoleAppender consoleAppender = new ConsoleAppender(); + consoleAppender.setName(CONSOLE_APPENDER); + consoleAppender.setEncoder( ple ); + consoleAppender.setContext( lc ); + consoleAppender.start(); + String[] appenderNameList = StringUtil.getStrArray(appenderList, ","); + HashMap> fa = new HashMap>(); + + for(int i=0;i appender = addFileAppender(appenderNameList[i]); + if ( appender == null ) { + continue; + } + CustomPatternLayoutEncoder fple = new CustomPatternLayoutEncoder(); + fple.setContext( lc ); + + String appenderLayout = pmanager.getProperty(appenderNameList[i], PATTERN_LAYOUT); + if (appenderLayout == null){ + fple.setPattern( defaultLayout ); + }else{ + fple.setPattern( appenderLayout ); + } + String encoding = pmanager.getProperty(appenderNameList[i],ENCODING); + if(encoding==null) { + encoding = "EUC-KR"; + }else { + encoding = encoding.trim(); + } + if (StringUtils.isNotBlank(encoding)) { + fple.setCharset(Charset.forName(encoding)); + } + + fple.start(); + + appender.setEncoder( fple ); + appender.start(); + + fa.put( appenderNameList[i], appender ); + } + + + //======================================================== + //3. 프라퍼티에 설정된 모든 파일 Logger 생성 + //======================================================== + String[] loggerNameList = StringUtil.getStrArray(loggerList, ","); //log4j Logger 생성 + ch.qos.logback.classic.Logger logger = null; + + for(int i=0; i appender = + (RollingFileAppender)fa.get(appenderName); + if(appender==null) { + continue; + } + + logger.addAppender(appender); + System.out.println("@ add FileAppender to "+logger.getName()+" - "+appender.getName()); + } + } + + PropManager prptManager = PropManager.getInstance(); + prptManager.addPropertyChangeListener( new FileLoggerPropertyChangeListener() ); + + } catch(Exception e) { + System.out.println(e.getMessage()); + } + + } + + public static void setLoggerLevel(String loggerName) { + + ch.qos.logback.classic.Logger logger = null; + Level asisLevel = null; + Level toLevel = null; + + try { + PropManager pmanager = PropManager.getInstance(); + String logLevel = pmanager.getProperty(loggerName, LOGGER_LEVEL); + + if(loggerName.startsWith(org.slf4j.Logger.ROOT_LOGGER_NAME)){ + logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + }else{ + logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName); + } + toLevel = Level.toLevel(logLevel, null); + + if ( logger == null || toLevel == null) { + System.out.println("@@ Logger setLoggerLevel | loggerName [" + + loggerName + "] or Level [" + logLevel + "] is incorrect"); + return; + } + + asisLevel = logger.getLevel(); + if ( asisLevel.toInt() != toLevel.toInt() ) { + logger.setLevel( toLevel ); + System.out.println("@@ Logger setLoggerLevel | " + loggerName + + " AS-IS [" + asisLevel.toString() + "] TO [" + toLevel.toString() + "]"); + } + + } catch (Exception e) { + System.err.println("@@ Logger setLoggerLevel Error | " + + loggerName + " | " + e.getMessage() ); + } + } + + /** + * 1. 기능 : logback의 logger를 추가 + * 2. 처리 개요 : + * - logback API를 통해 logger를 추가 + * 3. 주의사항 + * + * @exception + **/ + public static ch.qos.logback.classic.Logger addLogger(String loggerName) { + + ch.qos.logback.classic.Logger logger = null; + + try { + PropManager pmanager = PropManager.getInstance(); + + props = pmanager.getProperties(loggerName); + String logLevel = props.getProperty( LOGGER_LEVEL); + String aditivity = props.getProperty( LOGGER_ADITIVITY); + +// logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName); + Logger fileLogger = loggers.get(loggerName); + if(fileLogger != null) + logger = (ch.qos.logback.classic.Logger)fileLogger.getLoggerImpl(); + else { + fileLogger = new Logger(loggerName); + } + logger = (ch.qos.logback.classic.Logger)fileLogger.getLoggerImpl();//(ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName); + try { + logger.setAdditive(new Boolean(aditivity).booleanValue()); + } catch(Exception e) { + logger.setAdditive(false); + } + + if(logLevel==null || logLevel.equals(DEBUG)) { + logger.setLevel(Level.DEBUG); + } else if(logLevel.equals(INFO)) { + logger.setLevel(Level.INFO); + } else if(logLevel.equals(WARN)) { + logger.setLevel(Level.WARN); + } else if(logLevel.equals(ERROR)) { + logger.setLevel(Level.ERROR); + } else if(logLevel.equals(TRACE)) { + logger.setLevel(Level.TRACE); + } else { + logger.setLevel(Level.DEBUG); + } + loggers.put(loggerName, fileLogger); +// Logger fileLogger = loggers.get(loggerName); +// if(fileLogger != null) +// fileLogger.setLoggerImpl(logger); + } catch (Exception e) { + System.err.println("@@ Logger Configure Error.==================="); + System.err.println("@@ addFileAppender | " + loggerName + " | " + e.getMessage() ); + logger = null; + } + + return logger; + } + + /** + * 1. 기능 : logback의 FileAppender를 추가 + * 2. 처리 개요 : + * - logback API를 통해 FileAppender를 추가 + * 3. 주의사항 + * + * @exception + **/ + public static RollingFileAppender addFileAppender(String appenderName) { + + RollingFileAppender appender = null; + + try { + PropManager pmanager = PropManager.getInstance(); + props = pmanager.getProperties(appenderName); + + + String logDirectory = props.getProperty(APPENDER_LOG_DIRECOTRY); + if(logDirectory==null || logDirectory.equals("")) { + throw new RuntimeException("RECEAICUL004"); + } + String datePattern = props.getProperty(APPENDER_DATE_PATTERN); + if(datePattern==null || datePattern.equals("")) { + throw new RuntimeException("RECEAICUL008"); + } + if(datePattern.equals("'-'yyyy.MM.dd")){ + datePattern = "-%d{yyyy.MM.dd}"; + } + String sMaxBackupIndex =props.getProperty(MAX_BACKUP_INDEX); + + int maxBackupIndex = 0; + try{ + maxBackupIndex = Integer.parseInt(sMaxBackupIndex); + }catch(Exception e) { + maxBackupIndex = 60; + } + + String localServer = System.getProperty("inst.Name"); + appender = new RollingFileAppender(); + String logFile = props.getProperty(APPENDER_LOG_FILENAME); + TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy(); + rollingPolicy.setFileNamePattern( logDirectory + localServer + File.separator + logFile + datePattern); + rollingPolicy.setContext( (LoggerContext) LoggerFactory.getILoggerFactory() ); + rollingPolicy.setParent(appender); + rollingPolicy.setMaxHistory(maxBackupIndex); + rollingPolicy.start(); + + appender.setFile( logDirectory + localServer + File.separator + logFile ); + appender.setRollingPolicy( rollingPolicy ); + try { + String append = props.getProperty(APPENDER_FILE_APPEND); + appender.setAppend(new Boolean(append).booleanValue()); + } catch(Exception e) { + appender.setAppend(true); + } + appender.setContext( (LoggerContext) LoggerFactory.getILoggerFactory() ); + appender.setName(appenderName); + + } catch (Exception e) { + System.err.println("@@ Logger Configure Error.==================="); + System.err.println("@@ addFileAppender | " + appenderName + " | " + e.getMessage() ); + appender = null; + } + + return appender; + } + + static public synchronized void reloadLogLevel(String loggerName) { + try { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + Properties props = PropManager.getInstance().getProperties(loggerName); + if( props == null ) + return; + + String logLevel = props.getProperty(LOGGER_LEVEL); + if(lc != null) { + Level level = Level.ERROR; + if ("DEBUG".equals(logLevel)){ + level = Level.DEBUG; + }else if ("INFO".equals(logLevel)){ + level = Level.INFO; + }else if ("WARN".equals(logLevel)){ + level = Level.WARN; + }else if ("ERROR".equals(logLevel)){ + level = Level.ERROR; + } + lc.getLogger(loggerName).setLevel(level); + } + } + catch (Exception e) { + System.err.println("@@ Logger ReloadLevel Error.==================="); + } + } + + /** + * 1. 기능 : Banner 형태의 로그를 출력 + * 2. 처리 개요 : + * - Banner 형태의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @exception + **/ + public void banner(Object msg) { + try { + this.loggerImpl.debug("==========================================================="); + this.loggerImpl.debug(msg.toString()); + this.loggerImpl.debug("==========================================================="); + } catch (Throwable t) { + printOut(t, msg); + } + } + + /** + * 1. 기능 : debug Level의 로그를 출력 + * 2. 처리 개요 : + * - debug Level의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @exception + **/ + public void debug(Object msg) { + try { + this.loggerImpl.debug(msg.toString()); + } catch (Throwable t) { + printOut(t, msg); + } + } + + /** + * 1. 기능 : error Level의 로그를 출력 + * 2. 처리 개요 : + * - error Level의 로그를 출력 (ErrorCode를 사용할 경우) + * 3. 주의사항 + * + * @param code String + * @param msg Object + * @exception + **/ + public void debug(String code, Object msg) { + try { + this.loggerImpl.debug(format(code,msg)); + } catch (Throwable t) { + printOut(t, msg); + } + } + + /** + * 1. 기능 : info Level의 로그를 출력 + * 2. 처리 개요 : + * - info Level의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @exception + **/ + public void info(Object msg) { + try { + this.loggerImpl.info(msg.toString()); + } catch (Throwable t) { + printOut(t, msg); + } + } + + /** + * 1. 기능 : error Level의 로그를 출력 + * 2. 처리 개요 : + * - error Level의 로그를 출력 (ErrorCode를 사용할 경우) + * 3. 주의사항 + * + * @param code String + * @param msg Object + * @exception + **/ + public void info(String code, Object msg) { + try { + this.loggerImpl.info("==========================================================="); + this.loggerImpl.info(format(code,msg)); + this.loggerImpl.info("==========================================================="); + } catch (Throwable t) { + printOut(t, msg); + } + } + + + + /** + * 1. 기능 : warn Level의 로그를 출력 + * 2. 처리 개요 : + * - warn Level의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @exception + **/ + public void warn(Object msg) { + try { + this.loggerImpl.warn(msg.toString()); + } catch (Throwable t) { + printOut(t, msg); + } + } + + /** + * 1. 기능 : warn Level의 로그를 출력 + * 2. 처리 개요 : + * - warn Level의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @param t Throwable + * @exception + **/ + public void warn(Object msg, Throwable t) { + try { + this.loggerImpl.warn(msg.toString(), t); + } catch (Throwable th) { + printOut(t, th, msg); + } + } + /** + * 1. 기능 : error Level의 로그를 출력 + * 2. 처리 개요 : + * - error Level의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @exception + **/ + public void error(Object msg) { + try { + this.loggerImpl.error("==========================================================="); + this.loggerImpl.error(msg.toString()); + this.loggerImpl.error("==========================================================="); + } catch (Throwable t) { + printOut(t, msg); + } + } + + /** + * 1. 기능 : error Level의 로그를 출력 + * 2. 처리 개요 : + * - error Level의 로그를 출력 (ErrorCode를 사용할 경우) + * 3. 주의사항 + * + * @param code String + * @param msg Object + * @exception + **/ + public void error(String code, Object msg) { + try { + this.loggerImpl.error("==========================================================="); + this.loggerImpl.error(format(code,msg)); + this.loggerImpl.error("==========================================================="); + } catch (Throwable t) { + printOut(t, msg); + } + } + /** + * 1. 기능 : error Level의 로그를 출력 + * 2. 처리 개요 : + * - error Level의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @param t Throwable + * @exception + **/ + public void error(String msg, Throwable t) { + try { + this.loggerImpl.error("==========================================================="); + this.loggerImpl.error(msg, t); + this.loggerImpl.error("==========================================================="); + } catch (Throwable th) { + printOut(t, th, msg); + } + } + + /** + * 1. 기능 : error Level의 로그를 출력 + * 2. 처리 개요 : + * - error Level의 로그를 출력 (ErrorCode를 사용할 경우) + * 3. 주의사항 + * + * @param code String + * @param msg Object + * @param t Throwable + * @exception + **/ + public void error(String code, Object msg, Throwable t) { + try { + this.loggerImpl.error("==========================================================="); + this.loggerImpl.error(format(code,msg), t); + this.loggerImpl.error("==========================================================="); + } catch (Throwable th) { + printOut(t, th, msg); + } + } + /** + * 1. 기능 : fatal Level의 로그를 출력 + * 2. 처리 개요 : + * - fatal Level의 로그를 출력 + * 3. 주의사항 + * + * @param msg Object + * @exception + **/ + public void fatal(Object msg) { + error(msg); + } + + /** + * 1. 기능 : ErrorCode와 메시지의 출력 포맷을 정의 + * 2. 처리 개요 : + * - ErrorCode와 메시지의 출력 포맷을 정의 + * 3. 주의사항 + * + * @param code String + * @param msg Object + * @exception + **/ + private String format(String code, Object msg) { + StringBuffer sb = new StringBuffer(); + sb.append("[").append(code).append("]") + .append(" ").append(msg); + + return sb.toString(); + } + /** + * 1. 기능 : debug Level의 로그를 출력 가능여부 확인 + * 2. 처리 개요 : + * - debug Level의 로그를 출력 가능여부 확인 + * 3. 주의사항 + * + * @return boolean + * @exception + **/ + public boolean isWarnEnabled() { + return this.loggerImpl.isWarnEnabled(); + } + /** + * 1. 기능 : warn Level의 로그를 출력 가능여부 확인 + * 2. 처리 개요 : + * - warn Level의 로그를 출력 가능여부 확인 + * 3. 주의사항 + * + * @return boolean + * @exception + **/ + public boolean isDebugEnabled() { + return this.loggerImpl.isDebugEnabled(); + } + /** + * 1. 기능 : info Level의 로그를 출력 가능여부 확인 + * 2. 처리 개요 : + * - info Level의 로그를 출력 가능여부 확인 + * 3. 주의사항 + * + * @return boolean + * @exception + **/ + public boolean isInfoEnabled() { + return this.loggerImpl.isInfoEnabled(); + } + + + /** + * 1. 기능 : Log4j를 통해 로그를 남길 수 없는 경우 표준출력 제공 + * 2. 처리 개요 : + * - Log4j를 통해 로그를 남길 수 없는 경우 표준출력 제공 + * 3. 주의사항 + * + * @param t Throwable + * @param msg Object + * @exception + **/ + private void printOut(Throwable t, Object msg) { + System.out.println("can't write to log file!! Because of " + t); + System.out.println("the message will be printed to System.out"); + System.out.println(msg); + } + + /** + * 1. 기능 : Log4j를 통해 로그를 남길 수 없는 경우 표준출력 제공 + * 2. 처리 개요 : + * - Log4j를 통해 로그를 남길 수 없는 경우 표준출력 제공 + * 3. 주의사항 + * + * @param t Throwable + * @param th Throwable + * @param msg Object + * @exception + **/ + private void printOut(Throwable t, Throwable th, Object msg) { + System.out.println("can't write to log file!! Because of " + t); + System.out.println("the message will be printed to System.out"); + System.out.println(th); + System.out.println(msg); + } + + /* + debug(1000) : debug, info, warn, error, fatal + info (2000) : info, warn, error, fatal + warn (3000) : warn, error, fatal + error(4000) : error, fatal + fatal(5000) : fatal + + if(logger.isError) logger.error(); + */ + public boolean isDebug() { + return this.loggerImpl.isDebugEnabled(); + } + public boolean isInfo() { + return this.loggerImpl.isInfoEnabled(); + } + public boolean isWarn() { + return this.loggerImpl.isWarnEnabled(); + } + public boolean isError() { + return this.loggerImpl.isErrorEnabled(); + } + public static void addInstLog(BatchDoc batchDoc) { + // TODO Auto-generated method stub + Logger logger = Logger.getLogger(LOGGER_DEFAULT); + batchDoc.setLogger(Logger.getLogger(Logger.LOGGER_DEFAULT)); + try { + // 기관별 로그 설정 확인 + String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode(); + + Properties instInfo = PropManager.getInstance().getProperties( + "TelegramInfo{" + processCode + "_" + institutionCode + "}"); + + // 프라퍼티가 없는 경우 + if (instInfo == null) { + return; + } + + String instLog = instInfo.getProperty(LogKeys.INST_LOG); + + logger.debug("instlog processCode=["+processCode+"],institutionCode=["+institutionCode+"], instLog=["+instLog+"]"); + + if (!"Y".equalsIgnoreCase(instLog)) { + return; + } + + String appenderName = processCode + "_" + institutionCode; + String loggerName = "INST_" + appenderName; + + final LoggerContext ctx =(LoggerContext) LoggerFactory.getILoggerFactory(); + + createBapFileAppender(LogKeys.APPENDER_INST, appenderName, processCode, institutionCode); + + batchDoc.setLogger(Logger.getLogger(loggerName)); + } catch (Exception e) { + logger.error("BatchDoc = " + batchDoc, e); + } + } + + public static void createBapFileAppender(String appenderPropertiesGroup, String appenderName, String processCode, String institutionCode) { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + try { + Properties props = PropManager.getInstance().getProperties(appenderPropertiesGroup); + if (props == null) { + if(logger != null) + logger.error("★★★★★ '" + appenderPropertiesGroup + "' FileAppender 프라퍼티 정보가 없습니다. ★★★★★"); + return; + } + + // 로그파일 저장 디렉토리 절대경로 + String logDirectory = props.getProperty(APPENDER_LOG_DIRECOTRY); + if (logDirectory == null || logDirectory.equals("")) { + if(logger != null) + logger.error("★★★★★ '" + appenderPropertiesGroup + "' FileAppender 프라퍼티의 디렉토리 정보가 없습니다. ★★★★★"); + return; + // throw new Exception("BECEAICUL004"); + } + + String loggerName = "INST_" + appenderName; + // 로그파일 명 + String logFilename = institutionCode + ".log"; + + // 로그파일 날자별 생성 규칙 + String datePattern = props.getProperty(APPENDER_DATE_PATTERN, "-%d{yyyy.MM.dd}"); + + // 로그 패턴 문자열 + String patternLayout = props.getProperty(APPENDER_PATTERN_LAYOUT, "[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5p %F[%L] %m%n"); + + // 로그파일 로그Append 여부 + String fileAppend = props.getProperty(APPENDER_FILE_APPEND, "true"); + + String maxBackupIndex = props.getProperty(MAX_BACKUP_INDEX); + if(logger != null) + logger.info("patternLayout = " + patternLayout); + try { + Integer.parseInt(maxBackupIndex); + } catch (Exception e) { + maxBackupIndex = "30"; + } + + // 로그 파일 갯수 + String logFileCount = props.getProperty(LOG_FILE_COUNT, "100"); + try { + Integer.parseInt(logFileCount); + } catch (Exception e) { + if(logger != null) + logger.error("{" + LOG_FILE_COUNT +"} = {"+ logFileCount +"}" ); + } + // 로그 파일 크기 + String fileSize = props.getProperty(FILE_SIZE, "200M"); + + + String localServer = EAIServerManager.getInstance().getLocalServerName(); + String logPath = logDirectory.replaceAll(Pattern.quote("${inst.name}"), localServer); + + if (!logPath.endsWith(File.separator)) { + logPath += File.separator; + } + + logPath += processCode + File.separator; + + File dir = new File(logPath); + + if (!dir.exists()) { + dir.mkdir(); + } + File f = new File(dir, logFilename); + if (!f.exists()) { + File parent = f.getParentFile(); + if (parent != null && !parent.exists()) { + parent.mkdir(); + } + } + RollingFileAppender appender = new RollingFileAppender(); + TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy(); + rollingPolicy.setFileNamePattern( logPath + logFilename + datePattern); + rollingPolicy.setContext( (LoggerContext) LoggerFactory.getILoggerFactory()); + rollingPolicy.setParent(appender); + rollingPolicy.setMaxHistory(Integer.parseInt(maxBackupIndex)); + rollingPolicy.start(); + try { + appender.setAppend(new Boolean(fileAppend).booleanValue()); + } catch(Exception e) { + appender.setAppend(true); + } + + appender.setFile( logPath + logFilename ); + appender.setRollingPolicy( rollingPolicy ); + + try { + appender.setAppend(new Boolean(fileAppend).booleanValue()); + } catch(Exception e) { + appender.setAppend(true); + } + + appender.setContext( (LoggerContext) LoggerFactory.getILoggerFactory()); + appender.setName(appenderName); + + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + CustomPatternLayoutEncoder fple = new CustomPatternLayoutEncoder(); + fple.setContext( lc ); + + fple.setPattern( patternLayout ); + + String encoding ="EUC-KR"; + if (StringUtils.isNotBlank(encoding)) { + fple.setCharset(Charset.forName(encoding)); + } + + fple.start(); + + appender.setEncoder( fple ); + appender.start(); + + ch.qos.logback.classic.Logger instLogger = addLogger(loggerName); + if(instLogger == null) { + if(logger != null) + logger.debug(" - 기관 배치 파일로거 '"+ loggerName +"' Appender 생성 실패."); + return; + } + + instLogger.detachAndStopAllAppenders(); + instLogger.addAppender(appender); + + if(logger != null) + logger.debug(" - 배치 파일로거 '"+ appenderName +"' Appender 생성됨."); + + + if(logger != null) + logger.info(" - 배치 파일로거 '" + appenderName + "' Appender 생성됨."); + } catch (Exception ex) { + if(logger != null) + logger.error("Create Inst Logger Fail" + ex.getMessage()); + } + } + +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/NullControl.java b/src/com/eactive/eai/common/util/NullControl.java new file mode 100644 index 0000000..0babf5d --- /dev/null +++ b/src/com/eactive/eai/common/util/NullControl.java @@ -0,0 +1,61 @@ +package com.eactive.eai.common.util; + + +/** + * 1. 기능 : Date, Time 관련 Utility Method 정의 + * 2. 처리 개요 : + * + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : + * @since : + */ +public final class NullControl { + + private NullControl() + {} + + /** + * 1. 기능 : Null값을 공백으로 변경 + * 2. 처리 개요 : + * - ""나 Null를 입력받아 SPACE로 변환한다. + * 3. 주의사항 + * + * @param "", Null + * @return String + * @exception + **/ + public static String addSpace(String val) + { + if(val == null || val.equals("")){ + val = " "; + } + + return val; + } + + /** + * 1. 기능 : 입력값을 트림하여 화이트스페이스를 없앤다. + * 2. 처리 개요 : + * - 입력받은 값을 트림하여 리턴한다. + * 3. 주의사항 + * + * @param "", Null + * @return String + * @exception + **/ + + public static String trimSpace(String val) + { + if(val == null || val.equals("")){ + val = ""; // ""나 Null을 체크하여 트림하여 에러가 발생하지 않도록 한다.. + }else{ + val = val.trim(); + } + + return val; + } + +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/SecureUtil.java b/src/com/eactive/eai/common/util/SecureUtil.java new file mode 100644 index 0000000..2b7b28b --- /dev/null +++ b/src/com/eactive/eai/common/util/SecureUtil.java @@ -0,0 +1,190 @@ +package com.eactive.eai.common.util; + + + +/** +* 1. 기능 : 보안 관련 Utility 제공 +* 2. 처리 개요 : +* - 보안관련 메소드 구현 +* 3. 주의사항 +* +* @author : +* @version : v 1.0.0 +* @see : +* @since : +* : +*/ +/** + * @author Administrator + * + */ +/** + * @author Administrator + * + */ +public final class SecureUtil { + + /** + * Private 생성자 + * Instance를 생성하지 못함 + */ + private SecureUtil() + { + + } + + + /** + * Path Manipulation 보안취약점 필터 + * + * @param sInvalid + * @return + */ + public static String getPMFilter(String sInvalid) { + String sValid = sInvalid; + + if (sValid == null || sValid.equals("")) + return ""; + + sValid = sValid.replaceAll("\\.\\./", ""); + return sValid; + } + + + /** + * XSS 보안취약점 필터 + * + * @param sInvalid + * @return + */ + public static String getXSSFilter(String sInvalid) { + String sValid = sInvalid; + if (sInvalid == null || sInvalid.equals("")) { + return ""; + } + sValid = sValid.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); + sValid = sValid.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;"); + sValid = sValid.replaceAll("'", "& #39;"); + sValid = sValid.replaceAll("eval\\((.*)\\)", ""); + sValid = sValid.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); + sValid = sValid.replaceAll("script", ""); + return sValid; + } + + /** + * 1. 기능 : SQL Injection 보안취약점 필터 + * 2. 처리 개요 : + * - sql 값을 filter를 한다. + * 3. 주의사항 + * @param value + * @return + */ + public static String getSQLInjectionFilter(String sInvalid){ + String sValid = sInvalid; + if (sValid == null || sValid.equals("")) + return ""; + + sValid = sValid.replaceAll(" (?i)or ", ""); + sValid = sValid.replaceAll(" (?i)and ", ""); + sValid = sValid.replaceAll(" (?i)select ", ""); + sValid = sValid.replaceAll(" (?i)delete ", ""); + sValid = sValid.replaceAll(" (?i)insert ", ""); + sValid = sValid.replaceAll(";", ""); + sValid = sValid.replaceAll(":", ""); + sValid = sValid.replaceAll("--", ""); + sValid = sValid.replaceAll("\\\\", ""); + sValid = sValid.replaceAll("\'", ""); + sValid = sValid.replaceAll("'", ""); + sValid = sValid.replaceAll("-", ""); + sValid = sValid.replaceAll("[.]", ""); + sValid = sValid.replaceAll("[(]", ""); + sValid = sValid.replaceAll("[)]", ""); + sValid = sValid.replaceAll("\"", ""); + + return sValid; + } + + /** + * Header Manipulation 보안취약점 필터 + * + * @param sInvalid + * @return + */ + public static String getHMFilter(String sInvalid) { + String sValid = sInvalid; + + if (sValid == null || sValid.equals("")) + return ""; + + sValid = sValid.replaceAll("\\n", ""); + sValid = sValid.replaceAll("\\r", ""); + return sValid; + } + + + + /** + * Dangerous File Inclusion 보안취약점 필터 + * + * @param sInvalid + * @return + */ + public static String getDFIFilter(String sInvalid) { + String sValid = sInvalid; + + if (sValid == null || sValid.length() < 1) + return ""; + + sValid = sValid.replaceAll("\\.\\./|\\./|\\|:|\\*|\"|<|>", ""); + + return sValid; + } + + /** + * Command Injection 보안취약점 필터 + * + * @param sInvalid + * @return + */ + public static String getCIFilter(String sInvalid) { + String sValid = sInvalid; + + if (sValid == null || sValid.equals("")) + return ""; + + sValid = sValid.replaceAll("&", ""); + sValid = sValid.replaceAll("&", ""); + sValid = sValid.replaceAll("&&", ""); + sValid = sValid.replaceAll("|", ""); + sValid = sValid.replaceAll("||", ""); + sValid = sValid.replaceAll(";", ""); + sValid = sValid.replaceAll("\\.\\.", ""); + + return sValid; + } + + /** + * Log Forging 보안취약점 필터 + * + * @param sInvalid + * @return + */ + public static String getLFFilter(String sInvalid) { + String sValid = sInvalid; + + if (sValid == null || sValid.equals("")) + return ""; + + sValid = sValid.replaceAll("\\r", ""); + sValid = sValid.replaceAll("\\n", ""); + sValid = sValid.replaceAll("DEBUG", ""); + sValid = sValid.replaceAll("WARN", ""); + sValid = sValid.replaceAll("INFO", ""); + sValid = sValid.replaceAll("FATAL", ""); + sValid = sValid.replaceAll("ERROR", ""); + + return sValid; + } + + +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/Seed.java b/src/com/eactive/eai/common/util/Seed.java new file mode 100644 index 0000000..7097b12 --- /dev/null +++ b/src/com/eactive/eai/common/util/Seed.java @@ -0,0 +1,78 @@ +package com.eactive.eai.common.util; + +/** + * 1.16Byte Server Key를 셋팅한다. + * 2.샘플을 보고 사용한다. + * + */ + +public class Seed { + + public static void main(String[] args) throws Exception { + //System.out.println("SEED Crypt Sample"); + + String[] text = {"1410466"}; + //String text = "테스트_\t/\\1234!@#$<>?_+|"; + // 초기문자 확인 + + // 2.암호화 + for (int inx = 0; inx < text.length; inx++) { + String encryptStr = encrypt(text[inx] ); + System.out.println(text[inx] + " " + encryptStr); + } + String[] codes = {"CEB,CIB,CAR,CUM,CAG,CMB,CTM,CAT,CFD", + "LCE,LRA,LMC,LAC,LPC,LMN,LEN,LCI", + "LEN ", + "LRA,LMC,LAC,LPC,LEN,VMM,VMR,VPR,VBL,VST,VAC,VAP ", + "LRA,LMC,LAC,LPC,LEN,VMM,VMR,VPR,VBL,VST,VAC,VAP ", + "LRA,LMC,LAC,LPC,LEN,VMM,VMR,VPR,VBL,VST,VAC,VAP ", + "LRA,LMC,LAC,LPC,LEN,VMM,VMR,VPR,VBL,VST,VAC,VAP ", + "VMM,VMR,VPR,VBL,VST,VAC,VAP ", + "GDA, GLM, GRP, GST "}; + + for (int inx = 0; inx < text.length; inx++) { + String[] idCode = codes[inx].split(","); + for (int jnx = 0; jnx < idCode.length; jnx++) { + System.out.println("INSERT INTO TSEAIRM06 (USERID, BZWKDSTCD) VALUES ('" +text[inx] + "', '"+idCode[jnx].replaceAll(" ", "")+"');" ); + } + } + + for (int inx = 0; inx < text.length; inx++) { + String[] idCode = codes[inx].split(","); + for (int jnx = 0; jnx < idCode.length; jnx++) { + System.out.println("INSERT INTO TSEAIRM06 (USERID, EAIBZWKDSTCD) VALUES ('" +text[inx] + "', '"+idCode[jnx].replaceAll(" ", "")+"');" ); + } + } + + } + + public static String encrypt(String planText) throws Exception { + SeedCipher seed = new SeedCipher(); + + String key = "ABCEaicd1234_+|>\n";// 16Byte Server Key + // 1.값셋팅 + String text = planText;//2Byte이상의 문자 취 + + // 2.암호화 + byte[] encryptSeedBytes = seed.encrypt(text, key.getBytes()); + + char[] encryptSeedChars = Base64Coder.encode(encryptSeedBytes); + String encryptText = new String(encryptSeedChars); + + return encryptText; + } + + public static String decrypt(String encryptText) throws Exception { + SeedCipher seed = new SeedCipher(); + + String key = "ABCEaicd1234_+|>\n";// 16Byte Server Key + + // 3.복호화 + byte[] encryptBytes = Base64Coder.decode(encryptText); + byte[] decryptSeedBytes = seed.decrypt(encryptBytes, key.getBytes()); + String decryptText = new String(decryptSeedBytes); + + // DeCrypt 확인 + return decryptText; + } +} diff --git a/src/com/eactive/eai/common/util/SeedCipher.java b/src/com/eactive/eai/common/util/SeedCipher.java new file mode 100644 index 0000000..0fb14fe --- /dev/null +++ b/src/com/eactive/eai/common/util/SeedCipher.java @@ -0,0 +1,722 @@ +package com.eactive.eai.common.util; + +import java.io.UnsupportedEncodingException; + +/** + * Seed 블럭암호 API
+ * 한국정보보호진흥원에서 제공하는 Java API를 조금 수정 함.
+ * Padding은 ANSI X.923을 사용 함. + * + */ + +public class SeedCipher { + + private int SS0[] = { 0x2989a1a8, 0x5858184, 0x16c6d2d4, 0x13c3d3d0, + 0x14445054, 0x1d0d111c, 0x2c8ca0ac, 0x25052124, 0x1d4d515c, + 0x3434340, 0x18081018, 0x1e0e121c, 0x11415150, 0x3cccf0fc, + 0xacac2c8, 0x23436360, 0x28082028, 0x4444044, 0x20002020, + 0x1d8d919c, 0x20c0e0e0, 0x22c2e2e0, 0x8c8c0c8, 0x17071314, + 0x2585a1a4, 0xf8f838c, 0x3030300, 0x3b4b7378, 0x3b8bb3b8, + 0x13031310, 0x12c2d2d0, 0x2ecee2ec, 0x30407070, 0xc8c808c, + 0x3f0f333c, 0x2888a0a8, 0x32023230, 0x1dcdd1dc, 0x36c6f2f4, + 0x34447074, 0x2ccce0ec, 0x15859194, 0xb0b0308, 0x17475354, + 0x1c4c505c, 0x1b4b5358, 0x3d8db1bc, 0x1010100, 0x24042024, + 0x1c0c101c, 0x33437370, 0x18889098, 0x10001010, 0xcccc0cc, + 0x32c2f2f0, 0x19c9d1d8, 0x2c0c202c, 0x27c7e3e4, 0x32427270, + 0x3838380, 0x1b8b9398, 0x11c1d1d0, 0x6868284, 0x9c9c1c8, + 0x20406060, 0x10405050, 0x2383a3a0, 0x2bcbe3e8, 0xd0d010c, + 0x3686b2b4, 0x1e8e929c, 0xf4f434c, 0x3787b3b4, 0x1a4a5258, + 0x6c6c2c4, 0x38487078, 0x2686a2a4, 0x12021210, 0x2f8fa3ac, + 0x15c5d1d4, 0x21416160, 0x3c3c3c0, 0x3484b0b4, 0x1414140, + 0x12425250, 0x3d4d717c, 0xd8d818c, 0x8080008, 0x1f0f131c, + 0x19899198, 0, 0x19091118, 0x4040004, 0x13435350, 0x37c7f3f4, + 0x21c1e1e0, 0x3dcdf1fc, 0x36467274, 0x2f0f232c, 0x27072324, + 0x3080b0b0, 0xb8b8388, 0xe0e020c, 0x2b8ba3a8, 0x2282a2a0, + 0x2e4e626c, 0x13839390, 0xd4d414c, 0x29496168, 0x3c4c707c, + 0x9090108, 0xa0a0208, 0x3f8fb3bc, 0x2fcfe3ec, 0x33c3f3f0, + 0x5c5c1c4, 0x7878384, 0x14041014, 0x3ecef2fc, 0x24446064, + 0x1eced2dc, 0x2e0e222c, 0xb4b4348, 0x1a0a1218, 0x6060204, + 0x21012120, 0x2b4b6368, 0x26466264, 0x2020200, 0x35c5f1f4, + 0x12829290, 0xa8a8288, 0xc0c000c, 0x3383b3b0, 0x3e4e727c, + 0x10c0d0d0, 0x3a4a7278, 0x7474344, 0x16869294, 0x25c5e1e4, + 0x26062224, 0x808080, 0x2d8da1ac, 0x1fcfd3dc, 0x2181a1a0, + 0x30003030, 0x37073334, 0x2e8ea2ac, 0x36063234, 0x15051114, + 0x22022220, 0x38083038, 0x34c4f0f4, 0x2787a3a4, 0x5454144, + 0xc4c404c, 0x1818180, 0x29c9e1e8, 0x4848084, 0x17879394, + 0x35053134, 0xbcbc3c8, 0xecec2cc, 0x3c0c303c, 0x31417170, + 0x11011110, 0x7c7c3c4, 0x9898188, 0x35457174, 0x3bcbf3f8, + 0x1acad2d8, 0x38c8f0f8, 0x14849094, 0x19495158, 0x2828280, + 0x4c4c0c4, 0x3fcff3fc, 0x9494148, 0x39093138, 0x27476364, 0xc0c0c0, + 0xfcfc3cc, 0x17c7d3d4, 0x3888b0b8, 0xf0f030c, 0xe8e828c, 0x2424240, + 0x23032320, 0x11819190, 0x2c4c606c, 0x1bcbd3d8, 0x2484a0a4, + 0x34043034, 0x31c1f1f0, 0x8484048, 0x2c2c2c0, 0x2f4f636c, + 0x3d0d313c, 0x2d0d212c, 0x404040, 0x3e8eb2bc, 0x3e0e323c, + 0x3c8cb0bc, 0x1c1c1c0, 0x2a8aa2a8, 0x3a8ab2b8, 0xe4e424c, + 0x15455154, 0x3b0b3338, 0x1cccd0dc, 0x28486068, 0x3f4f737c, + 0x1c8c909c, 0x18c8d0d8, 0xa4a4248, 0x16465254, 0x37477374, + 0x2080a0a0, 0x2dcde1ec, 0x6464244, 0x3585b1b4, 0x2b0b2328, + 0x25456164, 0x3acaf2f8, 0x23c3e3e0, 0x3989b1b8, 0x3181b1b0, + 0x1f8f939c, 0x1e4e525c, 0x39c9f1f8, 0x26c6e2e4, 0x3282b2b0, + 0x31013130, 0x2acae2e8, 0x2d4d616c, 0x1f4f535c, 0x24c4e0e4, + 0x30c0f0f0, 0xdcdc1cc, 0x8888088, 0x16061214, 0x3a0a3238, + 0x18485058, 0x14c4d0d4, 0x22426260, 0x29092128, 0x7070304, + 0x33033330, 0x28c8e0e8, 0x1b0b1318, 0x5050104, 0x39497178, + 0x10809090, 0x2a4a6268, 0x2a0a2228, 0x1a8a9298 }; + + private int SS1[] = { 0x38380830, 0xe828c8e0, 0x2c2d0d21, 0xa42686a2, + 0xcc0fcfc3, 0xdc1eced2, 0xb03383b3, 0xb83888b0, 0xac2f8fa3, + 0x60204060, 0x54154551, 0xc407c7c3, 0x44044440, 0x6c2f4f63, + 0x682b4b63, 0x581b4b53, 0xc003c3c3, 0x60224262, 0x30330333, + 0xb43585b1, 0x28290921, 0xa02080a0, 0xe022c2e2, 0xa42787a3, + 0xd013c3d3, 0x90118191, 0x10110111, 0x4060602, 0x1c1c0c10, + 0xbc3c8cb0, 0x34360632, 0x480b4b43, 0xec2fcfe3, 0x88088880, + 0x6c2c4c60, 0xa82888a0, 0x14170713, 0xc404c4c0, 0x14160612, + 0xf434c4f0, 0xc002c2c2, 0x44054541, 0xe021c1e1, 0xd416c6d2, + 0x3c3f0f33, 0x3c3d0d31, 0x8c0e8e82, 0x98188890, 0x28280820, + 0x4c0e4e42, 0xf436c6f2, 0x3c3e0e32, 0xa42585a1, 0xf839c9f1, + 0xc0d0d01, 0xdc1fcfd3, 0xd818c8d0, 0x282b0b23, 0x64264662, + 0x783a4a72, 0x24270723, 0x2c2f0f23, 0xf031c1f1, 0x70324272, + 0x40024242, 0xd414c4d0, 0x40014141, 0xc000c0c0, 0x70334373, + 0x64274763, 0xac2c8ca0, 0x880b8b83, 0xf437c7f3, 0xac2d8da1, + 0x80008080, 0x1c1f0f13, 0xc80acac2, 0x2c2c0c20, 0xa82a8aa2, + 0x34340430, 0xd012c2d2, 0x80b0b03, 0xec2ecee2, 0xe829c9e1, + 0x5c1d4d51, 0x94148490, 0x18180810, 0xf838c8f0, 0x54174753, + 0xac2e8ea2, 0x8080800, 0xc405c5c1, 0x10130313, 0xcc0dcdc1, + 0x84068682, 0xb83989b1, 0xfc3fcff3, 0x7c3d4d71, 0xc001c1c1, + 0x30310131, 0xf435c5f1, 0x880a8a82, 0x682a4a62, 0xb03181b1, + 0xd011c1d1, 0x20200020, 0xd417c7d3, 0x20202, 0x20220222, 0x4040400, + 0x68284860, 0x70314171, 0x4070703, 0xd81bcbd3, 0x9c1d8d91, + 0x98198991, 0x60214161, 0xbc3e8eb2, 0xe426c6e2, 0x58194951, + 0xdc1dcdd1, 0x50114151, 0x90108090, 0xdc1cccd0, 0x981a8a92, + 0xa02383a3, 0xa82b8ba3, 0xd010c0d0, 0x80018181, 0xc0f0f03, + 0x44074743, 0x181a0a12, 0xe023c3e3, 0xec2ccce0, 0x8c0d8d81, + 0xbc3f8fb3, 0x94168692, 0x783b4b73, 0x5c1c4c50, 0xa02282a2, + 0xa02181a1, 0x60234363, 0x20230323, 0x4c0d4d41, 0xc808c8c0, + 0x9c1e8e92, 0x9c1c8c90, 0x383a0a32, 0xc0c0c00, 0x2c2e0e22, + 0xb83a8ab2, 0x6c2e4e62, 0x9c1f8f93, 0x581a4a52, 0xf032c2f2, + 0x90128292, 0xf033c3f3, 0x48094941, 0x78384870, 0xcc0cccc0, + 0x14150511, 0xf83bcbf3, 0x70304070, 0x74354571, 0x7c3f4f73, + 0x34350531, 0x10100010, 0x30303, 0x64244460, 0x6c2d4d61, + 0xc406c6c2, 0x74344470, 0xd415c5d1, 0xb43484b0, 0xe82acae2, + 0x8090901, 0x74364672, 0x18190911, 0xfc3ecef2, 0x40004040, + 0x10120212, 0xe020c0e0, 0xbc3d8db1, 0x4050501, 0xf83acaf2, 0x10101, + 0xf030c0f0, 0x282a0a22, 0x5c1e4e52, 0xa82989a1, 0x54164652, + 0x40034343, 0x84058581, 0x14140410, 0x88098981, 0x981b8b93, + 0xb03080b0, 0xe425c5e1, 0x48084840, 0x78394971, 0x94178793, + 0xfc3cccf0, 0x1c1e0e12, 0x80028282, 0x20210121, 0x8c0c8c80, + 0x181b0b13, 0x5c1f4f53, 0x74374773, 0x54144450, 0xb03282b2, + 0x1c1d0d11, 0x24250521, 0x4c0f4f43, 0, 0x44064642, 0xec2dcde1, + 0x58184850, 0x50124252, 0xe82bcbe3, 0x7c3e4e72, 0xd81acad2, + 0xc809c9c1, 0xfc3dcdf1, 0x30300030, 0x94158591, 0x64254561, + 0x3c3c0c30, 0xb43686b2, 0xe424c4e0, 0xb83b8bb3, 0x7c3c4c70, + 0xc0e0e02, 0x50104050, 0x38390931, 0x24260622, 0x30320232, + 0x84048480, 0x68294961, 0x90138393, 0x34370733, 0xe427c7e3, + 0x24240420, 0xa42484a0, 0xc80bcbc3, 0x50134353, 0x80a0a02, + 0x84078783, 0xd819c9d1, 0x4c0c4c40, 0x80038383, 0x8c0f8f83, + 0xcc0ecec2, 0x383b0b33, 0x480a4a42, 0xb43787b3 }; + + private int SS2[] = { 0xa1a82989, 0x81840585, 0xd2d416c6, 0xd3d013c3, + 0x50541444, 0x111c1d0d, 0xa0ac2c8c, 0x21242505, 0x515c1d4d, + 0x43400343, 0x10181808, 0x121c1e0e, 0x51501141, 0xf0fc3ccc, + 0xc2c80aca, 0x63602343, 0x20282808, 0x40440444, 0x20202000, + 0x919c1d8d, 0xe0e020c0, 0xe2e022c2, 0xc0c808c8, 0x13141707, + 0xa1a42585, 0x838c0f8f, 0x3000303, 0x73783b4b, 0xb3b83b8b, + 0x13101303, 0xd2d012c2, 0xe2ec2ece, 0x70703040, 0x808c0c8c, + 0x333c3f0f, 0xa0a82888, 0x32303202, 0xd1dc1dcd, 0xf2f436c6, + 0x70743444, 0xe0ec2ccc, 0x91941585, 0x3080b0b, 0x53541747, + 0x505c1c4c, 0x53581b4b, 0xb1bc3d8d, 0x1000101, 0x20242404, + 0x101c1c0c, 0x73703343, 0x90981888, 0x10101000, 0xc0cc0ccc, + 0xf2f032c2, 0xd1d819c9, 0x202c2c0c, 0xe3e427c7, 0x72703242, + 0x83800383, 0x93981b8b, 0xd1d011c1, 0x82840686, 0xc1c809c9, + 0x60602040, 0x50501040, 0xa3a02383, 0xe3e82bcb, 0x10c0d0d, + 0xb2b43686, 0x929c1e8e, 0x434c0f4f, 0xb3b43787, 0x52581a4a, + 0xc2c406c6, 0x70783848, 0xa2a42686, 0x12101202, 0xa3ac2f8f, + 0xd1d415c5, 0x61602141, 0xc3c003c3, 0xb0b43484, 0x41400141, + 0x52501242, 0x717c3d4d, 0x818c0d8d, 0x80808, 0x131c1f0f, + 0x91981989, 0, 0x11181909, 0x40404, 0x53501343, 0xf3f437c7, + 0xe1e021c1, 0xf1fc3dcd, 0x72743646, 0x232c2f0f, 0x23242707, + 0xb0b03080, 0x83880b8b, 0x20c0e0e, 0xa3a82b8b, 0xa2a02282, + 0x626c2e4e, 0x93901383, 0x414c0d4d, 0x61682949, 0x707c3c4c, + 0x1080909, 0x2080a0a, 0xb3bc3f8f, 0xe3ec2fcf, 0xf3f033c3, + 0xc1c405c5, 0x83840787, 0x10141404, 0xf2fc3ece, 0x60642444, + 0xd2dc1ece, 0x222c2e0e, 0x43480b4b, 0x12181a0a, 0x2040606, + 0x21202101, 0x63682b4b, 0x62642646, 0x2000202, 0xf1f435c5, + 0x92901282, 0x82880a8a, 0xc0c0c, 0xb3b03383, 0x727c3e4e, + 0xd0d010c0, 0x72783a4a, 0x43440747, 0x92941686, 0xe1e425c5, + 0x22242606, 0x80800080, 0xa1ac2d8d, 0xd3dc1fcf, 0xa1a02181, + 0x30303000, 0x33343707, 0xa2ac2e8e, 0x32343606, 0x11141505, + 0x22202202, 0x30383808, 0xf0f434c4, 0xa3a42787, 0x41440545, + 0x404c0c4c, 0x81800181, 0xe1e829c9, 0x80840484, 0x93941787, + 0x31343505, 0xc3c80bcb, 0xc2cc0ece, 0x303c3c0c, 0x71703141, + 0x11101101, 0xc3c407c7, 0x81880989, 0x71743545, 0xf3f83bcb, + 0xd2d81aca, 0xf0f838c8, 0x90941484, 0x51581949, 0x82800282, + 0xc0c404c4, 0xf3fc3fcf, 0x41480949, 0x31383909, 0x63642747, + 0xc0c000c0, 0xc3cc0fcf, 0xd3d417c7, 0xb0b83888, 0x30c0f0f, + 0x828c0e8e, 0x42400242, 0x23202303, 0x91901181, 0x606c2c4c, + 0xd3d81bcb, 0xa0a42484, 0x30343404, 0xf1f031c1, 0x40480848, + 0xc2c002c2, 0x636c2f4f, 0x313c3d0d, 0x212c2d0d, 0x40400040, + 0xb2bc3e8e, 0x323c3e0e, 0xb0bc3c8c, 0xc1c001c1, 0xa2a82a8a, + 0xb2b83a8a, 0x424c0e4e, 0x51541545, 0x33383b0b, 0xd0dc1ccc, + 0x60682848, 0x737c3f4f, 0x909c1c8c, 0xd0d818c8, 0x42480a4a, + 0x52541646, 0x73743747, 0xa0a02080, 0xe1ec2dcd, 0x42440646, + 0xb1b43585, 0x23282b0b, 0x61642545, 0xf2f83aca, 0xe3e023c3, + 0xb1b83989, 0xb1b03181, 0x939c1f8f, 0x525c1e4e, 0xf1f839c9, + 0xe2e426c6, 0xb2b03282, 0x31303101, 0xe2e82aca, 0x616c2d4d, + 0x535c1f4f, 0xe0e424c4, 0xf0f030c0, 0xc1cc0dcd, 0x80880888, + 0x12141606, 0x32383a0a, 0x50581848, 0xd0d414c4, 0x62602242, + 0x21282909, 0x3040707, 0x33303303, 0xe0e828c8, 0x13181b0b, + 0x1040505, 0x71783949, 0x90901080, 0x62682a4a, 0x22282a0a, + 0x92981a8a }; + + private int SS3[] = { 0x8303838, 0xc8e0e828, 0xd212c2d, 0x86a2a426, + 0xcfc3cc0f, 0xced2dc1e, 0x83b3b033, 0x88b0b838, 0x8fa3ac2f, + 0x40606020, 0x45515415, 0xc7c3c407, 0x44404404, 0x4f636c2f, + 0x4b63682b, 0x4b53581b, 0xc3c3c003, 0x42626022, 0x3333033, + 0x85b1b435, 0x9212829, 0x80a0a020, 0xc2e2e022, 0x87a3a427, + 0xc3d3d013, 0x81919011, 0x1111011, 0x6020406, 0xc101c1c, + 0x8cb0bc3c, 0x6323436, 0x4b43480b, 0xcfe3ec2f, 0x88808808, + 0x4c606c2c, 0x88a0a828, 0x7131417, 0xc4c0c404, 0x6121416, + 0xc4f0f434, 0xc2c2c002, 0x45414405, 0xc1e1e021, 0xc6d2d416, + 0xf333c3f, 0xd313c3d, 0x8e828c0e, 0x88909818, 0x8202828, + 0x4e424c0e, 0xc6f2f436, 0xe323c3e, 0x85a1a425, 0xc9f1f839, + 0xd010c0d, 0xcfd3dc1f, 0xc8d0d818, 0xb23282b, 0x46626426, + 0x4a72783a, 0x7232427, 0xf232c2f, 0xc1f1f031, 0x42727032, + 0x42424002, 0xc4d0d414, 0x41414001, 0xc0c0c000, 0x43737033, + 0x47636427, 0x8ca0ac2c, 0x8b83880b, 0xc7f3f437, 0x8da1ac2d, + 0x80808000, 0xf131c1f, 0xcac2c80a, 0xc202c2c, 0x8aa2a82a, + 0x4303434, 0xc2d2d012, 0xb03080b, 0xcee2ec2e, 0xc9e1e829, + 0x4d515c1d, 0x84909414, 0x8101818, 0xc8f0f838, 0x47535417, + 0x8ea2ac2e, 0x8000808, 0xc5c1c405, 0x3131013, 0xcdc1cc0d, + 0x86828406, 0x89b1b839, 0xcff3fc3f, 0x4d717c3d, 0xc1c1c001, + 0x1313031, 0xc5f1f435, 0x8a82880a, 0x4a62682a, 0x81b1b031, + 0xc1d1d011, 0x202020, 0xc7d3d417, 0x2020002, 0x2222022, 0x4000404, + 0x48606828, 0x41717031, 0x7030407, 0xcbd3d81b, 0x8d919c1d, + 0x89919819, 0x41616021, 0x8eb2bc3e, 0xc6e2e426, 0x49515819, + 0xcdd1dc1d, 0x41515011, 0x80909010, 0xccd0dc1c, 0x8a92981a, + 0x83a3a023, 0x8ba3a82b, 0xc0d0d010, 0x81818001, 0xf030c0f, + 0x47434407, 0xa12181a, 0xc3e3e023, 0xcce0ec2c, 0x8d818c0d, + 0x8fb3bc3f, 0x86929416, 0x4b73783b, 0x4c505c1c, 0x82a2a022, + 0x81a1a021, 0x43636023, 0x3232023, 0x4d414c0d, 0xc8c0c808, + 0x8e929c1e, 0x8c909c1c, 0xa32383a, 0xc000c0c, 0xe222c2e, + 0x8ab2b83a, 0x4e626c2e, 0x8f939c1f, 0x4a52581a, 0xc2f2f032, + 0x82929012, 0xc3f3f033, 0x49414809, 0x48707838, 0xccc0cc0c, + 0x5111415, 0xcbf3f83b, 0x40707030, 0x45717435, 0x4f737c3f, + 0x5313435, 0x101010, 0x3030003, 0x44606424, 0x4d616c2d, 0xc6c2c406, + 0x44707434, 0xc5d1d415, 0x84b0b434, 0xcae2e82a, 0x9010809, + 0x46727436, 0x9111819, 0xcef2fc3e, 0x40404000, 0x2121012, + 0xc0e0e020, 0x8db1bc3d, 0x5010405, 0xcaf2f83a, 0x1010001, + 0xc0f0f030, 0xa22282a, 0x4e525c1e, 0x89a1a829, 0x46525416, + 0x43434003, 0x85818405, 0x4101414, 0x89818809, 0x8b93981b, + 0x80b0b030, 0xc5e1e425, 0x48404808, 0x49717839, 0x87939417, + 0xccf0fc3c, 0xe121c1e, 0x82828002, 0x1212021, 0x8c808c0c, + 0xb13181b, 0x4f535c1f, 0x47737437, 0x44505414, 0x82b2b032, + 0xd111c1d, 0x5212425, 0x4f434c0f, 0, 0x46424406, 0xcde1ec2d, + 0x48505818, 0x42525012, 0xcbe3e82b, 0x4e727c3e, 0xcad2d81a, + 0xc9c1c809, 0xcdf1fc3d, 0x303030, 0x85919415, 0x45616425, + 0xc303c3c, 0x86b2b436, 0xc4e0e424, 0x8bb3b83b, 0x4c707c3c, + 0xe020c0e, 0x40505010, 0x9313839, 0x6222426, 0x2323032, 0x84808404, + 0x49616829, 0x83939013, 0x7333437, 0xc7e3e427, 0x4202424, + 0x84a0a424, 0xcbc3c80b, 0x43535013, 0xa02080a, 0x87838407, + 0xc9d1d819, 0x4c404c0c, 0x83838003, 0x8f838c0f, 0xcec2cc0e, + 0xb33383b, 0x4a42480a, 0x87b3b437 }; + + private int KC[] = { 0x9e3779b9, 0x3c6ef373, 0x78dde6e6, 0xf1bbcdcc, + 0xe3779b99, 0xc6ef3733, 0x8dde6e67, 0x1bbcdccf, 0x3779b99e, + 0x6ef3733c, 0xdde6e678, 0xbbcdccf1, 0x779b99e3, 0xef3733c6, + 0xde6e678d, 0xbcdccf1b }; + + private boolean LITTLE = false; + private boolean ENDIAN = LITTLE; +// private final int NO_ROUNDS = 16; + + /** Seed Block Size (16byte) */ + private final int SEED_BLOCK_SIZE = 16; + + /** Padding Object */ + private CryptoPaddingImpl padding = null; + + public SeedCipher() { + padding = new AnsiX923Padding(); + } + + private int getB0(int A) { + return 0xff & A; + } + + private int getB1(int A) { + return 0xff & A >>> 8; + } + + private int getB2(int A) { + return 0xff & A >>> 16; + } + + private int getB3(int A) { + return 0xff & A >>> 24; + } + + private void EndianChange(int dws[]) { + dws[0] = dws[0] >>> 24 | dws[0] << 24 | dws[0] << 8 & 0xff0000 + | dws[0] >>> 8 & 0xff00; + } + + private int EndianChange(int dws) { + return dws >>> 24 | dws << 24 | dws << 8 & 0xff0000 | dws >>> 8 + & 0xff00; + } + + private void seedRound(int L0[], int L1[], int R0[], int R1[], int K[]) { + long T00 = 0L; + long T11 = 0L; + int T0 = R0[0] ^ K[0]; + int T1 = R1[0] ^ K[1]; + T1 ^= T0; + T00 = T0 >= 0 ? T0 : (T0 & 0x7fffffff) | 0xffffffff80000000L; + T1 = SS0[getB0(T1)] ^ SS1[getB1(T1)] ^ SS2[getB2(T1)] ^ SS3[getB3(T1)]; + T11 = T1 >= 0 ? T1 : (T1 & 0x7fffffff) | 0xffffffff80000000L; + T00 += T11; + T0 = SS0[getB0((int) T00)] ^ SS1[getB1((int) T00)] + ^ SS2[getB2((int) T00)] ^ SS3[getB3((int) T00)]; + T00 = T0 >= 0 ? T0 : (T0 & 0x7fffffff) | 0xffffffff80000000L; + T11 += T00; + T1 = SS0[getB0((int) T11)] ^ SS1[getB1((int) T11)] + ^ SS2[getB2((int) T11)] ^ SS3[getB3((int) T11)]; + T11 = T1 >= 0 ? T1 : (T1 & 0x7fffffff) | 0xffffffff80000000L; + T00 += T11; + L0[0] ^= (int) T00; + L1[0] ^= (int) T11; + } + + private void seedEncrypt(byte pbData[], int pdwRoundKey[], byte outData[]) { + int L0[] = new int[1]; + int L1[] = new int[1]; + int R0[] = new int[1]; + int R1[] = new int[1]; + L0[0] = 0; + L1[0] = 0; + R0[0] = 0; + R1[0] = 0; + int K[] = new int[2]; + int nCount = 0; + L0[0] = pbData[0] & 0xff; + L0[0] = L0[0] << 8 ^ pbData[1] & 0xff; + L0[0] = L0[0] << 8 ^ pbData[2] & 0xff; + L0[0] = L0[0] << 8 ^ pbData[3] & 0xff; + L1[0] = pbData[4] & 0xff; + L1[0] = L1[0] << 8 ^ pbData[5] & 0xff; + L1[0] = L1[0] << 8 ^ pbData[6] & 0xff; + L1[0] = L1[0] << 8 ^ pbData[7] & 0xff; + R0[0] = pbData[8] & 0xff; + R0[0] = R0[0] << 8 ^ pbData[9] & 0xff; + R0[0] = R0[0] << 8 ^ pbData[10] & 0xff; + R0[0] = R0[0] << 8 ^ pbData[11] & 0xff; + R1[0] = pbData[12] & 0xff; + R1[0] = R1[0] << 8 ^ pbData[13] & 0xff; + R1[0] = R1[0] << 8 ^ pbData[14] & 0xff; + R1[0] = R1[0] << 8 ^ pbData[15] & 0xff; + if (!ENDIAN) { + EndianChange(L0); + EndianChange(L1); + EndianChange(R0); + EndianChange(R1); + } + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + + //if (NO_ROUNDS == 16) + { + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(L0, L1, R0, R1, K); + K[0] = pdwRoundKey[nCount++]; + K[1] = pdwRoundKey[nCount++]; + seedRound(R0, R1, L0, L1, K); + } + + if (!ENDIAN) { + EndianChange(L0); + EndianChange(L1); + EndianChange(R0); + EndianChange(R1); + } + + for (int i = 0; i < 4; i++) { + outData[i] = (byte) (R0[0] >>> 8 * (3 - i) & 0xff); + outData[4 + i] = (byte) (R1[0] >>> 8 * (3 - i) & 0xff); + outData[8 + i] = (byte) (L0[0] >>> 8 * (3 - i) & 0xff); + outData[12 + i] = (byte) (L1[0] >>> 8 * (3 - i) & 0xff); + } + + } + + private void seedDecrypt(byte pbData[], int pdwRoundKey[], byte outData[]) { + int L0[] = new int[1]; + int L1[] = new int[1]; + int R0[] = new int[1]; + int R1[] = new int[1]; + int K[] = new int[2]; + L0[0] = 0; + L1[0] = 0; + R0[0] = 0; + R1[0] = 0; + int nCount = 31; + L0[0] = pbData[0] & 0xff; + L0[0] = L0[0] << 8 ^ pbData[1] & 0xff; + L0[0] = L0[0] << 8 ^ pbData[2] & 0xff; + L0[0] = L0[0] << 8 ^ pbData[3] & 0xff; + L1[0] = pbData[4] & 0xff; + L1[0] = L1[0] << 8 ^ pbData[5] & 0xff; + L1[0] = L1[0] << 8 ^ pbData[6] & 0xff; + L1[0] = L1[0] << 8 ^ pbData[7] & 0xff; + R0[0] = pbData[8] & 0xff; + R0[0] = R0[0] << 8 ^ pbData[9] & 0xff; + R0[0] = R0[0] << 8 ^ pbData[10] & 0xff; + R0[0] = R0[0] << 8 ^ pbData[11] & 0xff; + R1[0] = pbData[12] & 0xff; + R1[0] = R1[0] << 8 ^ pbData[13] & 0xff; + R1[0] = R1[0] << 8 ^ pbData[14] & 0xff; + R1[0] = R1[0] << 8 ^ pbData[15] & 0xff; + + if (!ENDIAN) { + EndianChange(L0); + EndianChange(L1); + EndianChange(R0); + EndianChange(R1); + } + + //if (NO_ROUNDS == 16) + { + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(R0, R1, L0, L1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(R0, R1, L0, L1, K); + } + + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(R0, R1, L0, L1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(R0, R1, L0, L1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(R0, R1, L0, L1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(R0, R1, L0, L1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(R0, R1, L0, L1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount--]; + seedRound(L0, L1, R0, R1, K); + K[1] = pdwRoundKey[nCount--]; + K[0] = pdwRoundKey[nCount]; + seedRound(R0, R1, L0, L1, K); + + if (!ENDIAN) { + EndianChange(L0); + EndianChange(L1); + EndianChange(R0); + EndianChange(R1); + } + + for (int i = 0; i < 4; i++) { + outData[i] = (byte) (R0[0] >>> 8 * (3 - i) & 0xff); + outData[4 + i] = (byte) (R1[0] >>> 8 * (3 - i) & 0xff); + outData[8 + i] = (byte) (L0[0] >>> 8 * (3 - i) & 0xff); + outData[12 + i] = (byte) (L1[0] >>> 8 * (3 - i) & 0xff); + } + + } + + private void EncRoundKeyUpdate0(int K[], int A[], int B[], int C[], + int D[], int Z) { + + int T0 = A[0]; + A[0] = A[0] >>> 8 ^ B[0] << 24; + B[0] = B[0] >>> 8 ^ T0 << 24; + int T00 = (A[0] + C[0]) - KC[Z]; + int T11 = (B[0] + KC[Z]) - D[0]; + K[0] = SS0[getB0(T00)] ^ SS1[getB1(T00)] ^ SS2[getB2(T00)] ^ SS3[getB3(T00)]; + K[1] = SS0[getB0(T11)] ^ SS1[getB1(T11)] ^ SS2[getB2(T11)] ^ SS3[getB3(T11)]; + } + + private void EncRoundKeyUpdate1(int K[], int A[], int B[], int C[], + int D[], int Z) { + + int T0 = C[0]; + C[0] = C[0] << 8 ^ D[0] >>> 24; + D[0] = D[0] << 8 ^ T0 >>> 24; + int T00 = (A[0] + C[0]) - KC[Z]; + int T11 = (B[0] + KC[Z]) - D[0]; + K[0] = SS0[getB0(T00)] ^ SS1[getB1(T00)] ^ SS2[getB2(T00)] ^ SS3[getB3(T00)]; + K[1] = SS0[getB0(T11)] ^ SS1[getB1(T11)] ^ SS2[getB2(T11)] ^ SS3[getB3(T11)]; + } + + private void seedEncRoundKey(int pdwRoundKey[], byte pbUserKey[]) { + int A[] = new int[1]; + int B[] = new int[1]; + int C[] = new int[1]; + int D[] = new int[1]; + int K[] = new int[2]; + int nCount = 2; + A[0] = pbUserKey[0] & 0xff; + A[0] = A[0] << 8 ^ pbUserKey[1] & 0xff; + A[0] = A[0] << 8 ^ pbUserKey[2] & 0xff; + A[0] = A[0] << 8 ^ pbUserKey[3] & 0xff; + B[0] = pbUserKey[4] & 0xff; + B[0] = B[0] << 8 ^ pbUserKey[5] & 0xff; + B[0] = B[0] << 8 ^ pbUserKey[6] & 0xff; + B[0] = B[0] << 8 ^ pbUserKey[7] & 0xff; + C[0] = pbUserKey[8] & 0xff; + C[0] = C[0] << 8 ^ pbUserKey[9] & 0xff; + C[0] = C[0] << 8 ^ pbUserKey[10] & 0xff; + C[0] = C[0] << 8 ^ pbUserKey[11] & 0xff; + D[0] = pbUserKey[12] & 0xff; + D[0] = D[0] << 8 ^ pbUserKey[13] & 0xff; + D[0] = D[0] << 8 ^ pbUserKey[14] & 0xff; + D[0] = D[0] << 8 ^ pbUserKey[15] & 0xff; + if (!ENDIAN) { + A[0] = EndianChange(A[0]); + B[0] = EndianChange(B[0]); + C[0] = EndianChange(C[0]); + D[0] = EndianChange(D[0]); + } + int T0 = (A[0] + C[0]) - KC[0]; + int T1 = (B[0] - D[0]) + KC[0]; + pdwRoundKey[0] = SS0[getB0(T0)] ^ SS1[getB1(T0)] ^ SS2[getB2(T0)] ^ SS3[getB3(T0)]; + pdwRoundKey[1] = SS0[getB0(T1)] ^ SS1[getB1(T1)] ^ SS2[getB2(T1)] ^ SS3[getB3(T1)]; + EncRoundKeyUpdate0(K, A, B, C, D, 1); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate1(K, A, B, C, D, 2); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate0(K, A, B, C, D, 3); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate1(K, A, B, C, D, 4); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate0(K, A, B, C, D, 5); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate1(K, A, B, C, D, 6); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate0(K, A, B, C, D, 7); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate1(K, A, B, C, D, 8); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate0(K, A, B, C, D, 9); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate1(K, A, B, C, D, 10); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate0(K, A, B, C, D, 11); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + //if (NO_ROUNDS == 16) + { + EncRoundKeyUpdate1(K, A, B, C, D, 12); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate0(K, A, B, C, D, 13); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate1(K, A, B, C, D, 14); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + EncRoundKeyUpdate0(K, A, B, C, D, 15); + pdwRoundKey[nCount++] = K[0]; + pdwRoundKey[nCount++] = K[1]; + } + } + + /** + * 한국정보보호진흥원 소스에 없는 추가 된 함수로 입력 받은 바이트 데이터를 암호화 하여 리턴한다. + * + * @param sbuffer + * String 평문 + * @param szKey + * byte[] key + * @return byte[] 암호화 된 데이터 + */ + public byte[] encrypt(byte[] sbuffer, byte szKey[]) { + int sRoundKey[] = new int[32]; + seedEncRoundKey(sRoundKey, szKey); + + byte[] inDataBuffer = padding.addPadding(sbuffer, SEED_BLOCK_SIZE); + byte[] encryptBytes = new byte[inDataBuffer.length]; + + int rt = inDataBuffer.length / SEED_BLOCK_SIZE; + for (int j = 0; j < rt; j++) { + byte sSource[] = new byte[SEED_BLOCK_SIZE]; + byte sTarget[] = new byte[SEED_BLOCK_SIZE]; + + System.arraycopy(inDataBuffer, (j * SEED_BLOCK_SIZE), sSource, 0, + SEED_BLOCK_SIZE); + seedEncrypt(sSource, sRoundKey, sTarget); + + System.arraycopy(sTarget, 0, encryptBytes, (j * SEED_BLOCK_SIZE), + sTarget.length); + } + + return encryptBytes; + } + + /** + * 한국정보보호진흥원 소스에 없는 추가 된 함수로 입력 받은 문자열을 암호화 하여 리턴한다. + * + * @param inData + * String 평문 + * @param szKey + * byte[] key + * @return byte[] 암호화 된 데이터 + */ + public byte[] encrypt(String inData, byte szKey[]) { + return encrypt(inData.getBytes(), szKey); + } + + /** + * 한국정보보호진흥원 소스에 없는 추가 된 함수로 입력 받은 문자열을 특정 Charset으로 변환하여 암호화 하여 리턴한다. + * + * @param inData + * String 평문 + * @param szKey + * byte[] key + * @param charset + * String String을 byte 데이터로 변환할때 사용할 charset + * @return byte[] 암호화 된 데이터 + */ + public byte[] encrypt(String inData, byte szKey[], String charset) + throws UnsupportedEncodingException { + + return encrypt(inData.getBytes(charset), szKey); + } + + /** + * 한국정보보호진흥원 소스에 없는 추가 된 함수로 암호화 된 바이트 데이터를 받아서 복호화한다. + * + * @param encryptBytes + * byte[] 암호화 된 바이트 데이터 + * @param szKey + * byte[] key + * @return byte[] 복호화 된 바이트 데이터 + */ + public byte[] decrypt(byte[] encryptBytes, byte[] szKey) { + int sRoundKey[] = new int[32]; + byte[] decryptBytes = new byte[encryptBytes.length]; + seedEncRoundKey(sRoundKey, szKey); + int rt = encryptBytes.length / SEED_BLOCK_SIZE; + + byte sSource[] = new byte[SEED_BLOCK_SIZE]; + byte sTarget[] = new byte[SEED_BLOCK_SIZE]; + for (int j = 0; j < rt; j++) { + System.arraycopy(encryptBytes, (j * SEED_BLOCK_SIZE), sSource, 0 ,SEED_BLOCK_SIZE); + seedDecrypt(sSource, sRoundKey, sTarget); + System.arraycopy(sTarget, 0, decryptBytes, (j * SEED_BLOCK_SIZE), SEED_BLOCK_SIZE); + } + + return padding.removePadding(decryptBytes, SEED_BLOCK_SIZE); + } + + /** + * 한국정보보호진흥원 소스에 없는 추가 된 함수로 암호화 된 바이트 데이터를 받아서 복호화하여 문자열로 반환한다. + * + * @param encryptBytes + * byte[] 암호화 된 바이트 데이터 + * @param szKey + * byte[] key + * @return String 복호화 문자열 + */ + public String decryptAsString(byte[] encryptBytes, byte[] szKey) { + return new String(decrypt(encryptBytes, szKey)); + } + + /** + * 한국정보보호진흥원 소스에 없는 추가 된 함수로 암호화 된 바이트 데이터를 받아서 복호화하여 지정한 charset으로 문자열로 + * 반환한다. + * + * @param encryptBytes + * byte[] 암호화 된 바이트 데이터 + * @param szKey + * byte[] key + * @param charset + * String 복호화 된 바이트 데이터를 문자열로 변환할 때 사용할 Charset + * @return String 복호화 문자열 + */ + public String decryptAsString(byte[] encryptBytes, byte[] szKey, + String charset) throws UnsupportedEncodingException { + + return new String(decrypt(encryptBytes, szKey), charset); + } + +} diff --git a/src/com/eactive/eai/common/util/ServiceLocator.java b/src/com/eactive/eai/common/util/ServiceLocator.java new file mode 100644 index 0000000..1f991af --- /dev/null +++ b/src/com/eactive/eai/common/util/ServiceLocator.java @@ -0,0 +1,242 @@ +package com.eactive.eai.common.util; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import javax.jms.Queue; +import javax.jms.QueueConnectionFactory; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; + +import com.eactive.eai.common.exception.ExceptionUtil; + +/** + * 1. 기능 : WAS의 각종 서비스를 레퍼런스를 얻어내는 공통 Class + * 2. 처리 개요 : + * * - + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + * : + */ +public class ServiceLocator { + /** Eai Logger */ +// static private Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + /** weblogic.jndi.WLInitialContextFactory */ + public final static String WEBLOGIC_INITIAL_CONTEXT_FACTORY = "weblogic.jndi.WLInitialContextFactory"; + + /** ServiceLocator singleton object */ + private static ServiceLocator instance; + + /** JNDI Context object */ + private InitialContext initial; + + /** caching을 위한 collection object */ + private Map cache; + + /** + * EaiMain start시 t3 url 초기화를 위해 호출된다
+ * t3 url을 초기화하고, ServiceLocator singleton object를 생성 초기화한다. + */ + /* + static public void init(String t3Url) { + try { + //WEBLOGIC_T3_URL = t3Url; + instance = new ServiceLocator(); + if (logger.isInfo()) logger.info("ServiceLocator#init() initailized..."); + } catch (ServiceLocatorException e) { + if (logger.isError()) logger.error("!! Cannot connect to WebLogic Server..."); + if (logger.isError()) logger.error("1. Check if WebLogic Server is alive."); + if (logger.isError()) logger.error("2. Check if t3Url is correct in config file(server.xml)."); + if (logger.isError()) logger.error(e.getMessage(), e); + //System.exit(1); + } + } + */ + + /** + * 1. 기능 : Constructor + * 2. 처리 개요 : + * - JNDI Context object를 생성 초기화하고, cache Map object를 생성 초기화한다. + * 3. 주의사항 + * + * @exception ServiceLocatorException + **/ + protected ServiceLocator() throws ServiceLocatorException { + try { + /* + Hashtable env = new Hashtable(); + env.put(Context.INITIAL_CONTEXT_FACTORY, WEBLOGIC_INITIAL_CONTEXT_FACTORY); + env.put(Context.PROVIDER_URL, WEBLOGIC_T3_URL); + initial = new InitialContext(env); + */ + initial = new InitialContext(); + + cache = Collections.synchronizedMap(new HashMap()); + + } catch (NamingException e) { +// throw new ServiceLocatorException(e); + throw new ServiceLocatorException(ExceptionUtil.getErrorCode(e,"RECEAICUL101")); + } catch (Exception e) { + // throw new ServiceLocatorException(e); + throw new ServiceLocatorException(ExceptionUtil.getErrorCode(e,"RECEAICUL102")); + } + } + + /** + * 1. 기능 : ServiceLocator object를 반환하는 factory method + * 2. 처리 개요 : + * - ServiceLocator object를 반환하는 factory method + * 3. 주의사항 + * + * @return ServiceLocator + * @exception + **/ + public static synchronized ServiceLocator getInstance() throws ServiceLocatorException { + if ( instance == null ) { + instance = new ServiceLocator(); + return instance; + } else { + return instance; + } + } + + /** + * 1. 기능 : 파라미터 name에 해당하는 DataSource를 lookup해 반환하는 method + * 2. 처리 개요 : + * - 파라미터 name에 해당하는 DataSource를 lookup해 반환하는 method + * 3. 주의사항 + * + * @param dataSourceName DataSource의 JNDI name + * @return DataSource JDBC DataSource object + * @exception ServiceLocatorException + **/ + public DataSource getDataSource(String dataSourceName) + throws ServiceLocatorException { + DataSource dataSource = null; + + try { + if (cache.containsKey(dataSourceName)) { + dataSource = (DataSource) cache.get(dataSourceName); + } else { + dataSource = (DataSource) initial.lookup(dataSourceName); + cache.put(dataSourceName,dataSource); + // already made connection pool + //throw new ServiceLocatorException("DataSource Name [" + dataSourceName + "] does not exist."); + } + } catch (Exception e) { + // throw new ServiceLocatorException(e); + throw new ServiceLocatorException(ExceptionUtil.getErrorCode(e,"RECEAICUL103")); + } + + return dataSource; + } + + public void putDataSource(String dataSourceName, DataSource dataSource) { + cache.put(dataSourceName, dataSource); + } + /** + * 1. 기능 : 파라미터 name에 해당하는 Remote 서버의 DataSource를 lookup해 반환하는 method + * 2. 처리 개요 : + * - 파라미터 name에 해당하는 Remote 서버의 DataSource를 lookup해 반환하는 method + * 3. 주의사항 + * + * @param providerUrl Remote URI + * @param dataSourceName DataSource의 JNDI name + * @return DataSource JDBC DataSource object + * @exception ServiceLocatorException + **/ + public DataSource getRemoteDataSource(String providerUrl, String dataSourceName) { + DataSource dataSource = null; + + try { + if (cache.containsKey(dataSourceName)) { + dataSource = (DataSource) cache.get(dataSourceName); + } else { + Hashtable env = new Hashtable(); + env.put(Context.INITIAL_CONTEXT_FACTORY, WEBLOGIC_INITIAL_CONTEXT_FACTORY); + env.put(Context.PROVIDER_URL, providerUrl); + initial = new InitialContext(env); + + dataSource = (DataSource)initial.lookup(dataSourceName); + + cache.put(dataSourceName,dataSource); + } + return dataSource; + } catch (Exception e) { + // throw new RuntimeException(e); + throw new RuntimeException(ExceptionUtil.getErrorCode(e,"RECEAICUL104")); + } + } + /** + * 1. 기능 : QueueConnectionFactory를 반환하는 method + * 2. 처리 개요 : + * - QueueConnectionFactory를 반환하는 method + * 3. 주의사항 + * + * @param qConnFactoryName QueueConnectionFactory의 JNDI name + * @return QueueConnectionFactory object + * @exception ServiceLocatorException + */ + public QueueConnectionFactory getQueueConnectionFactory(String qConnFactoryName) + throws ServiceLocatorException { + QueueConnectionFactory factory = null; + + try { + if (cache.containsKey(qConnFactoryName)) { + factory = (QueueConnectionFactory) cache.get(qConnFactoryName); + } else { + factory = (QueueConnectionFactory) initial.lookup(qConnFactoryName); + cache.put(qConnFactoryName, factory); + } + } catch (NamingException ne) { + //throw new ServiceLocatorException(ne); + throw new ServiceLocatorException(ExceptionUtil.getErrorCode(ne,"RECEAICUL113")); + } catch (Exception e) { + //throw new ServiceLocatorException(e); + throw new ServiceLocatorException(ExceptionUtil.getErrorCode(e,"RECEAICUL114")); + } + + return factory; + } + + /** + * 1. 기능 : Queue를 반환하는 method + * 2. 처리 개요 : + * - Queue를 반환하는 method + * 3. 주의사항 + * + * @param queueName Queue의 JNDI name + * @return Queue object + * @exception ServiceLocatorException + */ + public Queue getQueue(String queueName) throws ServiceLocatorException { + Queue queue = null; + + try { + if (cache.containsKey(queueName)) { + queue = (Queue) cache.get(queueName); + } else { + queue = (Queue) initial.lookup(queueName); + cache.put(queueName, queue); + } + } catch (NamingException ne) { + //throw new ServiceLocatorException(ne); + throw new ServiceLocatorException(ExceptionUtil.getErrorCode(ne,"RECEAICUL115")); + } catch (Exception e) { + //throw new ServiceLocatorException(e); + throw new ServiceLocatorException(ExceptionUtil.getErrorCode(e,"RECEAICUL116")); + } + + return queue; + } + + +} diff --git a/src/com/eactive/eai/common/util/ServiceLocatorException.java b/src/com/eactive/eai/common/util/ServiceLocatorException.java new file mode 100644 index 0000000..709d15d --- /dev/null +++ b/src/com/eactive/eai/common/util/ServiceLocatorException.java @@ -0,0 +1,103 @@ +package com.eactive.eai.common.util; + +/** + * ServiceLocator의 예외 처리를 위한 사용자 정의 class
+ * + * @since 1.0 + * @author bmchae + */ +public class ServiceLocatorException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + /** 발생한 실재 Exception */ + private Exception exception; + + /** + * 1. 기능 : Constructor + * 2. 처리 개요 : + * - Constructor + * 3. 주의사항 + * + * @param message Excetpion message + * @param Excetpion 발생한 Exception + */ + public ServiceLocatorException(String message, Exception exception) { + super(message); + this.exception = exception; + + return; + } + + /** + * 1. 기능 : Constructor + * 2. 처리 개요 : + * - Constructor + * 3. 주의사항 + * + * @param message Excetpion message + */ + public ServiceLocatorException(String message) { + this(message, null); + + return; + } + + /** + * 1. 기능 : Constructor + * 2. 처리 개요 : + * - Constructor + * 3. 주의사항 + * + * @param Excetpion 발생한 Exception + */ + public ServiceLocatorException(Exception exception) { + this(null, exception); + + return; + } + + /** + * 1. 기능 : 실재 발생한 Exception을 반환하는 method + * 2. 처리 개요 : + * - 실재 발생한 Exception을 반환하는 method + * 3. 주의사항 + * + * @return 실재 발생한 Exception + */ + public Exception getException() { + return exception; + } + + /** + * 1. 기능 : 실재 발생한 Exception을 반환하는 method + * 2. 처리 개요 : + * - 실재 발생한 Exception을 반환하는 method + * 3. 주의사항 + * + * @return 실재 발생한 Exception + */ + public Exception getRootCause() { + if (exception instanceof ServiceLocatorException) { + return ((ServiceLocatorException) exception).getRootCause(); + } + + return (exception == null) ? this : exception; + } + + /** + * 1. 기능 : 실재 발생한 Exception의 toString() method의 결과를 반환하는 method + * 2. 처리 개요 : + * - 실재 발생한 Exception의 toString() method의 결과를 반환하는 method + * 3. 주의사항 + */ + public String toString() { + if (exception instanceof ServiceLocatorException) { + return ((ServiceLocatorException) exception).toString(); + } + + return (exception == null) + ? super.toString() : exception.toString(); + } +} diff --git a/src/com/eactive/eai/common/util/StringUtil.java b/src/com/eactive/eai/common/util/StringUtil.java new file mode 100644 index 0000000..16b48b1 --- /dev/null +++ b/src/com/eactive/eai/common/util/StringUtil.java @@ -0,0 +1,394 @@ +package com.eactive.eai.common.util; + +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.StringTokenizer; +import java.util.Vector; + +/** + * 1. 기능 : String 관련 Utility Class + * 2. 처리 개요 : + * * - Date, Time 관련 Utility Method 정의 + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public final class StringUtil { + + /** + * Private 생성자 + * Instance를 생성하지 못함 + */ + private StringUtil() + { + + } + + /** + * 1. 기능 : byte array를 원하는 Encoding의 스트링으로 변환하는 Method + * 2. 처리 개요 : + * + * 주요 Character Set( Parameter로 Name또는 Alias 입력 ) + * Name Alias Description + * -------------------- ------------------------------------- ---------------------------- + * ANSI_X3.4-1968 ASCII, US-ASCII, IBM367, cp367 영문 ASCII + * KS_C_5601-1987 KSC_5601 한글 완성형 + * EUC-KR csEUCKR 한글 조합형 + * ISO-2022-JP csISO2022JP 일어 + * ISO-2022-JP-2 csISO2022JP2 일어 + * GB_2312-80 csISO58GB231280 중국어 + * ISO_8859-1:1987 ISO_8859-1, ISO-8859-1, IBM819, CP819 영문 라틴1 + * UTF-8 유니코드(8비트) + * UTF-16 유니코드(16비트) + + * 3. 주의사항 + * + * 참고 : http://www.iana.org/assignments/character-sets + * + * @param bytes 변환대상 byte array + * @param charsetName byte array decoding용 character set + * @return byte array를 변환한 결과 스트링 + */ + public static java.lang.String bytes2String(byte[] bytes, String charsetName) { + StringBuffer strBuffer = new StringBuffer(30); + try { + strBuffer.append(new String(bytes, charsetName)); + } catch (UnsupportedEncodingException uee) { + } catch (Exception e) {} + + return strBuffer.toString(); + } + + + /** + * 1. 기능 : 헥사스트링(16진수)을 byte arrary로 변환하는 Method + * 2. 처리 개요 : + * - 헥사스트링(16진수)을 byte arrary로 변환하는 Method + * 3. 주의사항 + * + * @param hexStr 변환대상 16진수 스트링 + * @return 16진수 스트링을 변환한 결과 byte array + */ + public static byte[] hex2Bytes(String hexStr) { + byte retByte[] = new byte[hexStr.length() / 2]; + for(int j = 0; j < retByte.length; j++) + retByte[j] = (byte)Integer.parseInt(hexStr.substring(2 * j, 2 * j + 2), 16); + return retByte; + } + + + /** + * 1. 기능 : byte arrary를 헥사스트링(16진수)으로 변환하는 Method + * 2. 처리 개요 : + * - byte arrary를 헥사스트링(16진수)으로 변환하는 Method + * 3. 주의사항 + * + * @param inBytes 변환대상 byte array + * @return byte array를 변환한 16진수 결과 스트링 + */ + public static String bytes2Hex(byte inBytes[]) { + String s = ""; + for(int i = 0; i < inBytes.length; i++) + s = s + Integer.toHexString((inBytes[i] & 0xf0) >> 4) + Integer.toHexString(inBytes[i] & 0xf); + + return s.toUpperCase(); + } + + + /** + * 1. 기능 : String을 헥사스트링(16진수)으로 변환하는 Method + * 2. 처리 개요 : + * - String을 헥사스트링(16진수)으로 변환하는 Method + * 3. 주의사항 + * + * @param inStr 변환대상 스트링 + * @return 변환대상스트링을 변환한 16진수 결과 스트링 + */ + public static String str2Hex(String inStr) { + if ( inStr == null || inStr.equals("") ) + { + return ""; + } + String retStr = bytes2Hex( inStr.getBytes() ); + return retStr; + } + + + /** + * 1. 기능 : 스트링에서 특정 문자 개수를 반환하는 Method(제어문자등이 전송중 누락되었는지 확인할 때 사용) + * 2. 처리 개요 : + * - 스트링에서 특정 문자 개수를 반환하는 Method(제어문자등이 전송중 누락되었는지 확인할 때 사용) + * 3. 주의사항 + * + * @param inStr 계수대상 스트링 + * @param ch 계수할 문자 + * @return int 계수결과(문자개수) + */ + public static int getCharCount(String inStr, char ch) { + char[] arrChar = inStr.toCharArray(); + int count = 0; + for (int i=0; i < arrChar.length ; i++) + if ( arrChar[i] == ch) count++; + return count; + } + + + /** + * 1. 기능 : 구분자가 들어간 스트링을 구분자기준으로 잘라 String Array를 만들어주는 Method + * 2. 처리 개요 : + * - 구분자가 들어간 스트링을 구분자기준으로 잘라 String Array를 만들어주는 Method + * 3. 주의사항 + * + * @param inStr 대상 스트링 + * @param delim 잘라낼 때의 기준 구분자 + * @return 잘라낸 스트링을 담고 있는 String Array + */ + public static String[] getStrArray(String inStr, String delim) { + String[] retStr = null; + + if ( inStr == null || inStr.equals("") ) { + return (new String[] {}); + } else { + retStr = inStr.split(delim); + } + + return retStr; + } + + /** + * 1. 기능 : String 이 null 이면 ""(Null String)을 리턴하는 Method + * 2. 처리 개요 : + * - String 이 null 이면 ""(Null String)을 리턴하는 Method + * 3. 주의사항 + * + * @param inStr 입력 스트링 + * @return Null 처리된 스트링 + */ + public static String getNullStr( String inStr ) + { + return inStr==null?"":inStr; + } + + /** + * 1. 기능 : Object가 null 이면 ""(Null String)을 리턴하는 Method + * 2. 처리 개요 : + * - Object가 null 이면 ""(Null String)을 리턴하는 Method + * 3. 주의사항 + * + * @param inObj 입력 Object + * @return Null 처리된 스트링 + */ + public static String getNullStr( Object inObj ) + { + return inObj==null?"":(String)inObj; + } + + /** + * 1. 기능 : 주어진 String값을 주어진 길이많큼 Padding/Trim한다. + * 2. 처리 개요 : + * - 주어진 String값을 주어진 길이많큼 Padding/Trim한다. + * 3. 주의사항 + * + * @param svalue - 입력스트링 + * @param isRightJustify - true이면 RIGHT JUSTIFY, false이면 LEFT JUSTIFY + * @param padding - Padding 문자 + * @param length - 리턴할 스트링의 바이트수 + * @return 포맷팅된 String결과 + */ + public static String stringFormat(String svalue, boolean isRightJustify, char padding, int length) { + if ( svalue == null ) return svalue; + + String mpad = new String(); + int pLength = 0; + + pLength = length - svalue.getBytes().length; + + if (pLength == 0) { + return svalue; + } + else if ( pLength < 0) { + byte[] abytes = null; + if (isRightJustify) { + abytes = (new String( svalue.getBytes(), -(pLength), length)).getBytes(); + } else { + abytes = (new String( svalue.getBytes(), 0, length)).getBytes(); + } + + if ( abytes.length == length ) { + return new String( abytes ); + } else { + svalue = new String( abytes ); + pLength = length - svalue.length(); + } + } + + for(int i =0; i < pLength ; i++) + mpad += padding; + + if ( isRightJustify ) { + return (mpad + svalue); + } else { + return (svalue + mpad); + } + } + + /** + * 1. 기능 : 주어진 String값을 주어진 길이많큼 자른다. + * 2. 처리 개요 : + * - 주어진 String값을 주어진 길이 많큼 자른다. + * 3. 주의사항 + * + * @param svalue - 입력스트링 + * @param length - 리턴할 스트링의 바이트수 + * @return 포맷팅된 String결과와 남은 String + */ + public static String[] chunkString(String sValue, int length) + { + String[] split = new String[2]; + + byte[] bytesValue = sValue.getBytes(); + + int doubleBytes = 0; + + if(bytesValue.length < length) { + split[0] = sValue; + split[1] = ""; + return split; + } + + for(int i = 0; i 0)) { + doubleBytes++; + } + } + + if( (doubleBytes%2) > 0) { + length = length - 1; + } + + byte[] retBytes = new byte[length]; + byte[] remainBytes = new byte[bytesValue.length - length]; + + System.arraycopy(bytesValue, 0, retBytes, 0, retBytes.length); + split[0] = new String(retBytes); + + System.arraycopy(bytesValue, length, remainBytes, 0, remainBytes.length); + split[1] = new String(remainBytes); + + return split; + } + + /** + * 1. 기능 : 주어진 String값을 주어진 길이많큼 똑같이 잘라서 배열에 넣는다. + * 2. 처리 개요 : + * - 주어진 String값을 주어진 길이많큼 자른다. + * 3. 주의사항 + * + * @param svalue - 입력스트링 + * @param length - 리턴할 스트링의 바이트수 + * @return 포맷팅된 String결과의배열 + */ + public static String[] chunkStringTotal(String sValue, int length){ + String[] data =null; + HashMap hm = new HashMap(); + int i = 0; + + do { + data = chunkString(sValue, length); + hm.put(Integer.toString(i), data[0]); + i++; + sValue = data[1]; + } + while (sValue.getBytes().length > length ); + + if (sValue.length() > 0) { + hm.put(Integer.toString(i), sValue); + } + + String [] result = new String [hm.size()]; + for (int j = 0; j < hm.size(); j++) { + result[j] = hm.get(Integer.toString(j)); + } + + return result; + + } + + /** + * 1. 기능 : 주어진 String값을 delimeter로 나누어 String[]를 생성한다 + * 2. 처리 개요 : + * - 주어진 String값을 delimeter로 나누어 String[]를 생성한다 + * 3. 주의사항 + * + * @param input - 입력스트링 + * @param delimeter - delimeter + * @return 포맷팅된 String결과의배열 + */ + public static String[] stringTokenizer(String input, String delimeter) + { + StringTokenizer st = new StringTokenizer(input, delimeter); + Vector vt = new Vector(); + + String temp = null; + + while (st.hasMoreTokens()) { + temp = st.nextToken(); + vt.addElement(temp); + } + + String[] out = new String[vt.size()]; + for ( int i = 0; i < vt.size() ; i ++ ) { + out[i] = (String)vt.elementAt(i); + } + return out; + } + + /** + * 1. 기능 : 주어진 String값을 delimeter로 나누어 XML Tag를 추가한다. + * 2. 처리 개요 : + * - 주어진 String값을 delimeter로 나누어 tag Prefix에 순차값을 생성하여 XML 형태의 String을 생성한다. + * 3. 주의사항 + * + * @param input - 입력스트링 + * @param delimeter - delimeter + * @param tagPrefix - tag Prefix + * @return XML형태로 포맷팅된 String결과 + */ + public static String delimeterToXml(String input, String delimeter, String tagPrefix) + { + StringBuffer sb = new StringBuffer(); + + if(input == null || input.length() == 0) return ""; + + String[] tokens = stringTokenizer(input, delimeter); + for(int i=0; i< tokens.length; i++) { + sb.append("<" + tagPrefix + (i+1) + ">" + tokens[i] + ""); + } + return sb.toString(); + } + + /** + * 1. 기능 : 주어진 byte[]값을 delimeter로 나누어 XML Tag를 추가한다. + * 2. 처리 개요 : + * - 주어진 byte[]값을 delimeter로 나누어 tag Prefix에 순차값을 생성하여 XML 형태의 byte[]을 생성한다. + * 3. 주의사항 + * + * @param input - 입력 byte[] + * @param delimeter - delimeter + * @param tagPrefix - tag Prefix + * @return XML형태로 포맷팅된 byte[]결과 + */ + public static byte[] delimeterToXmlBytes(byte[] input, String delimeter, String tagPrefix) { + if(input == null) return new byte[0]; + String xmlStr = delimeterToXml(new String(input), delimeter, tagPrefix); + return xmlStr.getBytes(); + } + + + + + +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/UCMsgSenderUtil.java b/src/com/eactive/eai/common/util/UCMsgSenderUtil.java new file mode 100644 index 0000000..1b403a0 --- /dev/null +++ b/src/com/eactive/eai/common/util/UCMsgSenderUtil.java @@ -0,0 +1,157 @@ +package com.eactive.eai.common.util; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.common.property.PropManager; +//import com.eactive.eai.common.server.EAIServerManager; + +public class UCMsgSenderUtil { + + public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public static final String UCINFO = "UCInfo"; + public static final String FEP_RECEIVER = "fep.receiver"; //FEP일괄전송 담당자 UC ID - ,로 분리 +// private static final String SUBJECT = "subject"; +// private static final String URL = "UC.url"; +// private static final String SENDER = "UC.sender"; + public static final String CHECK_PERIOD = "check.period"; + + private UCMsgSenderUtil(){ + } + + public static void sendUcMsg( String contents, String recvid, String fileName ){ +// try{ +// +// if ( recvid == null || recvid.trim().equals("") ) return; +// if ( recvid.startsWith("00") ){ +// recvid = "98" + recvid.substring(2); +// } +// +// Properties prop = PropManager.getInstance().getProperties(UCINFO); +// String sysGb = "운영"; +// if ( EAIServerManager.getInstance().isDEAIServer() ) +// sysGb = "개발"; +// if ( EAIServerManager.getInstance().isTEAIServer() ) +// sysGb = "검증"; +// String subject = prop.getProperty(SUBJECT) + "<" +sysGb+ ">"; +// if ( fileName != null ) +// subject = subject + fileName; +// +// String Encoding = "UTF-8"; +// String ucUrl = prop.getProperty(URL); +// String sender = prop.getProperty(SENDER); +// +// URL url = new URL(ucUrl); +// HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); +// urlConn.setRequestMethod("POST"); +// urlConn.setDoOutput(true); +// +// OutputStream os = urlConn.getOutputStream(); +// +// +// BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(os)); +// bw1.write("CMD=MSG&Action=ALERT&SystemName=FEP 일괄전송["+sysGb+"]&SendName="+sender+"&RecvID="+recvid+"&Subject="+subject+"&Subject_Encode="+Encoding+"&Contents="+contents+"&Option=UM=POST,EN=BASE64H,SP=F,LT=20,TP=50,WD=600,HG=520,IT=N,IR=Y"); +// +// bw1.flush(); +// bw1.close(); +// +// BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); +// String str = ""; +// while((str = br.readLine()) != null){ +// logger.debug(str); +// } +// br.close(); +// }catch(Exception e){ +// logger.error(e.getMessage(), e); +// } + } + + public static void setUcMsg(BatchJobInfoVO info, String fileName, boolean success, String msg ){ + + if ( info == null ) return; + if (!info.getRecvNotiUseYn().equals("1")){ + return; + } + String procCode = fileName.substring(0, 5); + String instCode = fileName.substring(6, 10); + String procName = ""; + String instName = ""; + OutsideVO osd = OutsideManager.getInstance().getOutsideInfo(procCode, instCode); + if ( osd != null ){ + procName = osd.getBatchName(); + instName = osd.getOsdName(); + } + String contents = "업무구분명 : " + procName + "

" ; + contents += "대외기관명 : " + instName + "

" ; + contents += "파일 구분자 : " + info.getJobTranDstcd() + "

" ; + contents += "파일 명 : " + fileName + "

" ; + contents += "파일 설명 : " + info.getMsgDstName() + "

" ; + if ( success ){ + contents += "파일 수신에 성공하였습니다."; + String[] ids = info.getChrgIDs(); + for (int inx = 0; inx < ids.length; inx++) { + String receiver = ids[inx]; + if ( receiver == null || receiver.trim().equals("") ) return; + if ( info.getRecvUseYN().equals("1") ) + sendUcMsg(contents, receiver, fileName); + } + }else{ + contents += "파일 수신에 성공하였으나 계정계 전송에 실패 하였습니다.

"; + contents += msg; + String[] ids = PropManager.getInstance().getProperties(UCINFO).getProperty(FEP_RECEIVER).split(","); + for (int inx = 0; inx < ids.length; inx++) { + String receiver = ids[inx]; + if ( receiver == null || receiver.trim().equals("") ) return; + if ( info.getRecvUseYN().equals("1") ) + sendUcMsg(contents, receiver, fileName); + } + } + + } + + public static void sendUCMsg(BatchDoc batchDoc){ + String msg = "다음과 같은 원인으로 일괄전송 송/수신 작업이 실패 하였습니다.

"; + msg += "이 쪽지는 시스템 상황에 따라 발송 되지 않을 수 있습니다.

"; + if (batchDoc.getBatchMsg().getBody().getErrorMsg() != null ) + msg += "

" + batchDoc.getBatchMsg().getBody().getErrorMsg() + "

"; + + msg += "

" + batchDoc + "
"; + String[] ids = PropManager.getInstance().getProperties(UCINFO).getProperty(FEP_RECEIVER).split(","); + for (int inx = 0; inx < ids.length; inx++) { + String receiver = ids[inx]; + if ( receiver == null || receiver.trim().equals("") ) continue; + logger.debug("[sendUCMsg]receiver-->" + receiver); + logger.debug("[sendUCMsg]msg-->" + msg); + sendUcMsg(msg, receiver, null); + } + + String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); + String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode(); + BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd( procCode, bizCode ); + String[] receivers = {}; + if ( jvo != null ){ + receivers = jvo.getChrgIDs(); + } + for (int inx = 0; inx < receivers.length; inx++) { + String receiver = receivers[inx]; + if ( receiver == null || receiver.trim().equals("") ) continue; + logger.debug("[sendUCMsg]receiver-->" + receiver); + logger.debug("[sendUCMsg]msg-->" + msg); + sendUcMsg(msg, receiver, null); + } + } + + public static void sendUCMsg( String msg ){ + String[] ids = PropManager.getInstance().getProperties(UCINFO).getProperty(FEP_RECEIVER).split(","); + for (int inx = 0; inx < ids.length; inx++) { + String receiver = ids[inx]; + if ( receiver == null || receiver.trim().equals("") ) return; + logger.debug("[sendUCMsg]receiver-->" + receiver); + logger.debug("[sendUCMsg]msg-->" + msg); + sendUcMsg(msg, receiver, null); + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/UUID.java b/src/com/eactive/eai/common/util/UUID.java new file mode 100644 index 0000000..ea1a181 --- /dev/null +++ b/src/com/eactive/eai/common/util/UUID.java @@ -0,0 +1,489 @@ +package com.eactive.eai.common.util; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.StringTokenizer; +import java.util.Vector; + +public final class UUID implements java.io.Serializable { + /** + * Explicit serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1L; + + /* + * The random number generator used by this class to create random based + * UUIDs. + */ + private static volatile SecureRandom numberGenerator = null; + + /* + * The most significant 64 bits of this UUID. + * + * @serial + */ + private final long mostSigBits; + + /* + * The least significant 64 bits of this UUID. + * + * @serial + */ + private final long leastSigBits; + + /* + * The version number associated with this UUID. Computed on demand. + */ + private transient int version = -1; + + /* + * The variant number associated with this UUID. Computed on demand. + */ + private transient int variant = -1; + + /* + * The timestamp associated with this UUID. Computed on demand. + */ + private transient volatile long timestamp = -1; + + /* + * The clock sequence associated with this UUID. Computed on demand. + */ + private transient int sequence = -1; + + /* + * The node number associated with this UUID. Computed on demand. + */ + private transient long node = -1; + + /* + * The hashcode of this UUID. Computed on demand. + */ + private transient int hashCode = -1; + + // Constructors and Factories + + /* + * Private constructor which uses a byte array to construct the new UUID. + */ + private UUID(byte[] data) { + long msb = 0; + long lsb = 0; + + for (int i = 0; i < 8; i++) + msb = (msb << 8) | (data[i] & 0xff); + + for (int i = 8; i < 16; i++) + lsb = (lsb << 8) | (data[i] & 0xff); + + this.mostSigBits = msb; + this.leastSigBits = lsb; + } + + /** + * Constructs a new UUID using the specified data. + * mostSigBits is used for the most significant 64 bits of the + * UUID and leastSigBits becomes the least significant + * 64 bits of the UUID. + * + * @param mostSigBits + * @param leastSigBits + */ + public UUID(long mostSigBits, long leastSigBits) { + this.mostSigBits = mostSigBits; + this.leastSigBits = leastSigBits; + } + + /** + * Static factory to retrieve a type 4 (pseudo randomly generated) UUID. + * + * The UUID is generated using a cryptographically strong + * pseudo random number generator. + * + * @return a randomly generated UUID. + */ + public static UUID randomUUID() { + SecureRandom ng = numberGenerator; + + if (ng == null) { + numberGenerator = ng = new SecureRandom(); + } + + byte[] randomBytes = new byte[16]; + ng.nextBytes(randomBytes); + randomBytes[6] &= 0x0f; /* clear version */ + randomBytes[6] |= 0x40; /* set to version 4 */ + randomBytes[8] &= 0x3f; /* clear variant */ + randomBytes[8] |= 0x80; /* set to IETF variant */ + + //UUID result = new UUID(randomBytes); + + return new UUID(randomBytes); + } + + /** + * Static factory to retrieve a type 3 (name based) UUID based on + * the specified byte array. + * + * @param name + * a byte array to be used to construct a UUID. + * @return a UUID generated from the specified array. + */ + public static UUID nameUUIDFromBytes(byte[] name) { + MessageDigest md; + + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException nsae) { + throw new InternalError("MD5 not supported"); + } + + byte[] md5Bytes = md.digest(name); + md5Bytes[6] &= 0x0f; /* clear version */ + md5Bytes[6] |= 0x30; /* set to version 3 */ + md5Bytes[8] &= 0x3f; /* clear variant */ + md5Bytes[8] |= 0x80; /* set to IETF variant */ + + return new UUID(md5Bytes); + } + + /** + * Creates a UUID from the string standard representation as + * described in the {@link #toString}method. + * + * @param name + * a string that specifies a UUID. + * @return a UUID with the specified value. + * @throws IllegalArgumentException + * if name does not conform to the string representation as + * described in {@link #toString}. + */ + public static UUID fromString(String name) { + + StringTokenizer tokenizer = new StringTokenizer(name); + + Vector cs = new Vector(); + + while (tokenizer.hasMoreTokens()) + cs.add(tokenizer.nextToken()); + + String[] components = new String[cs.size()]; + + for (int a = 0; a < cs.size(); a++) + components[a] = (String) (cs.elementAt(a)); + + if (components.length != 5) { + throw new IllegalArgumentException("Invalid UUID string: " + name); + } + + for (int i = 0; i < 5; i++) + components[i] = "0x" + components[i]; + + long mostSigBits = Long.decode(components[0]).longValue(); + mostSigBits <<= 16; + mostSigBits |= Long.decode(components[1]).longValue(); + mostSigBits <<= 16; + mostSigBits |= Long.decode(components[2]).longValue(); + + long leastSigBits = Long.decode(components[3]).longValue(); + leastSigBits <<= 48; + leastSigBits |= Long.decode(components[4]).longValue(); + + return new UUID(mostSigBits, leastSigBits); + } + + // Field Accessor Methods + + /** + * Returns the least significant 64 bits of this UUID's 128 bit value. + * + * @return the least significant 64 bits of this UUID's 128 bit value. + */ + public long getLeastSignificantBits() { + return leastSigBits; + } + + /** + * Returns the most significant 64 bits of this UUID's 128 bit value. + * + * @return the most significant 64 bits of this UUID's 128 bit value. + */ + public long getMostSignificantBits() { + return mostSigBits; + } + + /** + * The version number associated with this UUID. The version + * number describes how this UUID was generated. + * + * The version number has the following meaning: + *

+ *

    + *
  • 1 Time-based UUID + *
  • 2 DCE security UUID + *
  • 3 Name-based UUID + *
  • 4 Randomly generated UUID + *
+ * + * @return the version number of this UUID. + */ + public int version() { + if (version < 0) { + // Version is bits masked by 0x000000000000F000 in MS long + version = (int) ((mostSigBits >> 12) & 0x0f); + } + + return version; + } + + /** + * The variant number associated with this UUID. The variant + * number describes the layout of the UUID. + * + * The variant number has the following meaning: + *

+ *

    + *
  • 0 Reserved for NCS backward compatibility + *
  • 2 The Leach-Salz variant (used by this class) + *
  • 6 Reserved, Microsoft Corporation backward compatibility + *
  • 7 Reserved for future definition + *
+ * + * @return the variant number of this UUID. + */ + public int variant() { + if (variant < 0) { + // This field is composed of a varying number of bits + if ((leastSigBits >>> 63) == 0) { + variant = 0; + } else if ((leastSigBits >>> 62) == 2) { + variant = 2; + } else { + variant = (int) (leastSigBits >>> 61); + } + } + + return variant; + } + + /** + * The timestamp value associated with this UUID. + * + *

+ * The 60 bit timestamp value is constructed from the time_low, time_mid, + * and time_hi fields of this UUID. The resulting timestamp is + * measured in 100-nanosecond units since midnight, October 15, 1582 UTC. + *

+ * + * The timestamp value is only meaningful in a time-based UUID, which has + * version type 1. If this UUID is not a time-based UUID then + * this method throws UnsupportedOperationException. + * + * @throws UnsupportedOperationException + * if this UUID is not a version 1 UUID. + */ + public long timestamp() { + if (version() != 1) { + throw new UnsupportedOperationException("Not a time-based UUID"); + } + + long result = timestamp; + + if (result < 0) { + result = (mostSigBits & 0x0000000000000FFFL) << 48; + result |= (((mostSigBits >> 16) & 0xFFFFL) << 32); + result |= mostSigBits >>> 32; + timestamp = result; + } + + return result; + } + + /** + * The clock sequence value associated with this UUID. + * + *

+ * The 14 bit clock sequence value is constructed from the clock sequence + * field of this UUID. The clock sequence field is used to guarantee + * temporal uniqueness in a time-based UUID. + *

+ * + * The clockSequence value is only meaningful in a time-based UUID, which + * has version type 1. If this UUID is not a time-based UUID then this + * method throws UnsupportedOperationException. + * + * @return the clock sequence of this UUID. + * @throws UnsupportedOperationException + * if this UUID is not a version 1 UUID. + */ + public int clockSequence() { + if (version() != 1) { + throw new UnsupportedOperationException("Not a time-based UUID"); + } + + if (sequence < 0) { + sequence = (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); + } + + return sequence; + } + + /** + * The node value associated with this UUID. + * + *

+ * The 48 bit node value is constructed from the node field of this UUID. + * This field is intended to hold the IEEE 802 address of the machine that + * generated this UUID to guarantee spatial uniqueness. + *

+ * + * The node value is only meaningful in a time-based UUID, which has version + * type 1. If this UUID is not a time-based UUID then this method throws + * UnsupportedOperationException. + * + * @return the node value of this UUID. + * @throws UnsupportedOperationException + * if this UUID is not a version 1 UUID. + */ + public long node() { + if (version() != 1) { + throw new UnsupportedOperationException("Not a time-based UUID"); + } + + if (node < 0) { + node = leastSigBits & 0x0000FFFFFFFFFFFFL; + } + + return node; + } + + // Object Inherited Methods + + /** + * Returns a String object representing this + * UUID. + * + *

+ * The UUID string representation is as described by this BNF : + * + *

+     *
+     *
+     *    UUID                   = <time_low> "-" <time_mid> "-"
+     *                             <time_high_and_version> "-"
+     *                             <variant_and_sequence> "-"
+     *                             <node>
+     *    time_low               = 4*<hexOctet>
+     *    time_mid               = 2*<hexOctet>
+     *    time_high_and_version  = 2*<hexOctet>
+     *    variant_and_sequence   = 2*<hexOctet>
+     *    node                   = 6*<hexOctet>
+     *    hexOctet               = <hexDigit><hexDigit>
+     *    hexDigit               =
+     *          "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
+     *          | "a" | "b" | "c" | "d" | "e" | "f"
+     *          | "A" | "B" | "C" | "D" | "E" | "F"
+     *
+     *
+     * 
+ * + * @return a string representation of this UUID. + */ + public String toString() { + return (digits(mostSigBits >> 32, 8) + "-" + + digits(mostSigBits >> 16, 4) + "-" + digits(mostSigBits, 4) + "-" + + digits(leastSigBits >> 48, 4) + "-" + digits(leastSigBits, 12)); + } + + /** Returns val represented by the specified number of hex digits. */ + private static String digits(long val, int digits) { + long hi = 1L << (digits * 4); + + return Long.toHexString(hi | (val & (hi - 1))).substring(1); + } + + /** + * Returns a hash code for this UUID. + * + * @return a hash code value for this UUID. + */ + public int hashCode() { + if (hashCode == -1) { + hashCode = (int) ((mostSigBits >> 32) ^ mostSigBits ^ + (leastSigBits >> 32) ^ leastSigBits); + } + + return hashCode; + } + + /** + * Compares this object to the specified object. The result is true + * if and only if the argument is not null, is a UUID + * object, has the same variant, and contains the same value, bit for bit, + * as this UUID. + * + * @param obj + * the object to compare with. + * @return true if the objects are the same; + * false otherwise. + */ + public boolean equals(Object obj) { + if (!(obj instanceof UUID)) { + return false; + } + + if (((UUID) obj).variant() != this.variant()) { + return false; + } + + UUID id = (UUID) obj; + + return ((mostSigBits == id.mostSigBits) && + (leastSigBits == id.leastSigBits)); + } + + // Comparison Operations + + /** + * Compares this UUID with the specified UUID. + * + *

+ * The first of two UUIDs follows the second if the most significant field + * in which the UUIDs differ is greater for the first UUID. + * + * @param val + * UUID to which this UUID is to be + * compared. + * @return -1, 0 or 1 as this UUID is less than, equal to, or + * greater than val. + */ + public int compareTo(UUID val) { + // The ordering is intentionally set up so that the UUIDs + // can simply be numerically compared as two numbers + return ((this.mostSigBits < val.mostSigBits) ? (-1) + : ((this.mostSigBits > val.mostSigBits) + ? 1 + : ((this.leastSigBits < val.leastSigBits) ? (-1) + : ((this.leastSigBits > val.leastSigBits) + ? 1 : 0)))); + } + + /** + * Reconstitute the UUID instance from a stream (that is, + * deserialize it). This is necessary to set the transient fields to their + * correct uninitialized value so they will be recomputed on demand. + */ + private void readObject(java.io.ObjectInputStream in) + throws java.io.IOException, ClassNotFoundException { + in.defaultReadObject(); + + // Set "cached computation" fields to their initial values + version = -1; + variant = -1; + timestamp = -1; + sequence = -1; + node = -1; + hashCode = -1; + } +} diff --git a/src/com/eactive/eai/common/util/UUIDGenerator.java b/src/com/eactive/eai/common/util/UUIDGenerator.java new file mode 100644 index 0000000..fd34a26 --- /dev/null +++ b/src/com/eactive/eai/common/util/UUIDGenerator.java @@ -0,0 +1,39 @@ +package com.eactive.eai.common.util; + + +/** + * 1. 기능 : UUID Generation Class + * 2. 처리 개요 : + * * - + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : 관련 기능을 참조 + * @since : + */ +public final class UUIDGenerator { + /** + * 1. 기능 : Private 생성자 + * 2. 처리 개요 : + * - + * 3. 주의사항 + * - Instance 생성하지 못함 + **/ + private UUIDGenerator() { + } + + /** + * 1. 기능 : UUID를 생성하여 스트링으로 리턴하는 메쏘드 + * 2. 처리 개요 : + * - + * 3. 주의사항 + * + * @return 생성된 UUID 스트링 + **/ + public static String getUUID() { + UUID uuid = UUID.randomUUID(); + + return uuid.toString(); + } +} diff --git a/src/com/eactive/eai/common/util/convert/ASCII2EBCDIC.java b/src/com/eactive/eai/common/util/convert/ASCII2EBCDIC.java new file mode 100644 index 0000000..3dd9c12 --- /dev/null +++ b/src/com/eactive/eai/common/util/convert/ASCII2EBCDIC.java @@ -0,0 +1,45 @@ +package com.eactive.eai.common.util.convert; + +import java.util.Stack; + +import org.nfunk.jep.ParseException; +import org.nfunk.jep.function.PostfixMathCommand; + + +/** + * ASCII 값을 EBCDIC으로 변환하는 함수. + * 입력 값은 byte[], 결과는 byte[]임. + */ +public class ASCII2EBCDIC extends PostfixMathCommand { + public ASCII2EBCDIC() { + numberOfParameters = 1; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + 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(null); + } else { + throw new ParseException( + "Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param); + } + if (value == null) {// 20250910 npe 추가 + throw new ParseException("value is null"); + } + try { + inStack.push(IConv.asciiToEBCDIC(new String(value))); + } catch (Exception e) { + throw new ParseException(e.getMessage()); + } + } +} diff --git a/src/com/eactive/eai/common/util/convert/ASCII2EBCDIC9.java b/src/com/eactive/eai/common/util/convert/ASCII2EBCDIC9.java new file mode 100644 index 0000000..194d9b9 --- /dev/null +++ b/src/com/eactive/eai/common/util/convert/ASCII2EBCDIC9.java @@ -0,0 +1,51 @@ +package com.eactive.eai.common.util.convert; + +import java.util.Stack; + +import org.nfunk.jep.ParseException; +import org.nfunk.jep.function.PostfixMathCommand; + + +/** + * ASCII 값을 EBCDIC으로 변환하는 함수. + * 입력 값은 byte[], 결과는 byte[]임. + */ +public class ASCII2EBCDIC9 extends PostfixMathCommand { + public ASCII2EBCDIC9() { + numberOfParameters = 2; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + 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 == null) { + inStack.push(null); + } else { + throw new ParseException( + "Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param); + } + + + + try { + //byte[] buff = CodeConversion.ascToSE9(value, len); + byte[] buff = (value == null) ? new byte[0] : CodeConversion.ascToSE9(value, len); // 20250910 npe + inStack.push(buff); + } catch (Exception e) { + throw new ParseException(e.getMessage()); + } + } +} diff --git a/src/com/eactive/eai/common/util/convert/ASCII2EBCDICX.java b/src/com/eactive/eai/common/util/convert/ASCII2EBCDICX.java new file mode 100644 index 0000000..e30b2b5 --- /dev/null +++ b/src/com/eactive/eai/common/util/convert/ASCII2EBCDICX.java @@ -0,0 +1,51 @@ +package com.eactive.eai.common.util.convert; + +import java.util.Stack; + +import org.nfunk.jep.ParseException; +import org.nfunk.jep.function.PostfixMathCommand; + + +/** + * ASCII 값을 EBCDIC으로 변환하는 함수. + * 입력 값은 byte[], 결과는 byte[]임. + */ +public class ASCII2EBCDICX extends PostfixMathCommand { + public ASCII2EBCDICX() { + numberOfParameters = 2; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + 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 == null) { + inStack.push(null); + } else { + throw new ParseException( + "Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param); + } + + + + + try { + //byte[] buff = CodeConversion.ascToSE(value, len); + byte[] buff = (value == null) ? new byte[0] : CodeConversion.ascToSE(value, len); // 20250910 npe + inStack.push(buff); + } catch (Exception e) { + throw new ParseException(e.getMessage()); + } + } +} diff --git a/src/com/eactive/eai/common/util/convert/CodeConversion.java b/src/com/eactive/eai/common/util/convert/CodeConversion.java new file mode 100644 index 0000000..b7a4891 --- /dev/null +++ b/src/com/eactive/eai/common/util/convert/CodeConversion.java @@ -0,0 +1,669 @@ +package com.eactive.eai.common.util.convert; + +import java.math.BigInteger; + +public class CodeConversion +{ + + public static void main(String[] args) { + byte[] bytes = null; + + if(args.length < 2) { + //System.out.println("Usage : java CodeConversion [data] [cmd] "); + //System.out.println("COMMAND : COMP, COMP3, SE, GE "); + //System.out.println("Example : java CodeConversion 123 COMP "); + return; + } + + try { + if( "COMP".equals(args[1]) ) { + bytes = ascToComp(args[0]); + + //System.out.println("HOST COMP[" + new String(bytes)+"]"); + //System.out.println("UNIX COMP[" + compToAsc(bytes)+"]"); + } + else if( "COMP3".equals(args[1]) ) { + + bytes = ascToComp3(args[0]); + //System.out.println("HOST COMP3[" + new String(bytes)+"]"); + //System.out.println("UNIX COMP3[" + comp3ToAsc(bytes)+"]"); + } + else if( "SE".equals(args[1]) ) { + + bytes = ascToSE(args[0].getBytes()); + //System.out.println("HOST SE[" + new String(bytes)+"]"); + //System.out.println("UNIX ASC[" + new String(seToAsc(bytes))+"]"); + } + else if( "GE".equals(args[1]) ) { + // Graphic + bytes = ascToGE(args[0].getBytes()); + System.out.println("HOST GE[" + new String(bytes)+"]"); + System.out.println("UNIX ASC[" + new String(geToAsc(bytes))+"]"); + } + else if( "ME".equals(args[1]) ) { + // Mixed + bytes = ascToSE(args[0].getBytes()); + //System.out.println("HOST ME[" + new String(bytes)+"]"); + //System.out.println("UNIX ASC[" + new String(meToAsc(bytes))+"]"); + } + + byte[] sByte = args[0].getBytes(); + //System.out.println("[ Source Bytes ]"); + for(int i=0; i< sByte.length; i++) { + //System.out.println("Byte["+i+"] = "+ printBit(sByte[i]) ); + } + + //System.out.println("[ Converted Bytes ]"); + for(int i=0; i< bytes.length; i++) { + //System.out.println("Byte["+i+"] = "+ printBit(bytes[i]) ); + } + } + catch(Exception e) { + //System.out.println(e.toString()); + e.printStackTrace(); + } + } + + + public static String printBit(byte bt) { + String bitStr = ""; + for(int i=0; i<8; i++) { + if( (bt & (0x80 >> i )) != 0x00) bitStr +="1"; + else bitStr +="0"; + } + return bitStr; + } + + + public CodeConversion() { + super(); + } + + + //------------------------------------------------------------- + // Host COMP Type 과 ASCII 간의 변환 메소드 + // 예) PIC S9(4) USAGE COMP. + //------------------------------------------------------------- + // 9(1-4) 2Byte + // 9(5-9) 4Byte + /** + * String을 HOST COMP로 변환한다. + * + * @param src 숫자형식의 String + * + * @return byte[] COMP 형의 byte Array + * @exception Exception + */ + public static byte[] ascToComp(byte[] src) throws Exception { + return ascToComp(new String(src)); + } + + public static byte[] ascToComp(String src) throws Exception { + + byte[] comp = null; + + try { + if( "+".equals(src.substring(0,1)) ) src = src.substring(1); + + int sLen = src.length(); + + if(sLen > 9) { + throw new Exception("Maximun COMP Length Over["+src+"]"); + } + + int iKey = new Integer(src).intValue(); + + // System.out.println("HEX[0x"+ Integer.toHexString(iKey)+"]"); + + if(sLen < 5) { + int lower = iKey & 0xff; + int upper = iKey >> 8 & 0xff; + + comp = new byte[2]; + comp[0] = new Integer(upper).byteValue(); + comp[1] = new Integer(lower).byteValue(); + } + else { + int byte1 = iKey >> 24 & 0xffff; + int byte2 = iKey >> 16 & 0xffff; + int byte3 = iKey >> 8 & 0xffff; + int byte4 = iKey & 0xffff; + comp = new byte[4]; + comp[0] = new Integer(byte1).byteValue(); + comp[1] = new Integer(byte2).byteValue(); + comp[2] = new Integer(byte3).byteValue(); + comp[3] = new Integer(byte4).byteValue(); + + } + } catch(Exception e) { + throw new Exception(e.getMessage()); + } + return comp; + } + + + /** + * HOST COMP를 String으로 변환한다. + * + * @param data byte[] COMP 형의 byte Array + * + * @return src 숫자형식의 String + */ + + public static String compToAsc(byte[] data) { + BigInteger bint = new BigInteger(data); + return bint.toString(); + } + public static byte[] compToAscB(byte[] data) { + return (compToAsc(data)).getBytes(); + } + //------------------------------------------------------------- + // Host COMP-3 Type 과 ASCII 간의 변환 메소드 + // 예) PIC S9(15)V USAGE COMP-3. + //------------------------------------------------------------- + + /** + * Packed-Decimal을 숫자형식의 String으로 변환한다. + * + * @param src 숫자형식의 String으로 변환할 byte배열 + * + * @return String 숫자형식의 String + */ + public static String comp3ToAsc(byte[] src) { + + boolean isMinus = false; + StringBuffer sf = new StringBuffer(); + + int end = src.length; + + for (int i=0; i> 4 & 0x0f; + + if (i == end-1) { + sf.append(upper); + if (lower == COMP3_MINUS) { + isMinus = true; + } + } else { + sf.append((upper + "" + lower)); + } + } + + String str = sf.toString(); + + if (isMinus) { + str = "-" + str; + } + else { + str = "+" + str; + } + return str; + } + + public static byte[] comp3ToAscB(byte[] src) { + return (comp3ToAsc(src)).getBytes(); + } + /** + * String을 Packed-Decimal을 숫자형식으로 변환한다. + * + * @param src 숫자형식의 bytes + * + * @return bytes + * @exception Exception + */ + // 예 + // S9(5)V USAGE COMP-3. 일경우 + // UNIX 12345 -> 1/2 3/4 5/+ -> 0001/0010 0011/0100 0101/1111 + // UNIX +12345 -> 1/2 3/4 5/- -> 0001/0010 0011/0100 0101/1101 + // UNIX -12345 -> 1/2 3/4 5/- -> 0001/0010 0011/0100 0101/1101 + public static byte[] ascToComp3(byte[] src) throws Exception { + return ascToComp3(new String(src)); + } + + public static byte[] ascToComp3(String src) throws Exception { + int srcSize = src.length(); + int byteSize = 0; + int pos = 0; + String bit = ""; + byte sByte = COMP3_UNSIGN; + + bit = src.substring(0,1); + + if( "-".equals(bit) ) { + sByte = COMP3_MINUS; + byteSize = ((srcSize-1)/2)+1; + } + else if( "+".equals(bit) ) { + sByte = COMP3_PLUS; + byteSize = ((srcSize-1)/2)+1; + } + else { + byteSize = (srcSize/2)+1; + } + + byte[] comp3bytes = new byte[byteSize]; + + // byte 초기화 + for( int i=0; i<(byteSize-1); i++ ) comp3bytes[i] = 0x00; + + //----------------------------- + // 부호 설정 및 첫자리 처리 + //----------------------------- + bit = src.substring(srcSize-1); + pos = Integer.parseInt(bit); + + comp3bytes[byteSize-1] = COMP3_UBYTES[pos]; + comp3bytes[byteSize-1] = (byte)(comp3bytes[byteSize-1] | sByte); + + if(sByte == COMP3_UNSIGN) { + src = src.substring(0,srcSize-1); + } + else { + src = src.substring(1,srcSize-1); + } + + //----------------------------- + + srcSize = src.length(); + + int bPos = 0; + int cPos = byteSize-2; + + for( int i=0; i 0) { + for(int i = 0; i 0) { + for(int i = 0; i fixedLength) { + System.arraycopy(source, 0, sBytes, 0, fixedLength); + } + else { + System.arraycopy(source, 0, sBytes, 0, source.length); + for(int i = source.length; i < fixedLength; i++) { + sBytes[i] = U_SPACE; + } + } + return sBytes; + } + + /** + * EBCDIC byte를 특정 길이로 변환하며 여분은 SPACE로 채운다. + * + * @param source EBCDIC bytes[] + * @param fixedLength 요청 byte 길이 + * + * @return EBCDIC bytes[] + * @exception Exception + */ + public static byte[] appendHostSpace(byte[] source, int fixedLength) throws Exception { + + byte[] sBytes = new byte[fixedLength]; + + if(source.length > fixedLength) { + System.arraycopy(source, 0, sBytes, 0, fixedLength); + } + else { + System.arraycopy(source, 0, sBytes, 0, source.length); + for(int i = source.length; i < fixedLength; i++) { + sBytes[i] = H_SPACE; + } + } + return sBytes; + } + + /** + * ASCII byte를 특정 길이로 변환하며 여분은 SPACE로 채운다. + * + * @param source ASCII bytes[] + * @param fixedLength 요청 byte 길이 + * + * @return ASCII bytes[] + * @exception Exception + */ + public static byte[] appendAsciiSpace(byte[] source, int fixedLength) throws Exception { + + byte[] sBytes = new byte[fixedLength]; + + if(source.length > fixedLength) { + System.arraycopy(source, 0, sBytes, 0, fixedLength); + } + else { + System.arraycopy(source, 0, sBytes, 0, source.length); + for(int i = source.length; i < fixedLength; i++) { + sBytes[i] = U_SPACE; + } + } + return sBytes; + } + + /** + * ASCII를 Single EBCDIC로 변환한다.. + * + * @param source Single ASCII bytes[] + * + * @return Single EBCDIC bytes[] + * @exception Exception + */ + public static byte[] ascToSE(byte[] source) throws Exception { + String sStr = new String(source); + byte[] sBytes = null; + try { + sBytes = sStr.getBytes("cp933"); + } + catch(Exception e) { + throw e; + } + return sBytes; + } + + /** + * ASCII를 특정 길이의 Single EBCDIC로 변환한다.. + * + * @param source Single ASCII bytes[] + * @param fixedLength ASCII byte 길이 + * + * @return Single EBCDIC bytes[] + * @exception Exception + */ + public static byte[] ascToSE(byte[] source, int fixedLength) throws Exception { + + byte[] tmpBytes = ascToSE(source); + return appendHostSpace(tmpBytes, fixedLength); + } + + /** + * ASCII를 특정 길이의 Single EBCDIC로 변환한다.. + * + * @param source Single ASCII bytes[] + * @param fixedLength ASCII byte 길이 + * + * @return Single EBCDIC bytes[] + * @exception Exception + */ + public static byte[] ascToSE9(byte[] source, int fixedLength) throws Exception { + + byte[] tmpBytes = ascToSE(source); + return appendHostZero(tmpBytes, fixedLength); + } + /** + * Single EBCDIC을 ASCII로 변환한다.. + * + * @param source Single EBCDIC bytes[] + * + * @return ASCII bytes[] + * @exception Exception + */ + public static byte[] seToAsc(byte[] source) throws Exception { + try { + String sStr = new String(source,"cp933"); + return sStr.getBytes(); + } catch(Exception e) { + throw e; + } + } + + /** + * Single EBCDIC을 특정 길이의 ASCII로 변환한다.. + * + * @param source Single EBCDIC bytes[] + * @param fixedLength ASCII byte 길이 + * + * @return ASCII bytes[] + * @exception Exception + */ + public static byte[] seToAsc(byte[] source, int fixedLength) throws Exception { + byte[] tmpBytes = seToAsc(source); + return appendAsciiSpace(tmpBytes, fixedLength); + } + + /** + * ASCII(반자)를 Graphic EBCDIC로 변환한다.. + * + * @param source ASCII bytes[] + * + * @return Graphic bytes[] + * @exception Exception + */ + public static byte[] ascToGE(byte[] source) throws Exception { + + String sealSource = simpleToSeal(new String(source)); + byte[] sealBytes = sealSource.getBytes(); + byte[] seBytes = ascToSE(sealBytes); + + // SO-SI Length는 제외한다. + byte[] gBytes = new byte[seBytes.length - 2]; + System.arraycopy(seBytes, 1, gBytes, 0, gBytes.length); + return gBytes; + } + + /** + * Graphic EBCDIC을 ASCII(반자)로 변환한다.. + * + * @param source Graphic bytes[] + * + * @return ASCII bytes[] + * @exception Exception + */ + public static byte[] geToAsc(byte[] source) throws Exception { + + byte[] seBytes = new byte[source.length + 2]; + seBytes[0] = H_SO; + seBytes[seBytes.length-1] = H_SI; + + System.arraycopy(source, 0, seBytes, 1, seBytes.length - 2); + String sealString = new String(seToAsc(seBytes)); + String simpSource = sealToSimple(sealString); + return simpSource.getBytes(); + + } + + /** + * Mixed EBCDIC을 ASCII(반자)로 변환한다. + * SO-SI를 blank로 변환 + * + * @param source Graphic bytes[] + * + * @return ASCII bytes[] + * @exception Exception + */ + public static byte[] meToAsc(byte[] source) throws Exception { + + byte[] seBytes = new byte[source.length * 2]; + int sPos = 0; + for(int i=0; i> 8) == 0) { + if (isDBCS) { + bytes[j++] = SI; + isDBCS = false; + } + + bytes[j++] = (byte) ASCII_TO_EBCDIC_TABLE[(int) value.charAt(i)]; + + continue; + } + + if (!isDBCS) { + bytes[j++] = SO; + isDBCS = true; + } + + System.arraycopy(value.substring(i, i + 1).getBytes(), 0, dbcs, 0, 2); + WORD = Integer.parseInt(bytes2Hex(dbcs), 16); + + if ((WORD < 0xA1A1) || (WORD > 0xFEFE)) { // Out of range for 2 bytes character set like hangul + bytes[j++] = (byte) 0xFF; + bytes[j++] = (byte) 0xFF; + + continue; + } + + wc = DB_ASCII_TO_EBCDIC_TABLE[(WORD >> 8) - 161][(WORD & 0x00FF) - + 161]; + bytes[j++] = (byte) (wc >> 8); + bytes[j++] = (byte) (wc & 0x00FF); + } + + if (isDBCS) { + bytes[j++] = SI; + } + + byte[] _obytes = new byte[j]; + System.arraycopy(bytes, 0, _obytes, 0, j); + + return _obytes; + } + + public static String ebcdicToASCII(byte[] abytes) { + int length = abytes.length; + int j = 0; + int WORD = 0; + boolean isDBCS = false; + byte[] bytes = new byte[length]; + byte[] dbcs = new byte[2]; + char wc = 0; + + for (int i = 0; i < length; i++) { + // DBCS start ot End SO-SI + if (abytes[i] == SO) { + isDBCS = true; + + continue; + } else if (abytes[i] == SI) { + isDBCS = false; + + continue; + } + + if (((length - i) < 2) && isDBCS) { + isDBCS = false; + } + + // one byte ALPHANUMERIC + if (!isDBCS) { + dbcs[0] = 0x00; + dbcs[1] = abytes[i]; + bytes[j++] = (byte) EBCDIC_TO_ASCII_TABLE[Integer.parseInt(bytes2Hex( + dbcs), 16)]; + + continue; + } + + dbcs[0] = abytes[i++]; + dbcs[1] = abytes[i]; + WORD = Integer.parseInt(bytes2Hex(dbcs), 16); + + if (WORD == 0x4040) { + bytes[j++] = (byte) 0xA1; + bytes[j++] = (byte) 0xA1; + + continue; + } + + if (WORD == 0x0000) { + bytes[j++] = (byte) 0x00; + bytes[j++] = (byte) 0x00; + + continue; + } + + if ((WORD < 0x4141) || (WORD > 0xD5FF) || ((WORD & 0x00FF) < 0x41) || + ((WORD & 0x00FF) > 0xFE)) { // Out of range for 2 bytes character set like hangul + bytes[j++] = (byte) 0xFF; + bytes[j++] = (byte) 0xFF; + + continue; + } + + wc = DB_EBCDIC_TO_ASCII_TABLE[(WORD >> 8) - 65][(WORD & 0x00FF) - + 65]; + bytes[j++] = (byte) (wc >> 8); + bytes[j++] = (byte) (wc & 0x00FF); + } + + byte[] _obytes = new byte[j]; + System.arraycopy(bytes, 0, _obytes, 0, j); + + return new String(_obytes); + } + + public static String bytes2Hex(byte[] abyte0) { + StringBuffer buffer = new StringBuffer(); + + for (int i = 0; i < abyte0.length; i++) { + buffer.append(Integer.toHexString((abyte0[i] & 0xf0) >> 4)).append(Integer.toHexString(abyte0[i] & + 0xf)); + } + + return buffer.toString().toUpperCase(); + } + + public static byte[] hex2Bytes(String hex) { + byte[] buffer = new byte[hex.length() / 2]; + + int bIndex = 0; + + for (int i = 0; i < hex.length(); i += 2) { + buffer[bIndex++] = (byte) (((Integer.parseInt(Character.toString( + hex.charAt(i)), 16) & 0xf) << 4) | + (Integer.parseInt(Character.toString(hex.charAt(i + 1)), 16) & + 0xf)); + } + + return buffer; + } + + private static void buildConvTable() { + try { +// String OS = System.getProperty("os.name"); + + String className = IConv.class.getName(); + String pathName = className.substring(0, className.lastIndexOf('.')) + .replace('.', '/'); + + BufferedReader br = new BufferedReader(new InputStreamReader( + IConv.class.getClassLoader().getResourceAsStream(pathName + + "/iconv.tab"))); + String lbuff = br.readLine(); + int bucket = 0; + + while (lbuff != null) { + if (lbuff.substring(0, 3).equals("*0x")) { + for (int i = 0; i < 94; i++) + DB_ASCII_TO_EBCDIC_TABLE[bucket][i] = (char) Integer.parseInt(lbuff.substring(22 + + (i * 5), 26 + (i * 5)), 16); + + bucket++; + lbuff = br.readLine(); + + if (lbuff.substring(0, 3).equals("*X'")) { + bucket = 0; + } + + continue; + } else { + for (int i = 0; i < 190; i++) + DB_EBCDIC_TO_ASCII_TABLE[bucket][i] = (char) Integer.parseInt(lbuff.substring(22 + + (i * 5), 26 + (i * 5)), 16); + + bucket++; + } + + lbuff = br.readLine(); + } + // End of while + + br.close(); + } catch (IOException ex) { + //System.err.println("IOException caught in readFile"); + //CommonMessages.logGenericTrace("*IConv class has exception in conversion table I/O:" + ex.getMessage()); + ex.printStackTrace(); + } + } + + public static void main(String[] args) { + IConv.asciiToEBCDIC("AAA"); + logger.debug("I'm now exit."); + System.exit(0); + } +} diff --git a/src/com/eactive/eai/common/util/logger/CustomClassOfCallerConverter.java b/src/com/eactive/eai/common/util/logger/CustomClassOfCallerConverter.java new file mode 100644 index 0000000..bb01cc2 --- /dev/null +++ b/src/com/eactive/eai/common/util/logger/CustomClassOfCallerConverter.java @@ -0,0 +1,21 @@ +package com.eactive.eai.common.util.logger; + +import ch.qos.logback.classic.pattern.NamedConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; + +public class CustomClassOfCallerConverter extends NamedConverter { + protected String getFullyQualifiedName(ILoggingEvent event) { + StackTraceElement[] cda = event.getCallerData(); + if (cda != null && cda.length > 0) { + if (cda[0].getFileName().equals("Logger.java") && cda.length > 1) { + if (cda[1].getFileName().equals("Logger.java") && cda.length > 2){ + return cda[2].getClassName(); + } + return cda[1].getClassName(); + } + return cda[0].getClassName(); + } else { + return "?"; + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/logger/CustomFileOfCallerConverter.java b/src/com/eactive/eai/common/util/logger/CustomFileOfCallerConverter.java new file mode 100644 index 0000000..e204fe8 --- /dev/null +++ b/src/com/eactive/eai/common/util/logger/CustomFileOfCallerConverter.java @@ -0,0 +1,21 @@ +package com.eactive.eai.common.util.logger; + +import ch.qos.logback.classic.pattern.ClassicConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; + +public class CustomFileOfCallerConverter extends ClassicConverter { + public String convert(ILoggingEvent le) { + StackTraceElement[] cda = le.getCallerData(); + if (cda != null && cda.length > 0) { + if (cda[0].getFileName().equals("Logger.java") && cda.length > 1) { + if (cda[1].getFileName().equals("Logger.java") && cda.length > 2){ + return cda[2].getFileName(); + } + return cda[1].getFileName(); + } + return cda[0].getFileName(); + } else { + return "?"; + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/logger/CustomLineOfCallerConverter.java b/src/com/eactive/eai/common/util/logger/CustomLineOfCallerConverter.java new file mode 100644 index 0000000..1d463f7 --- /dev/null +++ b/src/com/eactive/eai/common/util/logger/CustomLineOfCallerConverter.java @@ -0,0 +1,21 @@ +package com.eactive.eai.common.util.logger; + +import ch.qos.logback.classic.pattern.ClassicConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; + +public class CustomLineOfCallerConverter extends ClassicConverter { + public String convert(ILoggingEvent le) { + StackTraceElement[] cda = le.getCallerData(); + if (cda != null && cda.length > 0) { + if (cda[0].getFileName().equals("Logger.java") && cda.length > 1) { + if (cda[1].getFileName().equals("Logger.java") && cda.length > 2){ + return Integer.toString(cda[2].getLineNumber()); + } + return Integer.toString(cda[1].getLineNumber()); + } + return Integer.toString(cda[0].getLineNumber()); + } else { + return "?"; + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/logger/CustomMethodOfCallerConverter.java b/src/com/eactive/eai/common/util/logger/CustomMethodOfCallerConverter.java new file mode 100644 index 0000000..d25b36e --- /dev/null +++ b/src/com/eactive/eai/common/util/logger/CustomMethodOfCallerConverter.java @@ -0,0 +1,21 @@ +package com.eactive.eai.common.util.logger; + +import ch.qos.logback.classic.pattern.ClassicConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; + +public class CustomMethodOfCallerConverter extends ClassicConverter { + public String convert(ILoggingEvent le) { + StackTraceElement[] cda = le.getCallerData(); + if (cda != null && cda.length > 0) { + if (cda[0].getFileName().equals("Logger.java") && cda.length > 1) { + if (cda[1].getFileName().equals("Logger.java") && cda.length > 2){ + return cda[2].getMethodName(); + } + return cda[1].getMethodName(); + } + return cda[0].getMethodName(); + } else { + return "?"; + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/logger/CustomPatternLayout.java b/src/com/eactive/eai/common/util/logger/CustomPatternLayout.java new file mode 100644 index 0000000..84dbc62 --- /dev/null +++ b/src/com/eactive/eai/common/util/logger/CustomPatternLayout.java @@ -0,0 +1,151 @@ +package com.eactive.eai.common.util.logger; + +import java.util.HashMap; +import java.util.Map; + +import ch.qos.logback.classic.pattern.CallerDataConverter; +import ch.qos.logback.classic.pattern.ClassOfCallerConverter; +import ch.qos.logback.classic.pattern.ContextNameConverter; +import ch.qos.logback.classic.pattern.DateConverter; +import ch.qos.logback.classic.pattern.EnsureExceptionHandling; +import ch.qos.logback.classic.pattern.ExtendedThrowableProxyConverter; +import ch.qos.logback.classic.pattern.LevelConverter; +import ch.qos.logback.classic.pattern.LineSeparatorConverter; +import ch.qos.logback.classic.pattern.LocalSequenceNumberConverter; +import ch.qos.logback.classic.pattern.LoggerConverter; +import ch.qos.logback.classic.pattern.MDCConverter; +import ch.qos.logback.classic.pattern.MarkerConverter; +import ch.qos.logback.classic.pattern.MessageConverter; +import ch.qos.logback.classic.pattern.MethodOfCallerConverter; +import ch.qos.logback.classic.pattern.NopThrowableInformationConverter; +import ch.qos.logback.classic.pattern.PropertyConverter; +import ch.qos.logback.classic.pattern.RelativeTimeConverter; +import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter; +import ch.qos.logback.classic.pattern.ThreadConverter; +import ch.qos.logback.classic.pattern.ThrowableProxyConverter; +import ch.qos.logback.classic.pattern.color.HighlightingCompositeConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.pattern.PatternLayoutBase; +import ch.qos.logback.core.pattern.color.BlackCompositeConverter; +import ch.qos.logback.core.pattern.color.BlueCompositeConverter; +import ch.qos.logback.core.pattern.color.BoldBlueCompositeConverter; +import ch.qos.logback.core.pattern.color.BoldCyanCompositeConverter; +import ch.qos.logback.core.pattern.color.BoldGreenCompositeConverter; +import ch.qos.logback.core.pattern.color.BoldMagentaCompositeConverter; +import ch.qos.logback.core.pattern.color.BoldRedCompositeConverter; +import ch.qos.logback.core.pattern.color.BoldWhiteCompositeConverter; +import ch.qos.logback.core.pattern.color.BoldYellowCompositeConverter; +import ch.qos.logback.core.pattern.color.CyanCompositeConverter; +import ch.qos.logback.core.pattern.color.GrayCompositeConverter; +import ch.qos.logback.core.pattern.color.GreenCompositeConverter; +import ch.qos.logback.core.pattern.color.MagentaCompositeConverter; +import ch.qos.logback.core.pattern.color.RedCompositeConverter; +import ch.qos.logback.core.pattern.color.WhiteCompositeConverter; +import ch.qos.logback.core.pattern.color.YellowCompositeConverter; +import ch.qos.logback.core.pattern.parser.Parser; + +public class CustomPatternLayout extends PatternLayoutBase { + public static final Map defaultConverterMap = new HashMap(); + public static final String HEADER_PREFIX = "#logback.classic pattern: "; + + static { + defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); + defaultConverterMap.put("d", DateConverter.class.getName()); + defaultConverterMap.put("date", DateConverter.class.getName()); + defaultConverterMap.put("r", RelativeTimeConverter.class.getName()); + defaultConverterMap.put("relative", RelativeTimeConverter.class.getName()); + defaultConverterMap.put("level", LevelConverter.class.getName()); + defaultConverterMap.put("le", LevelConverter.class.getName()); + defaultConverterMap.put("p", LevelConverter.class.getName()); + defaultConverterMap.put("t", ThreadConverter.class.getName()); + defaultConverterMap.put("thread", ThreadConverter.class.getName()); + defaultConverterMap.put("lo", LoggerConverter.class.getName()); + defaultConverterMap.put("logger", LoggerConverter.class.getName()); + defaultConverterMap.put("c", LoggerConverter.class.getName()); + defaultConverterMap.put("m", MessageConverter.class.getName()); + defaultConverterMap.put("msg", MessageConverter.class.getName()); + defaultConverterMap.put("message", MessageConverter.class.getName()); + defaultConverterMap.put("C", CustomClassOfCallerConverter.class.getName()); + defaultConverterMap.put("class", CustomClassOfCallerConverter.class.getName()); + defaultConverterMap.put("M", CustomMethodOfCallerConverter.class.getName()); + defaultConverterMap.put("method", CustomMethodOfCallerConverter.class.getName()); + defaultConverterMap.put("L", CustomLineOfCallerConverter.class.getName()); + defaultConverterMap.put("line", CustomLineOfCallerConverter.class.getName()); + defaultConverterMap.put("F", CustomFileOfCallerConverter.class.getName()); + defaultConverterMap.put("file", CustomFileOfCallerConverter.class.getName()); + defaultConverterMap.put("X", MDCConverter.class.getName()); + defaultConverterMap.put("mdc", MDCConverter.class.getName()); + defaultConverterMap.put("ex", ThrowableProxyConverter.class.getName()); + defaultConverterMap.put("exception", ThrowableProxyConverter.class.getName()); + defaultConverterMap.put("rEx", RootCauseFirstThrowableProxyConverter.class.getName()); + defaultConverterMap.put("rootException", RootCauseFirstThrowableProxyConverter.class.getName()); + defaultConverterMap.put("throwable", ThrowableProxyConverter.class.getName()); + defaultConverterMap.put("xEx", ExtendedThrowableProxyConverter.class.getName()); + defaultConverterMap.put("xException", ExtendedThrowableProxyConverter.class.getName()); + defaultConverterMap.put("xThrowable", ExtendedThrowableProxyConverter.class.getName()); + defaultConverterMap.put("nopex", NopThrowableInformationConverter.class.getName()); + defaultConverterMap.put("nopexception", NopThrowableInformationConverter.class.getName()); + defaultConverterMap.put("cn", ContextNameConverter.class.getName()); + defaultConverterMap.put("contextName", ContextNameConverter.class.getName()); + defaultConverterMap.put("caller", CallerDataConverter.class.getName()); + defaultConverterMap.put("marker", MarkerConverter.class.getName()); + defaultConverterMap.put("property", PropertyConverter.class.getName()); + defaultConverterMap.put("n", LineSeparatorConverter.class.getName()); + defaultConverterMap.put("black", BlackCompositeConverter.class.getName()); + defaultConverterMap.put("red", RedCompositeConverter.class.getName()); + defaultConverterMap.put("green", GreenCompositeConverter.class.getName()); + defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName()); + defaultConverterMap.put("blue", BlueCompositeConverter.class.getName()); + defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName()); + defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName()); + defaultConverterMap.put("white", WhiteCompositeConverter.class.getName()); + defaultConverterMap.put("gray", GrayCompositeConverter.class.getName()); + defaultConverterMap.put("boldRed", BoldRedCompositeConverter.class.getName()); + defaultConverterMap.put("boldGreen", BoldGreenCompositeConverter.class.getName()); + defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName()); + defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName()); + defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName()); + defaultConverterMap.put("boldCyan", BoldCyanCompositeConverter.class.getName()); + defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName()); + defaultConverterMap.put("highlight", HighlightingCompositeConverter.class.getName()); + defaultConverterMap.put("lsn", LocalSequenceNumberConverter.class.getName()); + } + + public CustomPatternLayout() { + this.postCompileProcessor = new EnsureExceptionHandling(); + } + + public Map getDefaultConverterMap() { + return defaultConverterMap; + } + + public String doLayout(ILoggingEvent event) { + return !this.isStarted() ? CoreConstants.EMPTY_STRING : this.writeLoopOnConverters(event); + // if(!this.isStarted()){ + // return CoreConstants.EMPTY_STRING; + // } + // String header = this.writeLoopOnConverters(event) + " "; + // StringBuilder sb = new StringBuilder(128); + // StringBuilder buffer = new StringBuilder(); + // + // for(char c : event.getFormattedMessage().toCharArray()){ + // switch(c){ + // case '\r' : continue; + // case '\n' : + // //System.out.println(">>>>>>>>>>>"+ + // "buffer="+header+","+buffer.toString()); + // sb.append(header).append(buffer).append(CoreConstants.LINE_SEPARATOR); + // buffer = new StringBuilder(); + // break; + // default : buffer.append(c); + // } + // } + // sb.append(header).append(buffer).append(CoreConstants.LINE_SEPARATOR); + // return sb.toString(); + } + + protected String getPresentationHeaderPrefix() { + return HEADER_PREFIX; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/util/logger/CustomPatternLayoutEncoder.java b/src/com/eactive/eai/common/util/logger/CustomPatternLayoutEncoder.java new file mode 100644 index 0000000..a75caca --- /dev/null +++ b/src/com/eactive/eai/common/util/logger/CustomPatternLayoutEncoder.java @@ -0,0 +1,16 @@ +package com.eactive.eai.common.util.logger; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.pattern.PatternLayoutEncoderBase; + +public class CustomPatternLayoutEncoder extends PatternLayoutEncoderBase { + public void start() { + CustomPatternLayout patternLayout = new CustomPatternLayout(); + patternLayout.setContext(this.context); + patternLayout.setPattern(this.getPattern()); + patternLayout.setOutputPatternAsHeader(this.outputPatternAsHeader); + patternLayout.start(); + this.layout = patternLayout; + super.start(); + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/common/web/AppInitializer.java b/src/com/eactive/eai/common/web/AppInitializer.java new file mode 100644 index 0000000..3be0059 --- /dev/null +++ b/src/com/eactive/eai/common/web/AppInitializer.java @@ -0,0 +1,225 @@ +package com.eactive.eai.common.web; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import javax.sql.DataSource; +import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.lifecycle.Lifecycle; +import com.eactive.eai.common.lifecycle.LifecycleException; +import com.eactive.eai.common.lifecycle.LifecycleManager; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.dao.Keys; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.ServiceLocator; +import com.eactive.eai.common.util.ServiceLocatorException; + +/** + * 1. 기능 : EAI FrameWork이 초기화(Deploy)될 때 실행되어야 할 작업을 정의 + * 2. 처리 개요 : Logger초기화, LifecycleManager를 통한 Manager 초기화 + * * - + * 3. 주의사항 + * + * @author : + * @version : v 1.0.0 + * @see : Logger.java, LifecycleManager.java + * @since : + */ +public class AppInitializer implements InitializingBean, DisposableBean { + + private DataSource dataSource; + + private String instName; + + private String tableOwner; + + private String systemMode = "D"; //EAI System Mode : [P/T/D/S] + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + public void setInstName(String instName) { + this.instName = instName; + } + + public void setTableOwner(String tableOwner) { + this.tableOwner = tableOwner; + } + + public void setSystemMode(String systemMode) { + this.systemMode = systemMode; + } + /** + * 1. 기능 : EAI FrameWork의 웹어플리케이션이 될 때 초기화 작업을 수행 + * 2. 처리 개요 : EAI FrameWork의 웹어플리케이션이 디플로이될 때 PropManager, Logger, LifecycleManager를 기동하여 + * 초기화작업을 수행한다. + * 3. 주의사항 + * - appicationContext에 정의된 DataSource를 사용하도록 처리 됨 + * @return void + * @exception + **/ + + private void init() + { + Logger logger = Logger.getLogger("root"); + String serverName = System.getProperty("inst.Name"); + if(serverName == null) { + System.setProperty("inst.Name", instName); +// System.setProperty("weblogic.Name", instName); + } + + String tOwner = System.getProperty(Keys.TABLE_OWNER_KEY); + if(tOwner == null) { + System.setProperty(Keys.TABLE_OWNER_KEY, tableOwner); + } + + String sMode = System.getProperty(com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE); + if(sMode == null) { + System.setProperty(com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE, systemMode); + } + + // set Spring dataSource to ServiceLoactor + try { + ServiceLocator sl = ServiceLocator.getInstance(); + sl.putDataSource(Keys.EAI_DATASOURCE, dataSource); + System.out.println("\n@@ " + Keys.EAI_DATASOURCE + " = " + dataSource); + } catch (ServiceLocatorException e1) { + e1.printStackTrace(); + } + + System.out.println("\n@@ ElinkBAP Framework ====================================================="); + System.out.println("@ Batch System Config Initializing---------------------------------- "); + try { + String tableOwner = System.getProperty(com.eactive.eai.common.dao.Keys.TABLE_OWNER_KEY); + String systemMode = System.getProperty(com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE); + + if(tableOwner == null || tableOwner.trim().length() == 0 || + systemMode == null || systemMode.trim().length() == 0 ) { + System.out.println("=========================================================================="); + System.out.println("# E R R O R : Batch System Configuration"); + System.out.println("# Check Start Script Rule table Owner : -D"+com.eactive.eai.common.dao.Keys.TABLE_OWNER_KEY+"="); + System.out.println("# Check Start Script Batch System Mode : -D"+com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE+"="); + System.out.println("# Batch System Mode : [P/T/D/S]"); + System.out.println("=========================================================================="); + throw new Exception(" Rule Table Owner Not Configured "); + } + + System.out.println("=========================================================================="); + System.out.println("# S U C C E S S : Batch System Configuration"); + System.out.println("# Rule table Owner : "+tableOwner); + System.out.println("# Batch System Mode : "+systemMode); + System.out.println("# Batch System Mode : [P(Product)/T(Test)/D(Develop)/S(Simulator)]"); + System.out.println("=========================================================================="); + + } catch(Exception e) { + throw new RuntimeException("EAI System Configuration Error - " + e.getMessage()); + } + + + logger.debug("Property 메모리 로딩 시작 ------------------------------------------"); + try { + PropManager.getInstance().start(); + } catch(LifecycleException e) { + logger.error( e.getMessage(), e); + throw new RuntimeException(ExceptionUtil.getErrorCode(e,"BFCEAICWB001")); + } + logger.debug("Property 메모리 로딩 종료 ------------------------------------------"); + + logger.debug("Logger 메모리 로딩 시작 ------------------------------------------"); + try { + Logger.doConfigure(); + } catch(Exception e) { + logger.error( e.getMessage(), e); + } + logger.debug("Logger 메모리 로딩 종료 ------------------------------------------"); + + try { + SchedulerMessageManager.getInstance().deleteJobFromProcessing(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + try { + Class clazz = Class + .forName("com.eactive.eai.rms.client.context.MonitoringContextFactory"); + Object factory = clazz.newInstance(); + Method method = clazz.getMethod("create"); + method.invoke(factory); + System.out.println("RMSCLIENT AGENT STARTED ~~ !!!!"); + logger.warn("EMSCLIENT AGENT STARTED ~~ !!!!"); + } catch (InvocationTargetException e) { + System.out.println("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.getTargetException().toString()); + logger.error("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.getTargetException().toString(),e.getTargetException()); + e.getTargetException().printStackTrace(); + } catch (Throwable e) { + System.out.println("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.toString()); + logger.error("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.toString(),e); + } + + logger.debug("LifeCycle 관련 클래스 메모리 로딩 시작 ------------------------------------------"); + LifecycleManager manager = LifecycleManager.getInstance(); + if(manager instanceof Lifecycle) { + try { + manager.start(); + } catch(LifecycleException e) { + logger.error( e.getMessage(), e); + throw new RuntimeException(ExceptionUtil.getErrorCode(e,"BECEAICWB002")); + } + } + + logger.debug("LifeCycle 관련 클래스 메모리 로딩 종료 ------------------------------------------"); + logger.debug("배치 프레임웍 Application 초기화 종료!"); + } + + /** + * 1. 기능 : EAI FrameWork의 웹어플리케이션이 Undeploy될 때 초기화된 Manager들을 중지시킴 + * 2. 처리 개요 : EAI FrameWork의 웹어플리케이션이 Undeploy될 때 LifecycleManager를 통해 Manager를 중지시킨다. + * + * 3. 주의사항 + * + * @param ServletContextEvent + * @return void + * @exception + **/ + public void destroy() + { + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + logger.debug("@ eLink Batch Application destroying."); + + + LifecycleManager manager = LifecycleManager.getInstance(); + if(manager instanceof Lifecycle) { + try { + manager.stop(); + } catch(LifecycleException e) { + throw new RuntimeException(ExceptionUtil.getErrorCode(e,"BECEAICWB003")); + } + } + + try { + PropManager.getInstance().stop(); + } catch(LifecycleException e) { + throw new RuntimeException(ExceptionUtil.getErrorCode(e,"BECEAICWB004")); + } + + try { + SocketAdapterManager.getInstance().stop(); + } catch ( Exception e ) { + throw new RuntimeException(ExceptionUtil.getErrorCode(e,"BECEAICWB005")); + } + logger.debug("\n\n"); + } + @Override + public void afterPropertiesSet() throws Exception { + init(); + } + +} diff --git a/src/com/eactive/eai/inbound/FileEventListener.java b/src/com/eactive/eai/inbound/FileEventListener.java new file mode 100644 index 0000000..330c229 --- /dev/null +++ b/src/com/eactive/eai/inbound/FileEventListener.java @@ -0,0 +1,202 @@ +package com.eactive.eai.inbound; + +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.batch.job.jobConstant.TelegramKeys; + +import com.eactive.eai.batch.scheduler.ScheduleSendProcess; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +//import com.eactive.eai.batch.xecure.XecureManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.routing.Process; +import com.eactive.eai.common.util.Logger; + +public class FileEventListener extends Process{ + + // FileLoger + static Logger logger = Logger.getLogger(Logger.LOGGER_FILEEVENT); + private String targetDir; +// private String errorDir; + private BatchDoc batchMsgDoc ; + private String dirPath; + private String fileName; + + public void procFileEvent(String recvdirPath, String recvfileName, String line){ + + String chkExt = BatchDirUtil.getRequestRootExt(); + dirPath = recvdirPath; + fileName = recvfileName.substring(0, recvfileName.length()-chkExt.length()); + + try { + getFileEventInfo(); + callFileMover(); + closeLog(); + + batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(line); + + ScheduleSendProcess process = new ScheduleSendProcess(); + process.proc(batchMsgDoc); + } catch (Exception e) { + catchException(e); + } + } + private void getFileEventInfo() throws Exception + { + // 수신한 파일 정보 + logger.info("[Send File Event] ========================================================================="); + logger.info("[Send File Event] ▶▶▶▶▶▶▶▶▶▶ Local 송신 FILE EVENT 발생 !! ◀◀◀◀◀◀◀◀◀◀"); + logger.info("[Send File Event] ※ Event 디렉토리 : [" + dirPath +"]"); + logger.info("[Send File Event] ※ Event 파일명 : [" + fileName +"]"); + logger.info("[Send File Event] ========================================================================="); + + //업무구분코드 + String processCode = fileName.substring(0, 5); + String institutionCode = fileName.substring(6, 10); + logger.info("processCode = " + processCode); + logger.info("institutionCode = " + institutionCode); + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + int orgIndex = 0; + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(processCode, institutionCode); + String institutionName = organInfo.getOsdName(); + String processName = organInfo.getBatchName(); + bizCodeStartIndex = organInfo.getBizCdStartIdx(); + bizCodeEndIndex = organInfo.getBizCdEndIdx(); + orgIndex = organInfo.getBizCdEndIdx(); + logger.info("processName = " + processName); + + String sFileName = fileName.substring(11); + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= sFileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex == 0 || bizCodeEndIndex > sFileName.length()) bizCodeEndIndex = sFileName.length(); + if (bizCodeEndIndex < 0 && 0 < sFileName.length() + bizCodeEndIndex ) bizCodeEndIndex = sFileName.length() + bizCodeEndIndex; + String bizCode = sFileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + // 거래 구분 코드 길이가 가변인 경우( END INDEX가 0인 경우) + if ( orgIndex == 0 ){ + String delStr = null; + try { + Properties orgInfo = PropManager.getInstance().getProperties( TelegramKeys.PROP_GROUP_NAME_PREFIX + + "{" + processCode + "_" + institutionCode + "}"); + delStr = orgInfo.getProperty( "del.string" ); + } catch (Exception e) {} + + if ( delStr != null && !delStr.trim().equals("")){ + int delIndex = bizCode.indexOf(delStr); + if ( delIndex > -1 ) { + bizCode = bizCode.substring(0, delIndex ); + } + } + } + + logger.info("[Send File Event] -------------------------------------------------------------------------"); + logger.info("[Send File Event] ■ File Event 파싱 정보"); + logger.info("[Send File Event] - 수신디렉토리: [" + dirPath +"]"); + logger.info("[Send File Event] - 수신파일명 : [" + sFileName +"]"); + logger.info("[Send File Event] - 업무구분코드: [" + processCode +"] (업무구분명: "+ processName +")"); + logger.info("[Send File Event] - 대외기관코드: [" + institutionCode +"] (대외기관명: "+ institutionName +")"); + logger.info("[Send File Event] - 거래구분코드: [" + bizCode +"]"); + logger.info("[Send File Event] -------------------------------------------------------------------------"); + + /* 저장할 디렉토리 및 파일정보 + * sourceDir : 파일을 읽어올 최상위 디렉토리 + * targetDir : 파일을 저장할 디렉토리 + * + * 현재는 FileEvent에 의해서 옮겨지는 Arch디렉토리가 읽어 올 디렉토리가 된다. (sourceDir) + * Arch 디렉토리에 있는 파일을 읽어서 Arch디렉토리 밑에 업무코드명과 동일하게 디렉토리를 만들고 저장한다. + */ + targetDir = BatchDirUtil.getRequestArchDir() +"/"+ processCode +"/"+ institutionCode ; + //errorDir = BatchDirUtil.getRequestErrorDir()+"/"+ processCode +"/"+ institutionCode ; + + /* + * FileEvent가 SchedulerProcess로 전달할 기본 EAIBatchMsg를 생성한다. + * FileEventListener가 입력가능한 값들은 EAIBatchMsg의 항목 중 다음과 같다. + * - UUID + * - Layer 구분 코드 (한시적) + * - ProcessCode: 수신한 서브디렉토리와 동일 + * - FileName : 송수신 원 파일명 + * - FilePath : 파일이 실재 존재하는 디렉토리 + * - RenamedFileName : 저장후 이름이 변경된 파일명 + */ + // BatchMsgDoc 생성 + batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(false); //UUID 생성, false:초기화안함 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_FILE_EVENT, CommonKeys.SUB_LAYER_FILE_EVENT); // layer, flowPahse, 시작시간 설정 + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(processCode); // 업무코드 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_REQUEST_SEND); // 업무유형 (요구송신 설정) + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(institutionCode); // 대외기관코드 + batchMsgDoc.getBatchMsg().getHeader().setFileName(sFileName); // 원 파일명 + batchMsgDoc.getBatchMsg().getHeader().setFilePath(targetDir); // 파일이 실재 존재하는 디렉토리 + batchMsgDoc.getBatchMsg().getHeader().setFileErrorPath(targetDir); // 장애발생시 실파일이 이동할 디렉토리를 지정한다. + batchMsgDoc.getBatchMsg().getHeader().setBizCode(bizCode); // 거래구분코드 + } + + private void callFileMover() throws Exception + { + String renamedFileName = fileName.substring(11) + "_" + CalendarUtil.getCurrentTimeNoDash(); + File realFile = new File(this.dirPath +"/"+ fileName); + File archFile = new File(this.targetDir +"/"+ renamedFileName); + + //Root 디렉토리에서 Arch 디렉토리로 파일 이동 + logger.info("[Send File Event] -------------------------------------------------------------------------"); + logger.info("[Send File Event] ■ 요구송신 파일 이동 (송신_Real -> 송신_Arch)"); + logger.info("[Send File Event] - Real 디렉토리: ["+ this.dirPath +"/"+ fileName +"] (exists: "+ realFile.exists() +")"); + logger.info("[Send File Event] - Arch 디렉토리: ["+ this.targetDir +"/"+ renamedFileName +"] (exists: "+ archFile.exists() +")"); + logger.info("[Send File Event] - 변경된 파일명: " + renamedFileName); + logger.info("[Send File Event] -------------------------------------------------------------------------"); + + boolean isSuccessMoveFile = FileUtil.copyTransferFile(realFile, archFile, true); + + if (!isSuccessMoveFile) { + String errMsg = ExceptionUtil.getErrorCode("BECEAIIFE002", new String[] {realFile.getAbsolutePath(), archFile.getAbsolutePath()}); + throw new Exception(errMsg); //요구송신 데이터파일을 송신_Real 디렉토리({1})에서 송신_Arch 디렉토리({2})로 이동시 실패하였습니다. + } + batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(renamedFileName); //변경된 파일명 설정 + } + private void closeLog() throws Exception + { + // 종료시간을 추가한다. + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + // 요구송신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (batchMsgDoc); + logger.info("[Send File Event] ※ Event 파일명 : [" + fileName +"]"); + + } + + private void catchException(Exception ex) + { + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIIFE001"); + logger.error(errMsg, ex); //Local 송신 File Event Listener 에서 오류가 발생하였습니다. + + // DB로그 처리 + batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchMsgDoc, errMsg); + + } catch (Exception e) { + logger.error("[Send File Event] ★★★★★ Local 송신 File Event Listner 예외 처리 중 에러 !! ★★★★★", e); + } + } + @Override + public BatchDoc clientRequestwithReturn( + BatchDoc batchDoc) throws Exception { + return null; + } + @Override + public void clientRequest() throws Exception { + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/inbound/RecvFileEventListener.java b/src/com/eactive/eai/inbound/RecvFileEventListener.java new file mode 100644 index 0000000..043f4eb --- /dev/null +++ b/src/com/eactive/eai/inbound/RecvFileEventListener.java @@ -0,0 +1,74 @@ +package com.eactive.eai.inbound; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.routing.Process; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.inbound.remote.RemoteTransfer; +import com.eactive.eai.inbound.remote.RemoteTransferLogKeys; + +public class RecvFileEventListener extends Process{ + + // FileLoger + static Logger logger = Logger.getLogger(Logger.LOGGER_FILEEVENT); + + + + +// private String dirPath; +// private String fileName; + + + public void procFileEvent(String dirPath, String fileName, String lines){ + + + logger.info("[Recv File Event] ========================================================================="); + logger.info("[Recv File Event] ▶▶▶▶▶▶▶▶▶▶ Local 수신 FILE EVENT 발생 !! ◀◀◀◀◀◀◀◀◀◀"); + + logger.info("[Recv File Event] ※ Event 디렉토리 : [" + dirPath +"]"); + logger.info("[Recv File Event] ※ Event 파일명 : [" + fileName +"]"); + logger.info("[Recv File Event] ========================================================================="); + + + try { + String recvRoot = BatchDirUtil.getResponseRootDir(); + if ( dirPath.indexOf(recvRoot) < 0 ){ + logger.error("경로 지정 오류입니다. 이벤트 발생 경로-->" + dirPath + ", 수신_Root-->" + recvRoot); + return; + } + String instPath = StringUtil.replaceStr( dirPath, recvRoot, "" ); + if ( instPath.startsWith("/")) + instPath = instPath.substring(1); + + if ( instPath.endsWith("/")) + instPath = instPath.substring(0, instPath.length()-1); + + String[] arr = instPath.split("/"); + if ( arr.length < 2 ){ + logger.error("수신 기관 경로 지정 오류입니다. 수신 기관 경로-->" + instPath); + return; + } + String procCode = arr[0]; + String instCode = arr[1]; + logger.debug("procCode -->" + procCode); + logger.debug("instCode -->" + instCode); + + RemoteTransfer trans = new RemoteTransfer(); + trans.sendFile(procCode, instCode, fileName, RemoteTransferLogKeys.START_BY_EVENT, RemoteTransferLogKeys.STARTER_SYSTEM, false); + trans.sendFile(procCode, instCode, fileName, RemoteTransferLogKeys.START_BY_EVENT, RemoteTransferLogKeys.STARTER_SYSTEM, true); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + + + @Override + public BatchDoc clientRequestwithReturn( + BatchDoc batchDoc) throws Exception { + return null; + } + @Override + public void clientRequest() throws Exception { + } +} diff --git a/src/com/eactive/eai/inbound/ReqRecvEventListener.java b/src/com/eactive/eai/inbound/ReqRecvEventListener.java new file mode 100644 index 0000000..fd4d7c8 --- /dev/null +++ b/src/com/eactive/eai/inbound/ReqRecvEventListener.java @@ -0,0 +1,213 @@ +package com.eactive.eai.inbound; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.routing.Process; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +public class ReqRecvEventListener extends Process{ + + // FileLoger + static Logger logger = Logger.getLogger(Logger.LOGGER_FILEEVENT); + private BatchDoc batchMsgDoc ; + private String dirPath; + private String fileName; + private SchedulerMessageVO info; + private String processCode; + private String institutionCode; + + + public void procFileEvent(String recvdirPath, String recvfileName, String lines){ + + dirPath = recvdirPath; + fileName = recvfileName; + + try { + getFileEventInfo(); + callFileMover(); + closeLog(); + + } catch (Exception e) { + catchException(e); + } + } + private void getFileEventInfo() throws Exception + { + // 수신한 파일 정보 + logger.info("[Req Recv File Event] ========================================================================="); + logger.info("[Req Recv File Event] ▶▶▶▶▶▶▶▶▶▶ Local 송신 FILE EVENT 발생 !! ◀◀◀◀◀◀◀◀◀◀"); + logger.info("[Req Recv File Event] ※ Event 디렉토리 : [" + dirPath +"]"); + logger.info("[Req Recv File Event] ※ Event 파일명 : [" + fileName +"]"); + logger.info("[Req Recv File Event] ========================================================================="); + + // 디렉토리 구조를 파싱하여 업무구분코드, 대외기관코드, 거래구분그룹 정보를 조회한다. + // 각 디렉토리명은 다음과같은 규칙으로 정의된다. + // 기본 ROOT : Property Table에 등록 ... + // 기본 ROOT 이하 + // --> 2단계 (업무코드/대외기관코드) + String strBaseDir = BatchDirUtil.getReqRecvRootDir(); //요구수신_Root 기준 디렉토리 + strBaseDir = strBaseDir.replaceAll("\\\\", "/"); + dirPath = dirPath.replaceAll("\\\\", "/"); + logger.info("※ BaseDir info in DB : [" + strBaseDir +"]"); + + int n = dirPath.indexOf(strBaseDir); + if (n < 0) { + throw new Exception("FILE EVENT directory is not match with Base Directory information in DB Table(TSEAIBP02)"); + } + + // 요구수신_Root 기준 디렉토리 이후의 디렉토리 구조를 잘라낸다. + dirPath = dirPath.substring(n); + dirPath = dirPath.substring(strBaseDir.length()); + logger.info("※ SubDir removed BaseDir : [" + dirPath +"]"); + + int index1 = (dirPath.charAt(0) == '/')? 1 : 0; + int index2 = dirPath.indexOf("/", index1+1); + + logger.info("index1="+index1+", index2="+index2); + + //업무구분 디렉토리 설정 (업무구분명_업무구분코드) + if (index2 < 0) { + throw new Exception("FILE EVENT directory is not proper. No subdirectory directed releated with Institution"); + } else { + processCode = dirPath.substring(index1, index2); + } + institutionCode = dirPath.substring(index2+1); + + logger.info("processCode = " + processCode); + + logger.info("institutionCode = " + institutionCode); + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(processCode, institutionCode); + String institutionName = organInfo.getOsdName(); + String processName = organInfo.getBatchName(); + bizCodeStartIndex = organInfo.getBizCdStartIdx(); + bizCodeEndIndex = organInfo.getBizCdEndIdx(); + logger.info("processName = " + processName); + + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + logger.info("[Req Recv File Event] -------------------------------------------------------------------------"); + logger.info("[Req Recv File Event] ■ File Event 파싱 정보"); + logger.info("[Req Recv File Event] - 수신디렉토리: [" + dirPath +"]"); + logger.info("[Req Recv File Event] - 수신파일명 : [" + fileName +"]"); + logger.info("[Req Recv File Event] - 업무구분명 : [" + processName +"] (업무구분코드: "+ processCode +")"); + logger.info("[Req Recv File Event] - 대외기관명 : [" + institutionName +"] (대외기관코드: "+ institutionCode +")"); + logger.info("[Req Recv File Event] - 거래구분코드: [" + bizCode +"]"); + logger.info("[Req Recv File Event] -------------------------------------------------------------------------"); + + + /* + * FileEvent가 SchedulerProcess로 전달할 기본 EAIBatchMsg를 생성한다. + * FileEventListener가 입력가능한 값들은 EAIBatchMsg의 항목 중 다음과 같다. + * - UUID + * - Layer 구분 코드 (한시적) + * - ProcessCode: 수신한 서브디렉토리와 동일 + * - FileName : 송수신 원 파일명 + * - FilePath : 파일이 실재 존재하는 디렉토리 + * - RenamedFileName : 저장후 이름이 변경된 파일명 + */ + // BatchMsgDoc 생성 + batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(false); //UUID 생성, false:초기화안함 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_FILE_EVENT, CommonKeys.SUB_LAYER_FILE_EVENT); // layer, flowPahse, 시작시간 설정 + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(processCode); // 업무코드 + batchMsgDoc.getBatchMsg().getHeader().setProcessName(processName); // 업무명 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_REQUEST_RECEIVE); // 업무유형 (요구송신 설정) + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(institutionCode); // 대외기관코드 + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(institutionName); // 대외기관명 + batchMsgDoc.getBatchMsg().getHeader().setFileName(fileName); // 원 파일명 + batchMsgDoc.getBatchMsg().getHeader().setBizCode(bizCode); // 거래구분코드 + info = SchedulerMessageManager.getInstance().getRecvScheduleInfo(bizCode, processCode, institutionCode); + if ( info == null ){ + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC016", new String[] {processCode, institutionCode, bizCode}); + throw new Exception(errMsg); //해당 정보에 대한 스케쥴 정보가 존재하지 않습니다. (업무코드: {1}, 대외기관코드: {2}, 거래구분코드: {3}) + } + } + + private void callFileMover() throws Exception + { + info.setFileName(batchMsgDoc.getBatchMsg().getHeader().getFileName()); + //1. 요구수신 스케쥴러 단계 DB로그를 위한 BatchMsg 객체 생성 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); // layer, flowPahse, 시작시간 설정 + + //2. 요구수신 디렉토리 설정 (수신_Real/업무구분/대외기관/..) + //요구수신 기준 디렉토리 --> 배치업무유형코드(ProcessCode) 와 대외기관코드 (InstitutionCode) 로 계산. + String strPathName = BatchDirUtil.getResponseRealDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + + + StringBuffer sb = new StringBuffer(); + sb.append(processCode); + sb.append("/"); + sb.append(institutionCode); + strPathName = strPathName + sb.toString(); + info.setFilePath(strPathName); + + + //3. UUID 설정 및 스케쥴 송수신 시각 설정 + info.setUUID (batchMsgDoc.getBatchMsg().getHeader().getUUID()); + info.setSubUUID (batchMsgDoc.getBatchMsg().getBody().getSubUUID()); + info.setStartTime(DatetimeUtil.getCurrentDate() + "000000000"); + info.setEndTime (DatetimeUtil.getCurrentDate() + "235900000"); + + //4. Job_Queue 테이블에 등록 + logger.info("[요구수신 스케쥴러] ========================================================================="); + logger.info("[요구수신 스케쥴러] ■ 요구수신 스케쥴 정보를 Job_Queue 테이블에 추가......"); + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(info); + logger.info("[요구수신 스케쥴러] ==> 배치 Job_Queue 테이블 INSERT 건수: "+ resultCnt); + logger.info("[요구수신 스케쥴러] ========================================================================="); + + } + private void closeLog() throws Exception + { + // 단계 종료시간을 추가한다. + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + // 요구송신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (batchMsgDoc); + logger.info("[Req Recv File Event] ※ Event 파일명 : [" + fileName +"]"); + } + + + private void catchException(Exception ex) + { + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIIFE007"); + logger.error(errMsg, ex); //Local 요구수신 File Event Listener 에서 오류가 발생하였습니다. + + // DB로그 처리 + batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg); + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setErrorLog(batchMsgDoc, errMsg); + + } catch (Exception e) { + logger.error("[Req Recv File Event] ★★★★★ 수신 요청 File Event Listner 예외 처리 중 에러 !! ★★★★★", e); + } + } + @Override + public BatchDoc clientRequestwithReturn( + BatchDoc batchDoc) throws Exception { + return null; + } + @Override + public void clientRequest() throws Exception { + } + +} diff --git a/src/com/eactive/eai/inbound/ResponseHandler.java b/src/com/eactive/eai/inbound/ResponseHandler.java new file mode 100644 index 0000000..7bca820 --- /dev/null +++ b/src/com/eactive/eai/inbound/ResponseHandler.java @@ -0,0 +1,59 @@ +package com.eactive.eai.inbound; + +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.routing.Process; +import com.eactive.eai.common.util.Logger; + +public class ResponseHandler +{ + public static final String ADAPTER_GROUP_NAME = "ADAPTER_GROUP_NAME"; + public static final String ADAPTER_NAME = "ADAPTER_NAME"; + + public static final String BATCH_UUID = "BATCH_UUID"; + public static final String BATCH_PROCESS_CODE = "BATCH_PROCESS_CODE"; + public static final String BATCH_PROCESS_SER_NO = "BATCH_PROCESS_SER_NO"; + public static final String BATCH_TELEGRAM_TIMEOUT = "BATCH_TELEGRAM_TIMEOUT"; + public static final String BATCH_SERVER_PORT = "BATCH_SERVER_PORT"; + + static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + public BatchDoc execute(BatchDoc batchMsgDoc) + { + logger.debug("[ELINK]################ ResponseHandler.execute() 호출됨."); + + long srtTime = 0; + srtTime = System.currentTimeMillis(); + + + //응답송수신 Process 호출 + //*** 응답송수신 스케쥴러 Process SKIP! 응답송수신 스케쥴러의 기능이 명확치 않음. 추후 기능정의가 되었을때 추가 예정. <---------- + try { + + // JPD호출 변환 +// FlowController process = (FlowController)JpdProxy.create(FlowController.class, FlowController.SERVICE_URI); + + //Process process = + logger.debug("[ELINK]################ 응답 송수신 JPD 호출 전 BatchMessageDoc: \n"+ batchMsgDoc.toString()); + String className = "com.eactive.eai.batch.job.jobHandle.FlowController"; + @SuppressWarnings("rawtypes") + Class cl = Class.forName(className); + Process process = (Process)cl.newInstance(); + batchMsgDoc = process.clientRequestwithReturn(batchMsgDoc); + logger.debug("[ELINK]################ 응답 송수신 JPD 호출 후 BatchMessageDoc: \n"+ batchMsgDoc.toString()); + + //Process 호출 오류시 오류전문 리턴 + } catch (Exception ex) { + logger.debug("[ELINK]★★★★★★★★ ResponseProcessHandler JPD 호출 시 예외발생 !! ★★★★★★★★"); + logger.debug(ex.getMessage()); + //오류전문 설정 및 DB로깅 + //RTMPSResponseUtil.setOutsideStageErrorTelegram(batchMsgDoc, null, srtTime, ex); + String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFAR004"); //응답수신 예외전문 생성 후 DB로그 저장시 오류가 발생하였습니다. + logger.error(errMsg, ex); + } + logger.debug("[ELINK]################ FLOW_PHASE_CODE: "+ batchMsgDoc.getBatchMsg().getBody().getSubLayerCode()); + logger.debug("[ELINK]################ ResponseHandler.execute() 종료. (수행 시간: "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec)"); + return batchMsgDoc; + } + +} diff --git a/src/com/eactive/eai/inbound/event/FileEventJob.java b/src/com/eactive/eai/inbound/event/FileEventJob.java new file mode 100644 index 0000000..4be0c81 --- /dev/null +++ b/src/com/eactive/eai/inbound/event/FileEventJob.java @@ -0,0 +1,88 @@ +package com.eactive.eai.inbound.event; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.List; + +import org.quartz.DisallowConcurrentExecution; +import org.quartz.Job; +import org.quartz.JobExecutionContext; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.common.routing.Process; +import com.eactive.eai.common.util.Logger; + +@DisallowConcurrentExecution +public class FileEventJob implements Job { + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public void execute(JobExecutionContext context) + { + String dir = context.getJobDetail().getJobDataMap().getString("DIR"); + String msg = context.getJobDetail().getJobDataMap().getString("MSG"); + + try { + File rootDir = new File(dir); + if ( rootDir == null || !rootDir.isDirectory()){ + logger.error( this.getClass().getName() + ":디렉터리 지정이 올바르지 않습니다. -" + dir); + return; + } + List fileList = FileUtil.getSendFileList(rootDir); + + for (File file : fileList) { + String chkExt = BatchDirUtil.getRequestRootExt(); + if ( !file.getName().endsWith(chkExt)){ + continue; + } + String line = getFileContent(file); + if ( line == null ){ + continue; + } + + String path = file.getParent(); + String fileName = file.getName(); + if ( file.delete() ){ + @SuppressWarnings("rawtypes") + Class cl = Class.forName(msg); + Process process = (Process)cl.newInstance(); + process.procFileEvent(path, fileName, line); + }else{ + logger.error( this.getClass().getName() + ":체크 파일을 삭제 할 수 없습니다. -" + file.getAbsolutePath()); + } + } + + } catch (Exception e) { + logger.error("FileEventJob 실행도중 에러가 발생하였습니다. -" + e.getMessage()); + } + } + + private String getFileContent( File file ){ + BufferedReader fbr = null; + try { + fbr = new BufferedReader(new FileReader(file)); + String line = fbr.readLine(); + if ( line != null && line.endsWith("@@")){ + return line; + } + } catch (Exception e) { + logger.error(e.getMessage(),e); + }finally{ + try { + if ( fbr != null ) + fbr.close(); + } catch (Exception e2) {} + } + return null; + } + public void setDIR( String dir){ + return; + } + public void setMSG( String msg){ + return; + } + public void setTYPE( String type){ + return; + } +} diff --git a/src/com/eactive/eai/inbound/event/RecvEventJob.java b/src/com/eactive/eai/inbound/event/RecvEventJob.java new file mode 100644 index 0000000..c3cbf5b --- /dev/null +++ b/src/com/eactive/eai/inbound/event/RecvEventJob.java @@ -0,0 +1,54 @@ +package com.eactive.eai.inbound.event; + +import java.io.File; +import java.util.List; + +import org.quartz.DisallowConcurrentExecution; +import org.quartz.Job; +import org.quartz.JobExecutionContext; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.common.routing.Process; +import com.eactive.eai.common.util.Logger; + +@DisallowConcurrentExecution +public class RecvEventJob implements Job { + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public void execute(JobExecutionContext context) + { + String dir = context.getJobDetail().getJobDataMap().getString("DIR"); + String msg = context.getJobDetail().getJobDataMap().getString("MSG"); + + try { + File rootDir = new File(dir); + if ( rootDir == null || !rootDir.isDirectory()){ + logger.error( this.getClass().getName() + ":디렉터리 지정이 올바르지 않습니다. -" + dir); + return; + } + List fileList = FileUtil.getFileList(rootDir); + for (File file : fileList) { + String path = file.getParent().replaceAll("\\\\", "/")+"/"; + String fileName = file.getName(); + if ( file.exists() && file.delete() ){ + @SuppressWarnings("rawtypes") + Class cl = Class.forName(msg); + Process process = (Process)cl.newInstance(); + process.procFileEvent(path, fileName, ""); + } + } + + } catch (Exception e) { + logger.error("FileEventJob 실행도중 에러가 발생하였습니다. -" + e.getMessage()); + } + } + public void setDIR( String dir){ + return; + } + public void setMSG( String msg){ + return; + } + public void setTYPE( String type){ + return; + } +} diff --git a/src/com/eactive/eai/inbound/event/ReqFileEventJob.java b/src/com/eactive/eai/inbound/event/ReqFileEventJob.java new file mode 100644 index 0000000..08fee5b --- /dev/null +++ b/src/com/eactive/eai/inbound/event/ReqFileEventJob.java @@ -0,0 +1,60 @@ +package com.eactive.eai.inbound.event; + +import java.io.File; +import java.util.List; + +import org.quartz.DisallowConcurrentExecution; +import org.quartz.Job; +import org.quartz.JobExecutionContext; + +import com.eactive.eai.batch.common.FileUtil; +import com.eactive.eai.common.routing.Process; +import com.eactive.eai.common.util.Logger; + +@DisallowConcurrentExecution +public class ReqFileEventJob implements Job { + static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER); + + public void execute(JobExecutionContext context) + { + String dir = context.getJobDetail().getJobDataMap().getString("DIR"); + String msg = context.getJobDetail().getJobDataMap().getString("MSG"); + + try { + File rootDir = new File(dir); + if ( rootDir == null || !rootDir.isDirectory()){ + logger.error( this.getClass().getName() + ":디렉터리 지정이 올바르지 않습니다. -" + dir); + return; + } + List fileList = FileUtil.getFileList(rootDir); + + for (File file : fileList) { + + String path = file.getParent(); + String fileName = file.getName(); + if ( file.delete() ){ + @SuppressWarnings("rawtypes") + Class cl = Class.forName(msg); + Process process = (Process)cl.newInstance(); + process.procFileEvent(path, fileName, null); + }else{ + logger.error( this.getClass().getName() + ":체크 파일을 삭제 할 수 없습니다. -" + file.getAbsolutePath()); + } + } + + } catch (Exception e) { + logger.error("FileEventJob 실행도중 에러가 발생하였습니다. -" + e.getMessage()); + } + } + + + public void setDIR( String dir){ + return; + } + public void setMSG( String msg){ + return; + } + public void setTYPE( String type){ + return; + } +} diff --git a/src/com/eactive/eai/inbound/remote/CommonTransfer.java b/src/com/eactive/eai/inbound/remote/CommonTransfer.java new file mode 100644 index 0000000..7d33d02 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/CommonTransfer.java @@ -0,0 +1,534 @@ +//package com.eactive.eai.inbound.remote; +// +//import java.io.BufferedReader; +//import java.io.File; +//import java.io.InputStreamReader; +// +//import com.eactive.eai.batch.common.BatchDirUtil; +//import com.eactive.eai.batch.common.CalendarUtil; +//import com.eactive.eai.batch.common.ItmsSmsUtil; +//import com.eactive.eai.batch.common.StringUtil; +//import com.eactive.eai.common.property.PropManager; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public abstract class CommonTransfer +//{ +// +// //리모트 전송 프라퍼티 정보 +// public static final String PROP_GROUP_REMOTE_TRANSFER = "RemoteTransferInfo"; +// public static final String PROP_EAI_DUMMY_FILE_PATH = "EAI_DUMMY_FILE_PATH"; //EAI 더미파일 경로 (WLI 수신파일 Event Generator 에 설정된 Archive 경로와 같아야함) +// +// public static final String TRANSFER_TYPE_FTP = "FTP"; //DB에 입력되는 값 +// public static final String TRANSFER_TYPE_NDM = "NDM"; //DB에 입력되는 값 +// +// public static final String DIRECTION_SEND = "송신"; //DB에 입력되는 값 +// public static final String DIRECTION_RECEIVE = "수신"; //DB에 입력되는 값 +// +// public static final String STARTING_TYPE_EVENT = "Event"; //DB에 입력되는 값 +// public static final String STARTING_TYPE_UI_NAVI = "UI(탐색)"; //DB에 입력되는 값 +// public static final String STARTING_TYPE_UI_MANUAL = "UI(수동)"; //DB에 입력되는 값 +// +// public static final String RESULT_CODE_SUCCESS = "0"; //정상 +// public static final String RESULT_CODE_PROCESSING = "P"; //진행중 +// public static final String RESULT_CODE_UNEXPECTED_ERROR = "999"; //오류 +// +// public static final String SMSINFO = "SMSInfo"; +// public static final String TRANS_MSG = "trans.msg"; +// public static final String TRANS_LEVEL = "trans.level"; +// +// protected static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT); +// +// protected RemoteTransferLogVO logInfo; +// protected boolean isLogging = true; +// protected String scriptErrorMsg = ""; +// protected String scriptOutputMsg = ""; +// private String applCd = ""; +// +// private static String getPropEaiDummyPath() throws Exception { +// String eaiDummyPath = PropManager.getInstance().getProperty(PROP_GROUP_REMOTE_TRANSFER, PROP_EAI_DUMMY_FILE_PATH); +// if (eaiDummyPath == null) throw new Exception("'EAI 리모트 송신 더미파일 경로' 프라퍼티 정보가 없습니다. (PropGroupName:"+ PROP_GROUP_REMOTE_TRANSFER +", PropName:"+ PROP_EAI_DUMMY_FILE_PATH +")"); +// //디렉토리 맨끝에 "/" 가 있으면 빼로 리턴 +// return eaiDummyPath.endsWith("/")? eaiDummyPath.substring(0, eaiDummyPath.length()-1) : eaiDummyPath; +// } +// +// public RemoteTransferLogVO getTransferLogVO() { +// return this.logInfo; +// } +// +// public static void sendFileByEvent(String eaiDir, String eaiFile) throws Exception { +// transferFileByEvent(DIRECTION_SEND, eaiDir, eaiFile, "", ""); +// } +// +// public static void receiveFileByEvent(String remoteDir, String remoteFile) throws Exception { +// transferFileByEvent(DIRECTION_RECEIVE, "", "", remoteDir, remoteFile); +// } +// +// public static void transferFileByEvent(String sendRecvType, String eaiDir, String eaiFile, String remoteDir, String remoteFile) throws Exception { +// +// //logger.info("[리모트송수신] ■ 리모트 Event 송수신 시작......"); +// //파라미터 체크 +// if (!sendRecvType.equals(DIRECTION_SEND) && !sendRecvType.equals(DIRECTION_RECEIVE)) throw new Exception("{송수신구분} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_SEND) && eaiDir.equals("")) throw new Exception("{EAI 디렉토리} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_SEND) && eaiFile.equals("")) throw new Exception("{EAI 파일명} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_RECEIVE) && remoteDir.equals("")) throw new Exception("{리모트 디렉토리} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_RECEIVE) && remoteFile.equals("")) throw new Exception("{리모트 파일명} 파라미터 오류"); +// +// String startingType = STARTING_TYPE_EVENT; +// String userId = "admin"; +// +// //--------------------------------------------------------------------- +// //1. Path 에 의한 remote Server 정보 조회 +// RemoteServerVO remoteServerVO; +// try { +// //logger.info("[리모트송수신] ▶ 업무구분에 의한 리모트 서버정보 조회..."); +// remoteServerVO = RemoteServerManager.getInstance().getRemoteServerByPath(sendRecvType.equals(DIRECTION_SEND)? eaiDir : remoteDir); +// if (remoteServerVO==null) throw new Exception("해당 Remote 경로에 대한 Remote 서버를 찾을수 없음"); +// } catch (Exception ex) { +// logger.error("[리모트송수신] ★★★★★ 업무구분에 의한 리모트 서버정보 조회시 오류발생 ★★★★★", ex); +// logger.error("[리모트송수신] ▶ 리모트 송수신 오류 로그 기록..."); +// //파일전송 거래 오류로그 DB Insert +// RemoteTransferLogVO logInfo = new RemoteTransferLogVO(); +// logInfo.setTransferLogId ("RTL"+ CalendarUtil.getCurrentTimeNoDash() + StringUtil.getRandomDigit(3)); //전송로그ID 생성 +// logInfo.setSendRecvType (sendRecvType); +// logInfo.setEaiFilePath (eaiDir); +// logInfo.setEaiFileName (eaiFile); +// logInfo.setRemoteFilePath (remoteDir); +// logInfo.setRemoteFileName (remoteFile); +// logInfo.setStartingType (startingType); +// logInfo.setCreateId (userId); +// logInfo.setResultCode (RESULT_CODE_UNEXPECTED_ERROR); //오류 +// logInfo.setResultMsg (ex.toString()); +// // DEFAULT 세팅 추가 2009.12.17 dhjeong +// logInfo.setTransferType (TRANSFER_TYPE_NDM); +// logInfo.setFransferStartTime(CalendarUtil.getCurrentTimeNoDash()); +// logInfo.setFransferEndTime (CalendarUtil.getCurrentTimeNoDash()); +// +// try { +// RemoteTransferLogManager.getInstance().insertRemoteTransferLog(logInfo); +// } catch (Exception e) { +// logger.error( e.getMessage(), e); +// } +// throw ex; +// } +// +// //--------------------------------------------------------------------- +// //2. 해당 리모트서버에 설정된 전송타입 (FTP/NDM) 에 따른 객체 생성라 파일 송수신 수행 +// CommonTransfer tran = null; +// if (remoteServerVO.getAutoTransferType().equals(TRANSFER_TYPE_FTP)) { +// logger.info("[리모트송수신] ▶ FTP 리모트 송수신 객체 생성..."); +// tran = new FTPTransferByScript(); +// +// } else if (remoteServerVO.getAutoTransferType().equals(TRANSFER_TYPE_NDM)) { +// logger.info("[리모트송수신] ▶ NDM 리모트 송수신 객체 생성..."); +// tran = new NDMTransferByScript(); +// +// } else { +// throw new Exception("리모트 서버 정보의 {자동전송유형} 필드 값이 'FTP' 또는 'NDM' 이 아닙니다. (Value:"+ remoteServerVO.getAutoTransferType() +")"); +// } +// +// //--------------------------------------------------------------------- +// //3. 리모트파일 송수신 수행 +// tran.transferFile(remoteServerVO, sendRecvType, eaiDir, eaiFile, remoteDir, remoteFile, startingType, userId); +// } +// +// public RemoteTransferLogVO transferFile(RemoteServerVO remoteServerVO, +// String sendRecvType, +// String eaiDir, +// String eaiFile, +// String remoteDir, +// String remoteFile, +// String startingType, +// String userId) throws Exception { +// +// logger.info("[리모트송수신] ■ 리모트 송수신 수행 시작......"); +// logger.info("[리모트송수신] ⓟ 송수신구분 : ["+ sendRecvType +"] (송신: EAI→Remote, 수신: Remote→EAI)"); +// logger.info("[리모트송수신] ⓟ EAI 디렉토리 : ["+ eaiDir +"]"); +// logger.info("[리모트송수신] ⓟ EAI 파일명 : ["+ eaiFile +"]"); +// logger.info("[리모트송수신] ⓟ 리모트 디렉토리 : ["+ remoteDir +"]"); +// logger.info("[리모트송수신] ⓟ 리모트 파일명 : ["+ remoteFile +"]"); +// logger.info("[리모트송수신] ⓟ 기동유형 : ["+ startingType +"]"); +// logger.info("[리모트송수신] ⓟ 사용자ID : ["+ userId +"]"); +// +// //파라미터 체크 +// if (remoteServerVO == null) throw new Exception("{리모트서버 VO} 파라미터 오류"); +// if (!sendRecvType.equals(DIRECTION_SEND) && !sendRecvType.equals(DIRECTION_RECEIVE)) throw new Exception("{송수신구분} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_SEND) && eaiDir.equals("")) throw new Exception("{EAI 디렉토리} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_SEND) && eaiFile.equals("")) throw new Exception("{EAI 파일명} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_RECEIVE) && remoteDir.equals("")) throw new Exception("{리모트 디렉토리} 파라미터 오류"); +// if (sendRecvType.equals(DIRECTION_RECEIVE) && remoteFile.equals("")) throw new Exception("{리모트 파일명} 파라미터 오류"); +// if (!startingType.equals(STARTING_TYPE_EVENT) && !startingType.equals(STARTING_TYPE_UI_NAVI) && !startingType.equals(STARTING_TYPE_UI_MANUAL)) throw new Exception("{기동유형} 파라미터 오류"); +// if (userId.equals("")) throw new Exception("{사용자ID} 파라미터 오류"); +// //--------------------------------------------------------------------- +// //1. 리모트파일 전송 시작로그 DB Insert +// //파일전송 로그정보 설정 +// if (logInfo==null) logInfo = new RemoteTransferLogVO(); +// logInfo.setTransferLogId ("RTL"+ CalendarUtil.getCurrentTimeNoDash() + StringUtil.getRandomDigit(3)); //전송로그ID 생성 +// logInfo.setRemoteServerVO (remoteServerVO); +// logInfo.setRemoteServerId (remoteServerVO.getRemoteServerId()); +// logInfo.setSendRecvType (sendRecvType); +// logInfo.setEaiFilePath (eaiDir); +// logInfo.setEaiFileName (eaiFile); +// logInfo.setRemoteFilePath (remoteDir); +// logInfo.setRemoteFileName (remoteFile); +// logInfo.setStartingType (startingType); +// logInfo.setFransferStartTime(CalendarUtil.getCurrentTimeNoDash()); +// logInfo.setCreateId (userId); +// logInfo.setResultCode (RESULT_CODE_PROCESSING); //진행중 +// if (this instanceof FTPTransferByApi || this instanceof FTPTransferByScript) { +// logInfo.setTransferType (TRANSFER_TYPE_FTP); +//// } else if (this instanceof NDMTransferByApi || this instanceof NDMTransferByScript) { +//// logInfo.setTransferType (TRANSFER_TYPE_NDM); +//// String sendRecvGb = null; +//// String fileName = null; +//// String ndmPname = null; +//// +//// // DIRECTION_SEND 의 의미는 EAI-->내부서버이며 여기서 sendRecvGb는 대외기관과의 송수신 구분을 의미하므로 반대로 세팅함. +//// if ( sendRecvType.equals(DIRECTION_SEND) ){ +//// sendRecvGb = "RECV"; +//// }else{ +//// sendRecvGb = "SEND"; +//// } +//// int index = eaiFile.indexOf('_'); +//// if ( index > 0 ) { +//// fileName = eaiFile.substring(0,index); +//// }else{ +//// fileName = eaiFile; +//// } +//// if ( fileName.length() > 7 ){ +////// ndmPname = sendRecvGb.subSequence(0,1) + fileName.substring(0,7); +//// // 파일명이 8자리 이상인 경우 파일명 8자리를 그대로 보내 준다. +//// // 향후 중복이 발생하게 되면 별도의 송신 스크립트를 만들어서 강제로 세팅하도록 한다. +//// // 2009.03.27 +//// ndmPname = fileName.substring(0,8); +//// }else if ( fileName.length() > 3 ){ +//// ndmPname = sendRecvGb.subSequence(0, 8 - fileName.length()) + fileName; +//// }else { +//// ndmPname = sendRecvGb + fileName + "0000"; +//// ndmPname = ndmPname.substring(0,8); +//// } +//// logInfo.setNdmPname(ndmPname); +// } +// +// boolean isTreatDummyFile = false; //더미파일 생성여부 (Event 또는 UI_탐색화면으로 부터 기동한 경우 더미파일 생성) +// String eaiDelimiter = ""; +// String remoteDelimiter = ""; +// String dirTree = ""; +// String eaiDummyPath = ""; +// String remoteDummyPath = ""; +// String[] batchCode = null; +// +// try { +// +// //--------------------------------------------------------------------- +// //2. Event 또는 UI_탐색화면으로 부터 기동한 경우 상대 경로 설정 +// if (sendRecvType.equals(DIRECTION_SEND) && (remoteDir.equals("") || remoteFile.equals(""))) { +// //EAI경로로 부터 리모트경로 설정 +// isTreatDummyFile = true; +// eaiDelimiter = StringUtil.getDirDelimiter(eaiDir); +// remoteDelimiter = StringUtil.getDirDelimiter(remoteServerVO.getRemoteRootDir()); +// dirTree = eaiDir.substring(BatchDirUtil.getResponseArchDir().length()); //예) /퇴직연금_WSR00/교보생명_IL05/계약및가입자_0100 +//// 2008.1.16 by kscheon - start +//// remoteDir = remoteServerVO.getRemoteRootDir() + remoteDelimiter + "수신_Real"+ dirTree.replaceAll(eaiDelimiter, remoteDelimiter); +// remoteDir = remoteServerVO.getRemoteRootDir() + remoteDelimiter + StringUtil.replaceStr("수신_Real"+ dirTree, eaiDelimiter, remoteDelimiter); +//// 2008.1.16 by kscheon - end +// remoteFile = eaiFile; //EAI 파일명 그대로 +// remoteDummyPath = remoteDir.replaceFirst("Real", "Root"); +// batchCode = dirTree.substring(1).split(eaiDelimiter.replaceAll("\\\\", "\\\\\\\\")); +//// String instCode = batchCode.length<2? "" : batchCode[1].substring( batchCode[1].indexOf("_") + 1); +//// String fileName = checkFileName(remoteServerVO, instCode, eaiFile); +//// if ( !StringUtil.nvlTrim(fileName).equals("")) { +//// remoteFile = fileName; +//// isTreatDummyFile = false; +//// } +// +// } else if (sendRecvType.equals(DIRECTION_RECEIVE) && (eaiDir.equals("") || eaiFile.equals(""))) { +// //리모트경로로 부터 EAI경로 설정 +// +// // 해당기능 없음 2012.11.28 +//// isTreatDummyFile = true; +//// eaiDelimiter = StringUtil.getDirDelimiter(BatchDirUtil.getRequestRealDir()); +//// remoteDelimiter = StringUtil.getDirDelimiter(remoteDir); +//// String dirSuffix = remoteDir.substring(remoteServerVO.getRemoteRootDir().length()); //예) /송신_Real/퇴직연금_WSR00/교보생명_IL05/계약및가입자_0100 +//// dirTree = dirSuffix.substring(dirSuffix.indexOf(remoteDelimiter, 1)); //예) /퇴직연금_WSR00/교보생명_IL05/계약및가입자_0100 +//// eaiDir = BatchDirUtil.getRequestRealDir() + dirTree; +//// eaiFile = remoteFile; //리모트 파일명 그대로 +//// eaiDummyPath = BatchDirUtil.getRequestRootDir() + dirTree; +//// batchCode = dirTree.substring(1).split(remoteDelimiter.replaceAll("\\\\", "\\\\\\\\")); +// +// } else if (startingType.equals(STARTING_TYPE_UI_MANUAL)) { +// eaiDelimiter = StringUtil.getDirDelimiter(eaiDir); +// remoteDelimiter = StringUtil.getDirDelimiter(remoteDir); +// //수동 입력된 EAI 디렉토리가 EAI 배치 구조에 맞는지 체크 (송수신 Real/Root/Arch 디렉토리 길이가 모두 같음을 전제함) +// if (eaiDir.length() > BatchDirUtil.getResponseArchDir().length()) { // +// dirTree = eaiDir.substring(BatchDirUtil.getResponseArchDir().length()); //예) /퇴직연금_WSR00/교보생명_IL05/계약및가입자_0100 +// batchCode = dirTree.substring(1).split(eaiDelimiter.replaceAll("\\\\", "\\\\\\\\")); +// } +// } +// +// //파일전송 로그정보 설정 (업무구분/대외기관/거래구분그룹) +// if (batchCode != null) { +// logInfo.setProcessCode (batchCode.length<1? "" : batchCode[0].substring( batchCode[0].indexOf("_") + 1)); +// logInfo.setProcessName (batchCode.length<1? "" : batchCode[0].substring(0, batchCode[0].indexOf("_"))); +// logInfo.setOrganCode (batchCode.length<2? "" : batchCode[1].substring( batchCode[1].indexOf("_") + 1)); +// logInfo.setOrganName (batchCode.length<2? "" : batchCode[1].substring(0, batchCode[1].indexOf("_"))); +// logInfo.setBizGroupCode (batchCode.length<3? "" : batchCode[2].substring( batchCode[2].indexOf("_") + 1)); +// logInfo.setBizGroupName (batchCode.length<3? "" : batchCode[2].substring(0, batchCode[2].indexOf("_"))); +// +// } +// +// if (sendRecvType.equals(DIRECTION_SEND)) { +// logger.info("[리모트송수신] ☞ FROM : EAI Dir [ "+ eaiDir + eaiDelimiter + eaiFile +" ]"); +// logger.info("[리모트송수신] ☞ TO : Remote Dir [ "+ remoteDir + remoteDelimiter + remoteFile +" ]"); +// } else { +// logger.info("[리모트송수신] ☞ FROM : Remote Dir [ "+ remoteDir + remoteDelimiter + remoteFile +" ]"); +// logger.info("[리모트송수신] ☞ TO : EAI Dir [ "+ eaiDir + eaiDelimiter + eaiFile +" ]"); +// } +// } catch (Exception ex) { +// logger.error("★★★★★ 전송경로 설정 시 오류 발생 !! ★★★★★", ex); +// //에러 메시지 설정 +// logInfo.setResultCode (RESULT_CODE_UNEXPECTED_ERROR); +// logInfo.setResultMsg ("리모트파일 전송 경로 설정시 오류가 발생하였습니다.\n> caused by..."+ ex.toString()); +// try { +// logger.info("[리모트송수신] ▶ 리모트파일 전송 결과로그 DB Update..."); +// logInfo.setFransferEndTime(CalendarUtil.getCurrentTimeNoDash()); +// RemoteTransferLogManager.getInstance().insertRemoteTransferLog(logInfo); +// } catch (Exception e) { +// logger.error("전송경로 설정 오류 시 전송결과로그 Update 시 오류 발생!", e); +// } +// throw ex; +// } +// +// try { +// //리모트파일 전송 시작로그 DB Insert +// logger.info("[리모트송수신] ▶ 리모트파일 전송 시작로그 DB Insert..."); +// RemoteTransferLogManager.getInstance().insertRemoteTransferLog(logInfo); +// +// } catch (Exception ex) { +// logInfo.setResultCode (RESULT_CODE_UNEXPECTED_ERROR); +// logInfo.setResultMsg (ex.toString()); +// throw new Exception("리모트파일 전송 전 전송시작로그 Insert 시 오류 발생!\n caused by..."+ ex.toString()); +// } +// +// //--------------------------------------------------------------------- +// //3. 리모트파일 송수신 수행 +// try { +// //================================================================= +// // 3-1. 송신 (EAI -> Remote) +// //================================================================= +// if (sendRecvType.equals(DIRECTION_SEND)) { +// //리모트서버로 실제파일 송신. +// logger.info("[리모트송수신] ▶ 리모트 서버에 실제파일 송신..."); +// try { +// sendFile(remoteServerVO, eaiDir, eaiFile, remoteDir, remoteFile); +// } catch (Exception ex) { +// throw new Exception("Real 파일 송신 실패!\n> caused by..."+ ex.toString()); +// } +// +// if (isTreatDummyFile) { +// //리모트서버로 더미파일 송신. +// logger.info("[리모트송수신] ▶ 리모트 서버에 더미파일 송신..."); +// try { +// this.isLogging = false; //더미파일 송신은 로그정보 설정 안함 +// sendFile(remoteServerVO, getPropEaiDummyPath(), eaiFile, remoteDummyPath, remoteFile); +// this.isLogging = true; +// +// } catch (Exception ex) { +// throw new Exception("Dummy 파일 송신 실패!\n> caused by..."+ ex.toString()); +// } +// } +// +// //================================================================= +// // 3-2. 수신 (Remote -> EAI) +// //================================================================= +// } else if (sendRecvType.equals(DIRECTION_RECEIVE)) { +// //리모트서버로 부터 실제파일 수신. +// logger.info("[리모트송수신] ▶ 리모트 서버로부터 실제파일 수신..."); +// try { +// /*20081106 by kscheon +// * 로컬이여도 파일 copy가 아닌 ftp script 실행 +// if (remoteIsLocal == true) { +// FileUtil.copyTransferFile(new File(remoteDir+remoteDelimiter+remoteFile), new File(eaiDir+eaiDelimiter+eaiFile)); +// } else { +// */ +// receiveFile(remoteServerVO, remoteDir, remoteFile, eaiDir, eaiFile); +// //} +// } catch (Exception ex) { +// throw new Exception("Real 파일 수신 실패!\n> caused by..."+ ex.toString()); +// } +// +// if (isTreatDummyFile) { +// //더미파일 생성 +// logger.info("[리모트송수신] ▶ EAI 서버에 더미파일 생성..."); +// File dummyFile = new File(eaiDummyPath, eaiFile); +// boolean dummyResult = dummyFile.createNewFile(); +// if (dummyResult==false) throw new Exception("Dummy 파일 생성 실패"); +// } +// } +// +// +// } catch (Exception ex) { +// logger.error("★★★★★ 리모트파일 전송 시 오류 발생 !! ★★★★★", ex); +// //에러 메시지 설정 +// if (logInfo.getResultCode().equals("") || +// logInfo.getResultCode().equals(RESULT_CODE_PROCESSING)) logInfo.setResultCode(RESULT_CODE_UNEXPECTED_ERROR); +// logInfo.setResultMsg (ex.getMessage()); +// throw ex; +// +// //--------------------------------------------------------------------- +// //4. 리모트파일 전송 결과로그 DB Update +// } finally { +// try { +// logger.info("[리모트송수신] ▶ 리모트파일 전송 결과로그 DB Update..."); +// RemoteTransferLogManager.getInstance().updateRemoteTransferLog(logInfo); +// // 송신인 경우 SMS발송한다. +// if ( sendRecvType.equals(DIRECTION_SEND) && !logInfo.getResultCode().endsWith(RESULT_CODE_SUCCESS) ){ +// sendITSMSms(); +// } +// +// } catch (Exception ex) { +// logger.error("리모트파일 전송 후 전송결과로그 Update 시 오류 발생!", ex); +// } +// } +// +// logger.info("[리모트송수신] ■ 리모트 송수신 수행 완료."); +// return logInfo; +// } +// +// +// +// protected void runSystemScript(String[] command) throws Exception { +// +// String cmdLine = command[0]; +// for ( int inx=1; inx < command.length; inx++) +// cmdLine += " " + command[inx]; +// +// logger.info("[리모트송수신] [Runtime.Exec] ▶ System Command Runtime 수행 시작..."); +// logger.info("[리모트송수신] [Runtime.Exec] ⓟ Command : ["+ cmdLine +"]"); +// +// //1. System FTP Shell 명령어를 Runtime 으로 실행 +// Process process = Runtime.getRuntime().exec(command); +// +// //2. Runtime 실행 결과 저장 +// BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); +// String errorLine = null; +// StringBuffer errorBuffer = new StringBuffer(); +// while ((errorLine = errorReader.readLine()) != null) { +// if (errorBuffer.length() > 0) errorBuffer.append("\n"); +// errorBuffer.append(errorLine); +// logger.debug("[리모트송수신] [Runtime.Exec] stderr> "+ errorLine); +// } +// +// BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); +// String outputLine = null; +// StringBuffer outputBuffer = new StringBuffer(); +// while ((outputLine = outputReader.readLine()) != null) { +// if (outputBuffer.length() > 0) outputBuffer.append("\n"); +// outputBuffer.append(outputLine); +// logger.debug("[리모트송수신] [Runtime.Exec] stdout> "+ outputLine); +// } +// +// int exitVal = process.waitFor(); +// +// scriptErrorMsg = errorBuffer.toString(); +// scriptOutputMsg = outputBuffer.toString(); +// +// logger.info("[리모트송수신] [Runtime.Exec] ☞ Exit Value : "+ exitVal); +// logger.info("[리모트송수신] [Runtime.Exec] ▶ System Command Runtime 수행 완료."); +// +// if (isLogging) logInfo.setResultCode(exitVal+""); +// +// if (exitVal != 0) throw new Exception("Runtime.Exec 으로 실행한 Command exit value (="+ exitVal +") 가 정상이 아닙니다. (Command : "+ cmdLine +")\n> caused by..."+ scriptErrorMsg); +// } +// +// public abstract void sendFile ( RemoteServerVO remoteServerVO, +// String eaiDir, +// String eaiFile, +// String remoteDir, +// String remoteFile ) throws Exception; +// +// public abstract void receiveFile( RemoteServerVO remoteServerVO, +// String remoteDir, +// String remoteFile, +// String eaiDir, +// String eaiFile ) throws Exception; +// +//// private String checkFileName (RemoteServerVO remoteServerVO, +//// String institutionCode, +//// String eaiFile) throws Exception { +//// String processCode = remoteServerVO.getProcessCode(); +//// String bizCode = getBizcode( processCode, institutionCode, eaiFile); +//// logInfo.setBizCode( bizCode ); +//// BatchJobInfoVO info = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode); +//// if ( info == null ) return null; +//// logInfo.setJobCode(info.getMsgDstCode()); +//// applCd = info.getUapplCd(); +//// if ( info.getRemoteNodeName() != null && !info.getRemoteNodeName().trim().equals( "")){ +//// remoteServerVO.setRemoteNodeName(info.getRemoteNodeName()); +//// } +//// return info.getFilename(); +//// } +// +//// private String getBizcode(String processCode, +//// String institutionCode, +//// String fileName) throws Exception { +//// +//// +//// //거래구분 코드 설정 +//// int bizCodeStartIndex = 0; +//// int bizCodeEndIndex = 0; +//// int orgIndex = 0; +//// ArrayList organList = OutsideManager.getInstance().getOutsideInfo(processCode); +//// for (int i=0; organList!=null && i= fileName.length()) bizCodeStartIndex = 0; +//// if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); +//// +//// String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); +//// // 거래 구분 코드 길이가 가변인 경우( END INDEX가 0인 경우) +//// if ( orgIndex == 0 ){ +//// String delStr = null; +//// try { +//// Properties orgInfo = PropManager.getInstance().getProperties( +//// "TelegramInfo{" + processCode + "_" + institutionCode + "}"); +//// delStr = orgInfo.getProperty( "del.string" ); +//// +//// } catch (Exception e) {} +//// +//// if ( delStr != null && !delStr.trim().equals("")){ +//// +//// int delIndex = bizCode.indexOf(delStr); +//// +//// if ( delIndex > -1 ) { +//// bizCode = bizCode.substring(0, delIndex ); +//// } +//// } +//// } +//// return bizCode; +//// } +// +// private void sendITSMSms(){ +// +// try { +// +// String message = "[수신 실패]" + "업무명:" + logInfo.getProcessName() +// + " 기관명:" + logInfo.getOrganName() +// + " 파일명:" + logInfo.getEaiFileName(); +// ItmsSmsUtil.sendSMS( PropManager.getInstance().getProperty(ItmsSmsUtil.SMSINFO, ItmsSmsUtil.REQ_BY_GROUP), applCd, message ); +// if ( applCd != null && !applCd.trim().equals("")){ +// if (!PropManager.getInstance().getProperty(ItmsSmsUtil.SMSINFO, ItmsSmsUtil.EAI_SEND_YN).trim().equals("")){ +// ItmsSmsUtil.sendSMS( PropManager.getInstance().getProperty(ItmsSmsUtil.SMSINFO, ItmsSmsUtil.REQ_BY_GROUP), "", message); +// } +// } +// +// } catch (Exception e) {} +// } +// +//} diff --git a/src/com/eactive/eai/inbound/remote/FTPTransferByApi.java b/src/com/eactive/eai/inbound/remote/FTPTransferByApi.java new file mode 100644 index 0000000..716a07c --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/FTPTransferByApi.java @@ -0,0 +1,131 @@ +//package com.eactive.eai.inbound.remote; +// +//import java.util.ArrayList; +//import org.apache.commons.net.ftp.FTPClient; +//import org.apache.commons.net.ftp.FTPFile; +//import org.apache.commons.net.ftp.FTPReply; +// +//public class FTPTransferByApi extends CommonTransfer +//{ +// +// private FTPClient ftpClient = null; +// +// +// //------------------------------------------------------------------------------------------- +// // +// //------------------------------------------------------------------------------------------- +// private void connect(RemoteServerVO remoteServerVO) throws Exception { +// +// try { +// String remoteServerIP = remoteServerVO.getRemoteServerIP(); +// String remoteFtpPort = remoteServerVO.getRemoteFtpPort(); +// +// if (remoteFtpPort.equals("")) { +// logger.warn("[리모트송수신] [FTP_Api] 해당 서버["+ remoteServerIP +"] 에 연결할 FTP 포트번호가 주어지지 않았습니다. 디폴트 포트번호 '21' 을 설정합니다."); +// remoteFtpPort = "21"; +// } +// logger.info("[리모트송수신] [FTP_Api] ▶ FTP 서버 연결 시도... " + remoteServerIP + ":" + remoteFtpPort); +// +// +// if (ftpClient!=null && ftpClient.isConnected()) { +// logger.info("[리모트송수신] [FTP_Api] ▶ 해당 FTP 서버에 이미 연결되어 있습니다."); +// return; +// } +// +// ftpClient = new FTPClient(); +// ftpClient.setControlEncoding("EUC-KR"); +// ftpClient.connect(remoteServerIP, Integer.parseInt(remoteFtpPort)); +// +// int reply = ftpClient.getReplyCode(); +// logger.info("[리모트송수신] [FTP_Api] ☞ 응답코드 : "+ reply); +// +// if (!FTPReply.isPositiveCompletion(reply)) { +// try { +// logger.error("[리모트송수신] [FTP_Api] FTP 서버 연결에 실패하였습니다."); +// ftpClient.disconnect(); +// +// } catch (Exception ex) { +// logger.error( ex.getMessage(), ex); +// } +// throw new Exception("FTP 연결 응답코드("+ reply +") 가 비정상입니다."); +// } +// logger.info("[리모트송수신] [FTP_Api] ▶ FTP 서버에 연결되었습니다."); +// +// } catch (Exception ex) { +// logger.error( ex.getMessage(), ex); +// throw new Exception("FTP 연결 오류!\n caused by..."+ ex.toString()); +// } +// } +// +// //------------------------------------------------------------------------------------------- +// // +// //------------------------------------------------------------------------------------------- +// private void disconnect() { +// logger.info("[리모트송수신] [FTP_Api] ▶ FTP 서버 연결 해제 시도..."); +// try { +// if (ftpClient!=null && ftpClient.isConnected()) ftpClient.disconnect(); +// logger.info("[리모트송수신] [FTP_Api] ▶ FTP 서버 연결이 해제 되었습니다."); +// } catch (Exception ex) { +// logger.error( ex.getMessage(), ex); +// } +// } +// +// //------------------------------------------------------------------------------------------- +// // +// //------------------------------------------------------------------------------------------- +// public ArrayList listFiles(RemoteServerVO remoteServerVO, String remoteDir) throws Exception { +// +// logger.info("[리모트송수신] [FTP_Api] ■ 리모트 파일 목록 조회 시작...... (Component 사용)"); +// logger.info("[리모트송수신] [FTP_Api] ⓟ 리모트 경로 : ["+ remoteDir +"]"); +// +// //파라미터 체크 +// if (remoteServerVO == null) throw new Exception("{리모트서버 VO} 파라미터 오류"); +// if (remoteDir.equals("")) throw new Exception("{리모트경로} 파라미터 오류"); +// +// ArrayList alist = new ArrayList(); +// +// try { +// if (ftpClient == null || !ftpClient.isConnected()) this.connect(remoteServerVO); +// +// ftpClient.login(remoteServerVO.getRemoteUserId(), remoteServerVO.getRemotePassword()); +// +// FTPFile[] files = ftpClient.listFiles(remoteDir); +// logger.info("[리모트송수신] [FTP_Api] ☞ 리모트 파일 건수 : ["+ files.length +"]"); +// +// for (int i=0; iRemote FTP 송신이 구현되지 않았습니다."); +// } +// +// //------------------------------------------------------------------------------------------- +// // +// //------------------------------------------------------------------------------------------- +// public void receiveFile(RemoteServerVO remoteServerVO, String remoteDir, String remoteFile, String eaiDir, String eaiFile) throws Exception { +// throw new Exception("Component 에 의한 Remote->EAI FTP 수신이 구현되지 않았습니다."); +// } +// +//} diff --git a/src/com/eactive/eai/inbound/remote/FTPTransferByScript.java b/src/com/eactive/eai/inbound/remote/FTPTransferByScript.java new file mode 100644 index 0000000..533b725 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/FTPTransferByScript.java @@ -0,0 +1,249 @@ +//package com.eactive.eai.inbound.remote; +// +//import com.eactive.eai.batch.common.CalendarUtil; +//import com.eactive.eai.common.property.PropManager; +//import com.eactive.eai.common.util.DatetimeUtil; +// +//import java.io.File; +//import java.util.Date; +// +//public class FTPTransferByScript extends CommonTransfer +//{ +// +// //리모트 FTP 전송 프라퍼티 정보 +// public static final String PROP_GROUP_REMOTE_TRANSFER_FTP = "RemoteTransferFtpInfo"; +// public static final String PROP_FTP_SEND_SCRIPT_PATH = "FTP_SEND_SCRIPT_PATH"; //FTP 송신 쉘스크립트 경로 (전체 경로) +// public static final String PROP_FTP_RECV_SCRIPT_PATH = "FTP_RECV_SCRIPT_PATH"; //FTP 수신 쉘스크립트 경로 (전체 경로) +// +// private static String getPropFtpSendScriptPath() throws Exception { +// String propValue = PropManager.getInstance().getProperty(PROP_GROUP_REMOTE_TRANSFER_FTP, PROP_FTP_SEND_SCRIPT_PATH); +// if (propValue == null) throw new Exception("'FTP 송신 쉘스크립트 파일' 프라퍼티 정보가 없습니다. (PropGroupName:"+ PROP_GROUP_REMOTE_TRANSFER_FTP +", PropName:"+ PROP_FTP_SEND_SCRIPT_PATH +")"); +// return propValue; +// } +// +// private static String getPropFtpRecvScriptPath() throws Exception { +// String propValue = PropManager.getInstance().getProperty(PROP_GROUP_REMOTE_TRANSFER_FTP, PROP_FTP_RECV_SCRIPT_PATH); +// if (propValue == null) throw new Exception("'FTP 수신 쉘스크립트 파일' 프라퍼티 정보가 없습니다. (PropGroupName:"+ PROP_GROUP_REMOTE_TRANSFER_FTP +", PropName:"+ PROP_FTP_RECV_SCRIPT_PATH +")"); +// return propValue; +// } +// +// +// +// //------------------------------------------------------------------------------------------- +// // 리모트서버로 실제파일 송신, 송신여부 리턴. (System FTP Shell Command 수행) +// //------------------------------------------------------------------------------------------- +// public void sendFile(RemoteServerVO remoteServerVO, String eaiDir, String eaiFile, String remoteDir, String remoteFile) throws Exception { +// +// +// logger.info("[리모트송수신] [FTP_Script] ■ EAI→Remote 파일 FTP 송신 시작...... (Runtime Script 사용)"); +// logger.info("[리모트송수신] [FTP_Script] ⓟ 리모트 서버 VO : ["+ remoteServerVO +"]"); +// logger.info("[리모트송수신] [FTP_Script] ⓟ EAI 경로 : ["+ eaiDir +"]"); +// logger.info("[리모트송수신] [FTP_Script] ⓟ EAI 파일 : ["+ eaiFile +"]"); +// logger.info("[리모트송수신] [FTP_Script] ⓟ 리모트 경로 : ["+ remoteDir +"]"); +// logger.info("[리모트송수신] [FTP_Script] ⓟ 리모트 파일 : ["+ remoteFile +"]"); +// +// //파라미터 체크 +// if (remoteServerVO == null) throw new Exception("{리모트서버 VO} 파라미터 오류"); +// if (eaiDir.equals("")) throw new Exception("{EAI경로} 파라미터 오류"); +// if (eaiFile.equals("")) throw new Exception("{EAI파일} 파라미터 오류"); +// if (remoteDir.equals("")) throw new Exception("{리모트경로} 파라미터 오류"); +// if (remoteFile.equals("")) throw new Exception("{리모트파일} 파라미터 오류"); +// +// //파일전송 로그정보 설정 +// if (isLogging) { +// if (logInfo==null) logInfo = new RemoteTransferLogVO(); +// logInfo.setRemoteServerVO (remoteServerVO); +// logInfo.setRemoteServerId (remoteServerVO.getRemoteServerId()); +// logInfo.setSendRecvType (DIRECTION_SEND); +// logInfo.setTransferType (TRANSFER_TYPE_FTP); +// logInfo.setEaiFilePath (eaiDir); +// logInfo.setEaiFileName (eaiFile); +// logInfo.setRemoteFilePath (remoteDir); +// logInfo.setRemoteFileName (remoteFile); +// logInfo.setFransferStartTime(CalendarUtil.getCurrentTimeNoDash()); +// File f = new File(eaiDir, eaiFile); +// logInfo.setFileSize (f.length()+""); +// logInfo.setFileLastModified (DatetimeUtil.getFormattedDate("yyyyMMddHHmmssSSS", new Date(f.lastModified()))); +// } +// +///* +//#!/bin/sh +// +//REMOTE_IP=$1 +//REMOTE_PORT=$2 +//USER_ID=$3 +//PASSWORD=$4 +//EAI_DIR=$5 +//EAI_FILE=$6 +//REMOTE_DIR=$7 +//REMOTE_FILE=$8 +// +//cd ${EAI_DIR} +// +//ftp -n ${REMOTE_IP} ${REMOTE_PORT} < 오류로 간주 안함 +// if (!super.scriptErrorMsg.equals("") && super.scriptErrorMsg.indexOf("리턴된 0 인쇄 여부") < 0) { +// logInfo.setResultCode(RESULT_CODE_UNEXPECTED_ERROR); +// throw new Exception("Runtime.Exec 으로 실행한 FTP Command 결과가 정상이 아닙니다.\n caused by..."+ super.scriptErrorMsg); +// } +// +// //exit value가 0(정상) 인 경우에도 output메시지를 체크하여 오류 체크 +// //ftp 리턴코드 값이 500 번대로 시작하면 오류임 (5.547e-320초 동안... .일케 시작하는 문장도 있음->제외) +// String[] outputMsgLines = super.scriptOutputMsg.split("\n"); +// for (int i=0; i selectCommand(String selectCommand) throws Exception { +// logger.info("[리모트송수신] [NDM_Api] ■ NDM Select Command 시작......"); +// logger.info("[리모트송수신] [NDM_Api] ⓟ Select Command : ["+ selectCommand +"]"); +// +// ArrayList alist = executeNdmCommand(COMMAND_TYPE_SELECT, selectCommand); +// +// logger.info("[리모트송수신] [NDM_Api] ■ NDM Select Command 완료."); +// return alist; +// } +// +// +// +// +// +// +// +// @SuppressWarnings("rawtypes") +// private ArrayList executeNdmCommand(String commandType, String command) throws Exception { +// +// logger.info("[리모트송수신] [NDM_Api] ▶ NDM Command 수행 시작... (Send Command to NDM 서버["+ this.ndmNodeName +"])"); +// logger.info("[리모트송수신] [NDM_Api] ⓟ commandType : ["+ commandType +"]"); +// +// ArrayList alist = null; +// try { +// this.connect(); +// +// if (commandType.equalsIgnoreCase(COMMAND_TYPE_SUBMIT)) { +// alist = this.executeSubmitCommand(command); //throw Exception +// +// } else if (commandType.equalsIgnoreCase(COMMAND_TYPE_SELECT)) { +// alist = this.executeSelectCommand(command); //throw Exception +// } +// +// } catch (MsgException ex) { +// logger.error( ex.getMessage(), ex); +// +// String errMsg = ex.toString(); +// Enumeration errorEnum = ex.elements(); +// while (errorEnum.hasMoreElements()) { +// Object obj = errorEnum.nextElement(); +// logger.error("[리모트송수신] [NDM_Api] - " + obj); +// errMsg += "\n - "+ obj; +// } +// throw new Exception("NDM Command 수행 실패!\n caused by..."+ errMsg); +// +// } catch (Exception ex) { +// logger.error( ex.getMessage(), ex); +// throw new Exception("NDM Command 수행 실패!\n caused by..."+ ex.toString()); +// +// } finally { +// this.disconnect(); +// } +// logger.info("[리모트송수신] [NDM_Api] ▶ NDM Command 수행 완료."); +// return alist; +// } +// +// private ArrayList executeSubmitCommand(String command) throws Exception { +// +// logger.info("[리모트송수신] [NDM_Api] ▶ NDM Submit Command 수행 시작..."); +// logger.info("[리모트송수신] [NDM_Api] ⓟ Command : submit maxdelay=unlimited \n"+ command); +// MediatorEnum submitResults = cdNode.execute("submit maxdelay=unlimited", command); +// +// ArrayList alist = new ArrayList(); +// while (submitResults.hasMoreElements()) { +// CDProcess processData = (CDProcess)submitResults.getNextElement(); +// alist.add(processData); +// String processNumber = processData.getProcessNumber() +""; +// String resultCode = processData.getConditionCode() +""; +// String messageId = processData.getMsgId(); +// String messageText = processData.getMsgText(); +// logger.info("[리모트송수신] [NDM_Api] ☞ Process Number : "+ processNumber); +// logger.info("[리모트송수신] [NDM_Api] ☞ Return code : "+ resultCode); +// logger.info("[리모트송수신] [NDM_Api] ☞ Message id : "+ messageId +" ["+ messageText +"]"); +// +// //파일전송 로그정보 설정 +// if (isLogging) logInfo.setNdmPnumber (processNumber); +// if (isLogging) logInfo.setResultCode (resultCode); +// +// if (!resultCode.equals(RESULT_CODE_SUCCESS)) { +// throw new Exception("NDM Submit 명령어 실행 결과 값이 정상이 아닙니다. (ResultCode:"+ resultCode +", MessageId:"+ messageId +")"); +// } +// } +// logger.info("[리모트송수신] [NDM_Api] ▶ NDM Submit Command 수행 완료."); +// return alist; +// } +// +// private ArrayList executeSelectCommand(String command) throws Exception { +// +// logger.info("[리모트송수신] [NDM_Api] ▶ NDM Select Command 수행 시작..."); +// logger.info("[리모트송수신] [NDM_Api] ⓟ Command : "+ command); +// MediatorEnum seleteResults = cdNode.execute(command); +// +// ArrayList alist = new ArrayList(); +// while (seleteResults.hasMoreElements()) { +// Object obj = seleteResults.getNextElement(); +// alist.add(obj); +// logger.debug("[리모트송수신] [NDM_Api] ☞ Process Data : "+ obj); +// //CDProcess processData = (CDProcess)submitResults.getNextElement(); +// //logger.info("[리모트송수신] [NDM_Api] [NDM Command] ☞ Process Data : "+ processData); +// } +// logger.info("[리모트송수신] [NDM_Api] ▶ NDM Select Command 수행 완료."); +// return alist; +// } +// +// +//} diff --git a/src/com/eactive/eai/inbound/remote/NDMTransferByScript.java b/src/com/eactive/eai/inbound/remote/NDMTransferByScript.java new file mode 100644 index 0000000..66852fe --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/NDMTransferByScript.java @@ -0,0 +1,235 @@ +//package com.eactive.eai.inbound.remote; +// +//import com.eactive.eai.batch.common.CalendarUtil; +//import com.eactive.eai.batch.common.StringUtil; +//import com.eactive.eai.common.property.PropManager; +//import com.eactive.eai.common.util.DatetimeUtil; +// +//import java.io.File; +//import java.util.Date; +// +//public class NDMTransferByScript extends CommonTransfer +//{ +// +// //리모트 NDM 전송 프라퍼티 정보 +// public static final String PROP_GROUP_REMOTE_TRANSFER_NDM = "RemoteTransferNdmInfo"; +// public static final String PROP_NDM_SEND_SCRIPT_PATH = "NDM_SEND_SCRIPT_PATH"; //NDM 송신 쉘스크립트 경로 (전체 경로) +// public static final String PROP_NDM_RECV_SCRIPT_PATH = "NDM_RECV_SCRIPT_PATH"; //NDM 수신 쉘스크립트 경로 (전체 경로) +// +// private static String getPropNdmSendScriptPath() throws Exception { +// String propValue = PropManager.getInstance().getProperty(PROP_GROUP_REMOTE_TRANSFER_NDM, PROP_NDM_SEND_SCRIPT_PATH); +// if (propValue == null) throw new Exception("'NDM 송신 쉘스크립트 파일' 프라퍼티 정보가 없습니다. (PropGroupName:"+ PROP_GROUP_REMOTE_TRANSFER_NDM +", PropName:"+ PROP_NDM_SEND_SCRIPT_PATH +")"); +// return propValue; +// } +// +// private static String getPropNdmRecvScriptPath() throws Exception { +// String propValue = PropManager.getInstance().getProperty(PROP_GROUP_REMOTE_TRANSFER_NDM, PROP_NDM_RECV_SCRIPT_PATH); +// if (propValue == null) throw new Exception("'NDM 수신 쉘스크립트 파일' 프라퍼티 정보가 없습니다. (PropGroupName:"+ PROP_GROUP_REMOTE_TRANSFER_NDM +", PropName:"+ PROP_NDM_RECV_SCRIPT_PATH +")"); +// return propValue; +// } +// +// +// //------------------------------------------------------------------------------------------- +// // 리모트서버로 실제파일 송신, 송신여부 리턴. (System NDM Shell Command 수행) +// //------------------------------------------------------------------------------------------- +// public void sendFile(RemoteServerVO remoteServerVO, String eaiDir, String eaiFile, String remoteDir, String remoteFile) throws Exception { +// +// +// logger.info("[리모트송수신] [NDM_Script] ■ EAI→Remote 파일 NDM 송신 시작...... (Runtime Script 사용)"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ 리모트 서버 VO : ["+ remoteServerVO +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ EAI 경로 : ["+ eaiDir +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ EAI 파일 : ["+ eaiFile +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ 리모트 경로 : ["+ remoteDir +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ 리모트 파일 : ["+ remoteFile +"]"); +// +// //파라미터 체크 +// if (remoteServerVO == null) throw new Exception("{리모트서버 VO} 파라미터 오류"); +// if (eaiDir.equals("")) throw new Exception("{EAI경로} 파라미터 오류"); +// if (eaiFile.equals("")) throw new Exception("{EAI파일} 파라미터 오류"); +// if (remoteDir.equals("")) throw new Exception("{리모트경로} 파라미터 오류"); +// if (remoteFile.equals("")) throw new Exception("{리모트파일} 파라미터 오류"); +// +// //파일전송 로그정보 설정 +// if (isLogging) { +// if (logInfo==null) logInfo = new RemoteTransferLogVO(); +// logInfo.setRemoteServerVO (remoteServerVO); +// logInfo.setRemoteServerId (remoteServerVO.getRemoteServerId()); +// logInfo.setSendRecvType (DIRECTION_SEND); +// logInfo.setTransferType (TRANSFER_TYPE_NDM); +// logInfo.setEaiFilePath (eaiDir); +// logInfo.setEaiFileName (eaiFile); +// logInfo.setRemoteFilePath (remoteDir); +// logInfo.setRemoteFileName (remoteFile); +// logInfo.setFransferStartTime(CalendarUtil.getCurrentTimeNoDash()); +// File f = new File(eaiDir, eaiFile); +// logInfo.setFileSize (f.length()+""); +// logInfo.setFileLastModified (DatetimeUtil.getFormattedDate("yyyyMMddHHmmssSSS", new Date(f.lastModified()))); +// } +// +///* +//#!/bin/sh +// +//ndmcli -x << EOJ +//submit maxdelay=unlimited +//SENDFILE process snode=$1 +//step1 copy from (file="$3" pnode) +// to (file="$4" disp=(rpl) snode) +//pend; +//EOJ +//*/ +// +// String remoteDelimiter = StringUtil.getDirDelimiter(remoteDir); +// String eaiDelimiter = StringUtil.getDirDelimiter(eaiDir); +// if (remoteDir.endsWith(remoteDelimiter)) remoteDir = remoteDir.substring(0, remoteDir.length()-1); +// if (eaiDir .endsWith(eaiDelimiter )) eaiDir = eaiDir .substring(0, eaiDir .length()-1); +// if (remoteFile==null || remoteFile.equals("")) remoteFile = eaiFile; +// +// //1. System NDM Shell 명령어 생성 +///* +// String command = getPropNdmSendScriptPath() +" "+ logInfo.getNdmPname() +// +" "+ remoteServerVO.getRemoteServerIP() +";"+ remoteServerVO.getRemoteNdmPort() +// +" "+ eaiDir + eaiDelimiter + eaiFile +// +" "+ remoteDir + remoteDelimiter + remoteFile; +//*/ +// String[] command = new String[5]; +// command[0] = getPropNdmSendScriptPath(); +// command[1] = logInfo.getNdmPname(); +// +// if ( remoteServerVO.getRemoteNodeName().trim().equals("")){ +// command[2] = remoteServerVO.getRemoteServerIP() +";"+ remoteServerVO.getRemoteNdmPort(); +// }else{ +// command[2] = remoteServerVO.getRemoteNodeName().trim(); +// } +// command[3] = eaiDir + eaiDelimiter + eaiFile; +// command[4] = remoteDir + remoteDelimiter + remoteFile; +// +// int pos = remoteFile.indexOf('|'); +// if ( pos > -1 ){ +// command[0] = remoteFile.substring(0,pos); +// command[4] = remoteFile.substring( pos + 1, remoteFile.length()); +// +// } +// //2. System NDM Shell 명령어를 Runtime 으로 실행 +// this.runSystemScript(command); +// +// //파일전송 로그정보 설정 +// if (isLogging) logInfo.setFransferEndTime (CalendarUtil.getCurrentTimeNoDash()); +// +// logger.info("[리모트송수신] [NDM_Script] ■ EAI→Remote 파일 NDM 송신 완료."); +// } +// +// //------------------------------------------------------------------------------------------- +// // 리모트서버로 부터 실제파일 수신, 수신여부 리턴. (System NDM Shell Command 수행) +// //------------------------------------------------------------------------------------------- +// public void receiveFile(RemoteServerVO remoteServerVO, String remoteDir, String remoteFile, String eaiDir, String eaiFile) throws Exception { +// +// logger.info("[리모트송수신] [NDM_Script] ■ Remote→EAI 파일 NDM 수신 시작...... (Runtime Script 사용)"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ 리모트 서버 VO : ["+ remoteServerVO +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ 리모트 경로 : ["+ remoteDir +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ 리모트 파일 : ["+ remoteFile +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ EAI 경로 : ["+ eaiDir +"]"); +// logger.info("[리모트송수신] [NDM_Script] ⓟ EAI 파일 : ["+ eaiFile +"]"); +// +// //파라미터 체크 +// if (remoteServerVO == null) throw new Exception("{리모트서버 VO} 파라미터 오류"); +// if (remoteDir.equals("")) throw new Exception("{리모트경로} 파라미터 오류"); +// if (remoteFile.equals("")) throw new Exception("{리모트파일} 파라미터 오류"); +// if (eaiDir.equals("")) throw new Exception("{EAI경로} 파라미터 오류"); +// if (eaiFile.equals("")) throw new Exception("{EAI파일} 파라미터 오류"); +// +// +// //파일전송 로그정보 설정 +// if (isLogging) { +// if (logInfo==null) logInfo = new RemoteTransferLogVO(); +// logInfo.setRemoteServerVO (remoteServerVO); +// logInfo.setRemoteServerId (remoteServerVO.getRemoteServerId()); +// logInfo.setSendRecvType (DIRECTION_RECEIVE); +// logInfo.setTransferType (TRANSFER_TYPE_NDM); +// logInfo.setEaiFilePath (eaiDir); +// logInfo.setEaiFileName (eaiFile); +// logInfo.setRemoteFilePath (remoteDir); +// logInfo.setRemoteFileName (remoteFile); +// logInfo.setFransferStartTime(CalendarUtil.getCurrentTimeNoDash()); +// } +// +// +///* +//#!/bin/sh +// +//ndmcli -x << EOJ +//submit maxdelay=unlimited +//SENDFILE process snode=$1 +//step1 copy from (file="$3" snode) +// to (file="$4" disp=(rpl) pnode) +//pend; +//EOJ +//*/ +// +// String remoteDelimiter = StringUtil.getDirDelimiter(remoteDir); +// String eaiDelimiter = StringUtil.getDirDelimiter(eaiDir); +// if (remoteDir.endsWith(remoteDelimiter)) remoteDir = remoteDir.substring(0, remoteDir.length()-1); +// if (eaiDir .endsWith(eaiDelimiter )) eaiDir = eaiDir .substring(0, eaiDir .length()-1); +// if (eaiFile==null || eaiFile.equals("")) eaiFile = remoteFile; +// +// //1. System NDM Shell 명령어 생성 +// /* +// String command = getPropNdmRecvScriptPath() +" "+ logInfo.getNdmPname() +// +" "+ remoteServerVO.getRemoteServerIP() +";"+ remoteServerVO.getRemoteNdmPort() +// +" "+ remoteDir + remoteDelimiter + remoteFile +// +" "+ eaiDir + eaiDelimiter + eaiFile; +// */ +// +// String command[] = new String[5]; +// command[0] = getPropNdmRecvScriptPath(); +// command[1] = logInfo.getNdmPname(); +// command[2] = remoteServerVO.getRemoteServerIP() +";"+ remoteServerVO.getRemoteNdmPort(); +// command[3] = remoteDir + remoteDelimiter + remoteFile; +// command[4] = eaiDir + eaiDelimiter + eaiFile; +// +// //2. System NDM Shell 명령어를 Runtime 으로 실행 +// this.runSystemScript(command); +// +// //파일전송 로그정보 설정 +// if (isLogging) { +// File f = new File(eaiDir, eaiFile); +// logInfo.setFileSize (f.length()+""); +// logInfo.setFileLastModified (DatetimeUtil.getFormattedDate("yyyyMMddHHmmssSSS", new Date(f.lastModified()))); +// logInfo.setFransferEndTime (CalendarUtil.getCurrentTimeNoDash()); +// } +// +// logger.info("[리모트송수신] [NDM_Script] ■ Remote→EAI 파일 NDM 수신 완료."); +// } +// +// +// +// protected void runSystemScript(String[] command) throws Exception { +// +// super.runSystemScript(command); +// +// if (!super.scriptErrorMsg.equals("")) { +// logInfo.setResultCode(CommonTransfer.RESULT_CODE_UNEXPECTED_ERROR); +// throw new Exception("Runtime.Exec 으로 실행한 NDM Command 결과가 정상이 아닙니다.\n caused by..."+ super.scriptErrorMsg); +// } +// +// int index1, index2, index3; +// index1 = scriptOutputMsg.indexOf("Process Number = "); +// index2 = scriptOutputMsg.indexOf("Return code = "); +// index3 = scriptOutputMsg.indexOf("Message id = "); +// String processNumber = StringUtil.nvlTrim( scriptOutputMsg.substring(index1 + 17, scriptOutputMsg.indexOf("\n", index1)) ); +// String resultCode = StringUtil.nvlTrim( scriptOutputMsg.substring(index2 + 17, scriptOutputMsg.indexOf("\n", index2)) ); +// String messageId = StringUtil.nvlTrim( scriptOutputMsg.substring(index3 + 17, scriptOutputMsg.indexOf("\n", index3)) ); +// logger.info("[리모트송수신] [NDM_Script] ☞ Process Number : "+ processNumber); +// logger.info("[리모트송수신] [NDM_Script] ☞ Return code : "+ resultCode); +// logger.info("[리모트송수신] [NDM_Script] ☞ Message id : "+ messageId); +// +// //파일전송 로그정보 설정 +// if (isLogging) logInfo.setNdmPnumber (processNumber); +// if (isLogging) logInfo.setResultCode (resultCode); +// +// if (!resultCode.equals(RESULT_CODE_SUCCESS)) { +// logInfo.setResultCode(resultCode); +// throw new Exception("Runtime.Exec 으로 실행한 NDM Command 결과가 정상이 아닙니다. (NDM ResultCode:"+ resultCode +", NDM MessageId:"+ messageId +")"); +// } +// } +// +//} diff --git a/src/com/eactive/eai/inbound/remote/RemoteDirectoryDAO.java b/src/com/eactive/eai/inbound/remote/RemoteDirectoryDAO.java new file mode 100644 index 0000000..3f6d8d5 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteDirectoryDAO.java @@ -0,0 +1,226 @@ +package com.eactive.eai.inbound.remote; + +import java.sql.ResultSet; +//import java.sql.ResultSetMetaData; +import java.util.ArrayList; + +import org.slf4j.LoggerFactory; + +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class RemoteDirectoryDAO extends BaseDAO implements RemoteDirectoryQuery +{ + + public RemoteDirectoryDAO() { + super(); + super.logger = Logger.getLogger(Logger.LOGGER_FILEEVENT); + } + + + //------------------------------------------------------------------------------------------- + // REMOTE 서버정보 상세조회 + //------------------------------------------------------------------------------------------- + public ArrayList selectRemoteDirectory(String searchProcessCode, String searchType, String searchText) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + String query = SEARCH_REMOTE_DIRECTORY; + if("SERVER_NAME".equals(searchType)) { + query = query + " AND A.\"RmtSevrName\" LIKE '%" + searchText + "%'\n"; + } + else if("DIRECTORY_NAME".equals(searchType)) { + query = query + " AND B.\"RmtSevrJobDirName\" LIKE '%" + searchText + "%'\n"; + } + else if("DIRECTORY_ID".equals(searchType)) { + query = query + " AND B.\"RmtSevrJobDirID\" LIKE '" + searchText + "%'\n"; + } + query = query + " ORDER BY B.\"RmtSevrJobDirID\" "; + + + this.connect(query); + logger.debug(">>> 리모트 디렉토리 검색 SQL : \n"+ query); + + index = 1; + this.preparedStatement.setString(index++, searchProcessCode); logger.debug(">>> 바인드("+(index-1)+") : ["+ searchProcessCode +"]"); + rs = executeQuery(); + + ArrayList alist = new ArrayList(); + while (rs.next()) { + RemoteServerVO sinfo = new RemoteServerVO(); + sinfo.setRemoteServerId (StringUtil.nvlTrim(rs.getString(1 ))); // 리모트서버 ID (PK) + sinfo.setRemoteServerName(StringUtil.nvlTrim(rs.getString(2 ))); // 리모트서버 명 + sinfo.setProcessCode (StringUtil.nvlTrim(rs.getString(3 ))); // 업무구분코드 (FK) + sinfo.setRemoteServerIP (StringUtil.nvlTrim(rs.getString(4 ))); // 리모트서버 IP + sinfo.setRemoteNdmPort (StringUtil.nvlTrim(rs.getString(5 ))); // 리모트서버 NDM Port Number + sinfo.setRemoteFtpPort (StringUtil.nvlTrim(rs.getString(6 ))); // 리모트서버 FTP Port Number + sinfo.setRemoteUserId (StringUtil.nvlTrim(rs.getString(7 ))); // 리모트서버 FTP User ID + sinfo.setRemotePassword (StringUtil.nvl (rs.getString(8 ))); // 리모트서버 FTP User Password + sinfo.setRemoteRootDir (StringUtil.nvlTrim(rs.getString(9 ))); // 리모트서버 Root Directory + sinfo.setAutoTransferType(StringUtil.nvlTrim(rs.getString(10))); // 리포트 파일 이벤트시 파일 복사 방법 + sinfo.setUseYn (StringUtil.nvlTrim(rs.getString(11))); // 리모트서버 사용여부 + sinfo.setCreateId (StringUtil.nvlTrim(rs.getString(12))); // 리모트서버 등록자ID + sinfo.setCreateTime (StringUtil.nvlTrim(rs.getString(13))); // 리모트서버 등록시간 + sinfo.setUpdateId (StringUtil.nvlTrim(rs.getString(14))); // 리모트서버 수정자ID + sinfo.setUpdateTime (StringUtil.nvlTrim(rs.getString(15))); // 리모트서버 수정시간 + + //리모트 Root Directory 가 "/" 로 끝나면 "/" 제거 + if (sinfo.getRemoteRootDir().endsWith("/")) { + sinfo.setRemoteRootDir(sinfo.getRemoteRootDir().substring(0, sinfo.getRemoteRootDir().length()-1)); + } + + RemoteDirectoryVO info = new RemoteDirectoryVO(); + info.setRemoteDirId (StringUtil.nvlTrim(rs.getString(16))); + info.setRemoteDirName (StringUtil.nvlTrim(rs.getString(17))); + info.setRemoteServerId(StringUtil.nvlTrim(rs.getString(18))); + info.setProcessCode (StringUtil.nvlTrim(rs.getString(19))); + info.setProcessName (StringUtil.nvlTrim(rs.getString(20))); + info.setOrganCode (StringUtil.nvlTrim(rs.getString(21))); + info.setOrganName (StringUtil.nvlTrim(rs.getString(22))); + info.setBizGroupCode (StringUtil.nvlTrim(rs.getString(23))); + info.setBizGroupName (StringUtil.nvlTrim(rs.getString(24))); + info.setUseYn (StringUtil.nvlTrim(rs.getString(25))); + info.setCreateId (StringUtil.nvlTrim(rs.getString(26))); + info.setCreateTime (StringUtil.nvlTrim(rs.getString(27))); + info.setUpdateId (StringUtil.nvlTrim(rs.getString(28))); + info.setUpdateTime (StringUtil.nvlTrim(rs.getString(29))); + info.setRemoteServerVO (sinfo); + + alist.add(info); + } + logger.info(">>> 리모트 디렉토리 검색 건수 : "+ alist.size()); + return alist; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + + //------------------------------------------------------------------------------------------- + // REMOTE 서버정보 신규 + //------------------------------------------------------------------------------------------- +// public int insertRemoteDirectory(RemoteDirectoryVO remoteDirectoryVO) throws DAOException { +// +// int retValue = 0; +// int index = 0; +// +// try { +// +// String query = INSERT_REMOTE_DIRECTORY; +// this.connect(query); +// logger.debug(">>> 리모트 디렉토리 등록 SQL : \n"+ query); +// +// index = 1; +// this.preparedStatement.setString(index++, remoteDirectoryVO.getRemoteServerId()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getRemoteServerId() +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getRemoteDirName ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getRemoteDirName () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getRemoteServerId()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getRemoteServerId() +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getProcessCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getProcessCode () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getOrganCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getOrganCode () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getBizGroupCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getBizGroupCode () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getUseYn ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getUseYn () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getCreateId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getCreateId () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getCreateTime ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getCreateTime () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getUpdateId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getUpdateId () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getUpdateTime ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getUpdateTime () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getRemoteServerId()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getRemoteServerId() +"]"); +// +// retValue = this.executeUpdate(); +// logger.info(">>> 리모트 디렉토리 등록 건수 : "+ retValue); +// +// return retValue; +// +// } catch (DAOException ex) { +// throw ex; +// } catch (Exception e) { +// String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); +// throw new DAOException(errMsg); //<-------------- +// } finally { +// disconnect(); +// } +// } +// +// +// //------------------------------------------------------------------------------------------- +// // REMOTE 서버정보 변경 +// //------------------------------------------------------------------------------------------- +// public int updatetRemoteDirectory(RemoteDirectoryVO remoteDirectoryVO) throws DAOException { +// +// int retValue = 0; +// int index = 0; +// +// try { +// +// String query = UPDATE_REMOTE_DIRECTORY; +// this.connect(query); +// logger.debug(">>> 리모트 디렉토리 수정 SQL : \n"+ query); +// +// index = 1; +// this.preparedStatement.setString(index++, remoteDirectoryVO.getRemoteServerId()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getRemoteServerId() +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getRemoteDirName ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getRemoteDirName () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getOrganCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getOrganCode () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getBizGroupCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getBizGroupCode () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getUseYn ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getUseYn () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getUpdateId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getUpdateId () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getUpdateTime ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getUpdateTime () +"]"); +// this.preparedStatement.setString(index++, remoteDirectoryVO.getRemoteDirId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirectoryVO.getRemoteDirId () +"]"); +// +// retValue = this.executeUpdate(); +// logger.info(">>> 리모트 디렉토리 수정 건수 : "+ retValue); +// +// return retValue; +// +// } catch (DAOException ex) { +// throw ex; +// } catch (Exception e) { +// String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); +// throw new DAOException(errMsg); //<-------------- +// } finally { +// disconnect(); +// } +// } +// +// +// //------------------------------------------------------------------------------------------- +// // REMOTE 서버정보 삭제 +// //------------------------------------------------------------------------------------------- +// public int deleteRemoteDirectory(String remoteDirId) throws DAOException { +// +// int retValue = 0; +// int index = 0; +// +// try { +// +// String query = DELETE_REMOTE_DIRECTORY; +// this.connect(query); +// logger.debug(">>> 리모트 디렉토리 삭제 SQL : \n"+ query); +// +// index = 1; +// this.preparedStatement.setString(index++, remoteDirId); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteDirId +"]"); +// +// retValue = this.executeUpdate(); +// logger.info(">>> 리모트 디렉토리 삭제 건수 : "+ retValue); +// +// return retValue; +// +// } catch (DAOException ex) { +// throw ex; +// } catch (Exception e) { +// String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); +// throw new DAOException(errMsg); //<-------------- +// } finally { +// disconnect(); +// } +// } + + +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteDirectoryManager.java b/src/com/eactive/eai/inbound/remote/RemoteDirectoryManager.java new file mode 100644 index 0000000..6c59c5f --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteDirectoryManager.java @@ -0,0 +1,49 @@ +package com.eactive.eai.inbound.remote; + +import com.eactive.eai.common.dao.DAOFactory; + +import java.util.ArrayList; + +public class RemoteDirectoryManager +{ + + //singleton 객체 생성 + private static RemoteDirectoryManager instance = new RemoteDirectoryManager(); + //singleton 객체 리턴 + public static RemoteDirectoryManager getInstance() { + return instance; + } + + //생성자 (다른 클래스에서 new 불가) + private RemoteDirectoryManager() {} + + + + public RemoteDirectoryVO detailRemoteDirectory(String remoteDirId) throws Exception { + RemoteDirectoryDAO dao = (RemoteDirectoryDAO)DAOFactory.newInstance().create(RemoteDirectoryDAO.class); + ArrayList alist = dao.selectRemoteDirectory("", "DIRECTORY_ID", remoteDirId); + if (alist.size() == 0) return null; + return (RemoteDirectoryVO) alist.get(0); + } + + public ArrayList searchRemoteDirectory(String searchProcessCode, String searchType, String searchText) throws Exception { + RemoteDirectoryDAO dao = (RemoteDirectoryDAO)DAOFactory.newInstance().create(RemoteDirectoryDAO.class); + return dao.selectRemoteDirectory(searchProcessCode, searchType, searchText); + } + +// public int insertRemoteDirectory(RemoteDirectoryVO remoteDirectoryVO) throws Exception { +// RemoteDirectoryDAO dao = (RemoteDirectoryDAO)DAOFactory.newInstance().create(RemoteDirectoryDAO.class); +// return dao.insertRemoteDirectory(remoteDirectoryVO); +// } +// +// public int updatetRemoteDirectory(RemoteDirectoryVO remoteDirectoryVO) throws Exception { +// RemoteDirectoryDAO dao = (RemoteDirectoryDAO)DAOFactory.newInstance().create(RemoteDirectoryDAO.class); +// return dao.updatetRemoteDirectory(remoteDirectoryVO); +// } +// +// public int deletetRemoteDirectory(String remoteDirId) throws Exception { +// RemoteDirectoryDAO dao = (RemoteDirectoryDAO)DAOFactory.newInstance().create(RemoteDirectoryDAO.class); +// return dao.deleteRemoteDirectory(remoteDirId); +// } + +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteDirectoryQuery.java b/src/com/eactive/eai/inbound/remote/RemoteDirectoryQuery.java new file mode 100644 index 0000000..0379919 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteDirectoryQuery.java @@ -0,0 +1,78 @@ +package com.eactive.eai.inbound.remote; + +import com.eactive.eai.common.dao.Keys; + +public interface RemoteDirectoryQuery +{ + + //REMOTE 서버별 작업디렉토리 목록 조회 + public static final String SEARCH_REMOTE_DIRECTORY = + "SELECT A.RmtSevrID , \n" + + " A.RmtSevrName , \n" + + " A.BjobBzwkDstcd , \n" + + " A.RmtSevrIP , \n" + + " A.RmtSevrNDMPortNoName , \n" + + " A.RmtSevrFTPPortNoName , \n" + + " A.RmtSevrFTPUID , \n" + + " A.RmtSevrFTPUserPwdName , \n" + + " A.RmtSevrRootDirName , \n" + + " A.RmtFileEvntCpyDstcd , \n" + + " A.ThisMsgUseYn , \n" + + " A.ThisMsgRegsntID , \n" + + " A.ThisMsgRegiHMS , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS , \n" + + " B.RmtSevrJobDirID , \n" + + " B.RmtSevrJobDirName , \n" + + " B.RmtSevrID , \n" + + " B.BjobBzwkDstcd , \n" + + " C.BjobBzwkName , \n" + + " LTRIM(RTRIM(B.OsidInstiDstcd )) AS OsidInstiDstcd , \n" + + " D.OsidInstiName , \n" + + " B.TranGroupDsticID , \n" + + " B.ThisMsgUseYn , \n" + + " B.ThisMsgRegsntID , \n" + + " B.ThisMsgRegiHMS , \n" + + " B.ThisMsgAmndrID , \n" + + " B.ThisMsgAmndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBU01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBU02 B \n" + + " LEFT OUTER JOIN " + Keys.TABLE_OWNER + "TSEAIBJ02 C \n" + + "ON B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + + " LEFT OUTER JOIN " + Keys.TABLE_OWNER + "TSEAIBJ06 D \n" + + "ON B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + + "AND LTRIM(RTRIM(B.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd)) \n" + + "WHERE A.RmtSevrID = B.RmtSevrID \n" + + "AND B.BjobBzwkDstcd LIKE ? || '%' \n"; + //REMOTE 서버작업디렉토리 등록 + public static final String INSERT_REMOTE_DIRECTORY = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBU02 ( \n" + + " RmtSevrJobDirID , \n" + + " RmtSevrJobDirName , RmtSevrID , BjobBzwkDstcd , OsidInstiDstcd , \n" + + " TranGroupDsticID , ThisMsgUseYn , ThisMsgRegsntID , ThisMsgRegiHMS , \n" + + " ThisMsgAmndrID , ThisMsgAmndHMS ) \n" + + "SELECT cast(? as VARCHAR (30)) || 'RD' || VALUE( TO_CHAR(INT(SUBSTR(MAX(RmtSevrJobDirID),12,3)) + 1, '000'), '001'), \n" + + " cast(? as VARCHAR (100)) , cast(? as VARCHAR (30)) , cast(? as CHARACTER (5)) , cast(? as CHARACTER (4)) , \n" + + " cast(? as VARCHAR (10)) , cast(? as CHARACTER (1)) , cast(? as VARCHAR (40)) , cast(? as CHARACTER (16)) , \n" + + " cast(? as VARCHAR (40)) , cast(? as CHARACTER (16)) \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBU02 \n" + + "WHERE RmtSevrID = ?"; + + + //REMOTE 서버 작업디렉토리 변경 + public static final String UPDATE_REMOTE_DIRECTORY = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBU02 \n" + + "SET RmtSevrID = ?, \n" + + " RmtSevrJobDirName = ?, \n" + + " OsidInstiDstcd = ?, \n" + + " TranGroupDsticID = ?, \n" + + " ThisMsgUseYn = ?, \n" + + " ThisMsgAmndrID = ?, \n" + + " ThisMsgAmndHMS = ? \n" + + "WHERE RmtSevrJobDirID = ?"; + + //REMOTE 서버 작업디렉토리 삭제 + public static final String DELETE_REMOTE_DIRECTORY = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBU02 \n" + + "WHERE RmtSevrJobDirID = ?"; +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteDirectoryVO.java b/src/com/eactive/eai/inbound/remote/RemoteDirectoryVO.java new file mode 100644 index 0000000..a1dba8e --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteDirectoryVO.java @@ -0,0 +1,61 @@ +package com.eactive.eai.inbound.remote; + +import java.io.Serializable; + +public class RemoteDirectoryVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String remoteDirId = ""; //리모트서버 작업디렉토리 ID + private String remoteDirName = ""; //리모트서버 작업디렉토리 명 + private String remoteServerId = ""; //리모트서버 ID + private String processCode = ""; //업무구분코드 + private String processName = ""; //업무구분명 + private String organCode = ""; //대외기관코드 + private String organName = ""; //대외기관명 + private String bizGroupCode = ""; //거래구분그룹코드 + private String bizGroupName = ""; //거래구분그룹명 + private String useYn = ""; //사용여부 + private String createId = ""; //등록자ID + private String createTime = ""; //등록시간 + private String updateId = ""; //수정자ID + private String updateTime = ""; //수정시간 + private RemoteServerVO remoteServerVO; + + + public void setRemoteDirId (String arg) { remoteDirId = arg; } + public void setRemoteDirName (String arg) { remoteDirName = arg; } + public void setRemoteServerId(String arg) { remoteServerId = arg; } + public void setProcessCode (String arg) { processCode = arg; } + public void setProcessName (String arg) { processName = arg; } + public void setOrganCode (String arg) { organCode = arg; } + public void setOrganName (String arg) { organName = arg; } + public void setBizGroupCode (String arg) { bizGroupCode = arg; } + public void setBizGroupName (String arg) { bizGroupName = arg; } + public void setUseYn (String arg) { useYn = arg; } + public void setCreateId (String arg) { createId = arg; } + public void setCreateTime (String arg) { createTime = arg; } + public void setUpdateId (String arg) { updateId = arg; } + public void setUpdateTime (String arg) { updateTime = arg; } + public void setRemoteServerVO (RemoteServerVO arg) { remoteServerVO = arg; } + + + public String getRemoteDirId () { return remoteDirId ; } + public String getRemoteDirName () { return remoteDirName ; } + public String getRemoteServerId() { return remoteServerId; } + public String getProcessCode () { return processCode ; } + public String getProcessName () { return processName ; } + public String getOrganCode () { return organCode ; } + public String getOrganName () { return organName ; } + public String getBizGroupCode () { return bizGroupCode ; } + public String getBizGroupName () { return bizGroupName ; } + public String getUseYn () { return useYn ; } + public String getCreateId () { return createId ; } + public String getCreateTime () { return createTime ; } + public String getUpdateId () { return updateId ; } + public String getUpdateTime () { return updateTime ; } + public RemoteServerVO getRemoteServerVO () { return remoteServerVO ; } + +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteServerDAO.java b/src/com/eactive/eai/inbound/remote/RemoteServerDAO.java new file mode 100644 index 0000000..b0162ad --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteServerDAO.java @@ -0,0 +1,282 @@ +package com.eactive.eai.inbound.remote; + +import java.sql.ResultSet; +import java.util.ArrayList; + +import org.slf4j.LoggerFactory; + +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.Logger; + +public class RemoteServerDAO extends BaseDAO implements RemoteServerQuery +{ + + public RemoteServerDAO() { + super(); + super.logger = Logger.getLogger(Logger.LOGGER_FILEEVENT); + } + + //------------------------------------------------------------------------------------------- + // EAI <-> REMOTE 파일 자동 전송시 업무구분에 의한 Remote 서버정보 조회 + //------------------------------------------------------------------------------------------- + public RemoteServerVO getRemoteServerByPath(String remotePath) throws DAOException { + + ResultSet rs = null; +// int index = 0; + String bjobBzwkDstcd= null; + + try { + String query = SELECT_REMOTE_SERVER_BY_PATH; + this.connect(query); +// logger.debug(">>> 업무구분에 의한 리모트 서버 조회 SQL : \n"+ query); + +// index = 1; + //this.preparedStatement.setString(index++, remotePath); logger.debug(">>> 바인드("+(index-1)+") : ["+ remotePath +"]"); + + rs = executeQuery(); + + RemoteServerVO info = null; + while (rs.next()) { + bjobBzwkDstcd = StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" )); + if (remotePath.indexOf(bjobBzwkDstcd) == -1 ) + continue; + + info = new RemoteServerVO(); + info.setRemoteServerId (StringUtil.nvlTrim(rs.getString("RmtSevrID" ))); // 리모트서버 ID (PK) + info.setRemoteServerName(StringUtil.nvlTrim(rs.getString("RmtSevrName"))); // 리모트서버 명 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분코드 (FK) + info.setRemoteServerIP (StringUtil.nvlTrim(rs.getString("RmtSevrIP" ))); // 리모트서버 IP + info.setRemoteNdmPort (StringUtil.nvlTrim(rs.getString("RmtSevrNDMPortNoName" ))); // 리모트서버 NDM Port Number + info.setRemoteFtpPort (StringUtil.nvlTrim(rs.getString("RmtSevrFTPPortNoName" ))); // 리모트서버 FTP Port Number + info.setRemoteUserId (StringUtil.nvlTrim(rs.getString("RmtSevrFTPUID" ))); // 리모트서버 FTP User ID + info.setRemotePassword (StringUtil.nvl (rs.getString("RmtSevrFTPUserPwdName" ))); // 리모트서버 FTP User Password + info.setRemoteRootDir (StringUtil.nvlTrim(rs.getString("RmtSevrRootDirName" ))); // 리모트서버 Root Directory + info.setAutoTransferType(StringUtil.nvlTrim(rs.getString("RmtFileEvntCpyDstcd"))); // 리포트 파일 이벤트시 파일 복사 방법 + info.setUseYn (StringUtil.nvlTrim(rs.getString("ThisMsgUseYn" ))); // 사용여부 + info.setCreateId (StringUtil.nvlTrim(rs.getString("ThisMsgRegsntID" ))); // 등록자ID + info.setCreateTime (StringUtil.nvlTrim(rs.getString("ThisMsgRegiHMS" ))); // 등록시간 + info.setUpdateId (StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID" ))); // 수정자ID + info.setUpdateTime (StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS" ))); // 수정시간 + + //리모트 Root Directory 가 "/" 로 끝나면 "/" 제거 + if (info.getRemoteRootDir().endsWith("/")) { + info.setRemoteRootDir(info.getRemoteRootDir().substring(0, info.getRemoteRootDir().length()-1)); + } + } + //logger.info(">>> 업무구분에 의한 리모트 서버 조회 RemoteServerVO : "+ info); + return info; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + + + + + //------------------------------------------------------------------------------------------- + // REMOTE 서버정보 목록 검색 및 상세조회 + //------------------------------------------------------------------------------------------- + public ArrayList selectRemoteServer(String searchProcessCode, String searchType, String searchText) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + String query = SEARCH_REMOTE_SERVER; + + if("SERVER_NAME".equals(searchType)) { + query = query + " AND A.\"RmtSevrName\" LIKE '%" + searchText + "%'\n ORDER BY A.\"RmtSevrID\" "; + } + else if("SERVER_ID".equals(searchType)) { + query = query + " AND A.\"RmtSevrID\" LIKE '" + searchText + "%'\n ORDER BY A.\"RmtSevrID\" "; + } + else if("SERVER_IP".equals(searchType)) { + query = query + " AND A.\"RmtSevrIP\" LIKE '%" + searchText + "%'\n ORDER BY A.\"RmtSevrID\" "; + } + else { + query = query + " ORDER BY A.\"RmtSevrID\" "; + } + + + this.connect(query); + logger.debug(">>> 리모트 서버 검색 SQL : \n"+ query); + + index = 1; + this.preparedStatement.setString(index++, searchProcessCode); logger.debug(">>> 바인드("+(index-1)+") : ["+ searchProcessCode +"]"); + + rs = executeQuery(); + + ArrayList alist = new ArrayList(); + while (rs.next()) { + RemoteServerVO info = new RemoteServerVO(); + info.setRemoteServerId (StringUtil.nvlTrim(rs.getString("RmtSevrID" ))); // 리모트서버 ID (PK) + info.setRemoteServerName(StringUtil.nvlTrim(rs.getString("RmtSevrName" ))); // 리모트서버 명 + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분코드 (FK) + info.setProcessName (StringUtil.nvlTrim(rs.getString("BjobBzwkName" ))); // 업무구분명 + info.setRemoteServerIP (StringUtil.nvlTrim(rs.getString("RmtSevrIP" ))); // 리모트서버 IP + info.setRemoteNdmPort (StringUtil.nvlTrim(rs.getString("RmtSevrNDMPortNoName" ))); // 리모트서버 NDM Port Number + info.setRemoteFtpPort (StringUtil.nvlTrim(rs.getString("RmtSevrFTPPortNoName" ))); // 리모트서버 FTP Port Number + info.setRemoteUserId (StringUtil.nvlTrim(rs.getString("RmtSevrFTPUID" ))); // 리모트서버 FTP User ID + info.setRemotePassword (StringUtil.nvl (rs.getString("RmtSevrFTPUserPwdName"))); // 리모트서버 FTP User Password + info.setRemoteRootDir (StringUtil.nvlTrim(rs.getString("RmtSevrRootDirName" ))); // 리모트서버 Root Directory + info.setAutoTransferType(StringUtil.nvlTrim(rs.getString("RmtFileEvntCpyDstcd" ))); // 리포트 파일 이벤트시 파일 복사 방법 + info.setUseYn (StringUtil.nvlTrim(rs.getString("ThisMsgUseYn" ))); // 사용여부 + info.setCreateId (StringUtil.nvlTrim(rs.getString("ThisMsgRegsntID" ))); // 등록자ID + info.setCreateTime (StringUtil.nvlTrim(rs.getString("ThisMsgRegiHMS" ))); // 등록시간 + info.setUpdateId (StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID" ))); // 수정자ID + info.setUpdateTime (StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS" ))); // 수정시간 + + //리모트 Root Directory 가 "/" 로 끝나면 "/" 제거 + if (info.getRemoteRootDir().endsWith("/")) { + info.setRemoteRootDir(info.getRemoteRootDir().substring(0, info.getRemoteRootDir().length()-1)); + } + alist.add(info); + } + logger.info(">>> 리모트 서버 검색 건수 : "+ alist.size()); + return alist; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + + //------------------------------------------------------------------------------------------- + // REMOTE 서버정보 신규 + //------------------------------------------------------------------------------------------- + public int insertRemoteServer(RemoteServerVO remoteServerVO) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + String query = INSERT_REMOTE_SERVER; + this.connect(query); + logger.debug(">>> 리모트 서버 등록 SQL : \n"+ query); + + index = 1; + this.preparedStatement.setString(index++, remoteServerVO.getProcessCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerName()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerName() +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getProcessCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerIP ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerIP () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteNdmPort ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteNdmPort () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteFtpPort ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteFtpPort () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteUserId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteUserId () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemotePassword ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemotePassword () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteRootDir ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteRootDir () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getAutoTransferType()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getAutoTransferType() +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getUseYn ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUseYn () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getCreateId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getCreateId () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getCreateTime ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getCreateTime () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getUpdateId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateId () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getUpdateTime ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateTime () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getProcessCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode () +"]"); + + retValue = this.executeUpdate(); + logger.info(">>> 리모트 서버 등록 건수 : "+ retValue); + + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + + + //------------------------------------------------------------------------------------------- + // REMOTE 서버정보 변경 + //------------------------------------------------------------------------------------------- + public int updatetRemoteServer(RemoteServerVO remoteServerVO) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + String query = UPDATE_REMOTE_SERVER; + this.connect(query); + logger.debug(">>> 리모트 서버 변경 SQL : \n"+ query); + + index = 1; + this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerName()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerName() +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getProcessCode ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerIP ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerIP () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteNdmPort ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteNdmPort () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteFtpPort ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteFtpPort () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteUserId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteUserId () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemotePassword ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemotePassword () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteRootDir ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteRootDir () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getAutoTransferType()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getAutoTransferType() +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getUseYn ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUseYn () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getUpdateId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateId () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getUpdateTime ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateTime () +"]"); + this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerId ()); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerId () +"]"); + + retValue = this.executeUpdate(); + logger.info(">>> 리모트 서버 수정 건수 : "+ retValue); + + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + + + //------------------------------------------------------------------------------------------- + // REMOTE 서버정보 삭제 + //------------------------------------------------------------------------------------------- + public int deleteRemoteServer(String remoteServerId) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + String query = DELETE_REMOTE_SERVER; + this.connect(query); + logger.debug(">>> 리모트 서버 삭제 SQL : \n"+ query); + + index = 1; + this.preparedStatement.setString(index++, remoteServerId); logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerId +"]"); + + retValue = this.executeUpdate(); + logger.info(">>> 리모트 서버 삭제 건수 : "+ retValue); + + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteServerManager.java b/src/com/eactive/eai/inbound/remote/RemoteServerManager.java new file mode 100644 index 0000000..e2fd28d --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteServerManager.java @@ -0,0 +1,54 @@ +package com.eactive.eai.inbound.remote; + +import com.eactive.eai.common.dao.DAOFactory; + +import java.util.ArrayList; + +public class RemoteServerManager +{ + + //singleton 객체 생성 + private static RemoteServerManager instance = new RemoteServerManager(); + //singleton 객체 리턴 + public static RemoteServerManager getInstance() { + return instance; + } + + //생성자 (다른 클래스에서 new 불가) + private RemoteServerManager() {} + + + + public RemoteServerVO getRemoteServerByPath(String remotePath) throws Exception { + RemoteServerDAO dao = (RemoteServerDAO)DAOFactory.newInstance().create(RemoteServerDAO.class); + return dao.getRemoteServerByPath(remotePath); + } + + public RemoteServerVO detailRemoteServer(String remoteServerId) throws Exception { + RemoteServerDAO dao = (RemoteServerDAO)DAOFactory.newInstance().create(RemoteServerDAO.class); + ArrayList alist = dao.selectRemoteServer("", "SERVER_ID", remoteServerId); + if (alist.size() == 0) return null; + return alist.get(0); + } + + public ArrayList searchRemoteServer(String searchProcessCode, String searchType, String searchText) throws Exception { + RemoteServerDAO dao = (RemoteServerDAO)DAOFactory.newInstance().create(RemoteServerDAO.class); + return dao.selectRemoteServer(searchProcessCode, searchType, searchText); + } + + public int insertRemoteServer(RemoteServerVO remoteServerVO) throws Exception { + RemoteServerDAO dao = (RemoteServerDAO)DAOFactory.newInstance().create(RemoteServerDAO.class); + return dao.insertRemoteServer(remoteServerVO); + } + + public int updatetRemoteServer(RemoteServerVO remoteServerVO) throws Exception { + RemoteServerDAO dao = (RemoteServerDAO)DAOFactory.newInstance().create(RemoteServerDAO.class); + return dao.updatetRemoteServer(remoteServerVO); + } + + public int deletetRemoteServer(String remoteServerId) throws Exception { + RemoteServerDAO dao = (RemoteServerDAO)DAOFactory.newInstance().create(RemoteServerDAO.class); + return dao.deleteRemoteServer(remoteServerId); + } + +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteServerQuery.java b/src/com/eactive/eai/inbound/remote/RemoteServerQuery.java new file mode 100644 index 0000000..0b760bb --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteServerQuery.java @@ -0,0 +1,101 @@ +package com.eactive.eai.inbound.remote; + +import com.eactive.eai.common.dao.Keys; + +public interface RemoteServerQuery +{ + //EAI <-> REMOTE 파일 자동 전송시 업무구분에 의한 Remote 서버정보 조회 + public static final String SELECT_REMOTE_SERVER_BY_PATH = + "SELECT RmtSevrID , \n" + + " RmtSevrName , \n" + + " BjobBzwkDstcd , \n" + + " RmtSevrIP , \n" + + " RmtSevrNDMPortNoName , \n" + + " RmtSevrFTPPortNoName , \n" + + " RmtSevrFTPUID , \n" + + " RmtSevrFTPUserPwdName , \n" + + " RmtSevrRootDirName , \n" + + " RmtFileEvntCpyDstcd , \n" + + " ThisMsgUseYn , \n" + + " ThisMsgRegsntID , \n" + + " ThisMsgRegiHMS , \n" + + " ThisMsgAmndrID , \n" + + " ThisMsgAmndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBU01 \n" + //+ "WHERE ? LIKE RmtSevrRootDirName || '%' \n" +// + "WHERE ? LIKE '%' || BjobBzwkDstcd || '%' \n" +// + "AND ThisMsgUseYn = '1' --사용중인 것만 조회"; + + "WHERE ThisMsgUseYn = '1' --사용중인 것만 조회"; + + //REMOTE 서버 목록 조회 + public static final String SEARCH_REMOTE_SERVER = + "SELECT A.RmtSevrID , \n" + + " A.RmtSevrName , \n" + + " A.BjobBzwkDstcd , \n" + + " B.BjobBzwkName , \n" + + " A.RmtSevrIP , \n" + + " A.RmtSevrNDMPortNoName , \n" + + " A.RmtSevrFTPPortNoName , \n" + + " A.RmtSevrFTPUID , \n" + + " A.RmtSevrFTPUserPwdName , \n" + + " A.RmtSevrRootDirName , \n" + + " A.RmtFileEvntCpyDstcd , \n" + + " A.ThisMsgUseYn , \n" + + " A.ThisMsgRegsntID , \n" + + " A.ThisMsgRegiHMS , \n" + + " A.ThisMsgAmndrID , \n" + + " A.ThisMsgAmndHMS \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBU01 A \n" +// + " " + Keys.TABLE_OWNER + "TSEAIBJ02 B \n" + + " LEFT OUTER JOIN " + Keys.TABLE_OWNER + "TSEAIBJ02 B \n" +// + "WHERE A.BjobBzwkDstcd = B.BjobBzwkDstcd (+) \n" + + "on A.BjobBzwkDstcd = B.BjobBzwkDstcd \n" +// + "AND A.BjobBzwkDstcd LIKE ? || '%' \n" + + "WHERE A.BjobBzwkDstcd LIKE ? || '%' \n"; + //+ " AND ( ( ? = 'SERVER_NAME' AND A.RmtSevrName LIKE '%' || ? || '%' ) OR \n" + //+ " ( ? = 'SERVER_ID' AND A.RmtSevrID LIKE ? || '%' ) OR \n" + //+ " ( ? = 'SERVER_IP' AND A.RmtSevrIP LIKE '%' || ? || '%' ) ) \n" + //+ "ORDER BY A.RmtSevrID "; + + //REMOTE 서버 등록 + public static final String INSERT_REMOTE_SERVER = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBU01 ( \n" + + " RmtSevrID , \n" + + " RmtSevrName , BjobBzwkDstcd , RmtSevrIP , RmtSevrNDMPortNoName , \n" + + " RmtSevrFTPPortNoName , RmtSevrFTPUID , RmtSevrFTPUserPwdName , RmtSevrRootDirName , \n" + + " RmtFileEvntCpyDstcd , ThisMsgUseYn , ThisMsgRegsntID , ThisMsgRegiHMS , \n" + + " ThisMsgAmndrID , ThisMsgAmndHMS ) \n" +// + "SELECT ? || 'RS' || NVL( TO_CHAR( SUBSTR(MAX(RmtSevrID),8,2) + 1, 'FM00'), '01'), \n" +// + "SELECT ? || 'RS' || VALUE( TO_CHAR(INT(SUBSTR(MAX(RmtSevrID),8,2)) + 1, '00'), '01'), \n" + + "SELECT cast(? as CHARACTER (5)) || 'RS' || VALUE( TO_CHAR(INT(SUBSTR(MAX(RmtSevrID),8,2)) + 1, '00'), '01'), \n" + + " cast (? as VARCHAR(100)) , cast(? as CHARACTER (5)) , cast (? as VARCHAR(15)) , \n" + + " cast (? as VARCHAR(10)) , cast (? as VARCHAR(10)) , cast (? as VARCHAR(40)) , cast (? as VARCHAR(40)) , \n" + + " cast (? as VARCHAR(300)) , cast (? as CHARACTER(3)) , cast (? as CHARACTER(1)) , \n" + + " cast (? as VARCHAR(40)) , cast (? as CHARACTER(16)) , cast (? as VARCHAR(40)) ,\n" + + " cast (? as CHARACTER(16)) \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBU01 \n" + + "WHERE BjobBzwkDstcd = ?"; + + //REMOTE 서버 변경 + public static final String UPDATE_REMOTE_SERVER = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBU01 \n" + + "SET RmtSevrName = ?, \n" + + " BjobBzwkDstcd = ?, \n" + + " RmtSevrIP = ?, \n" + + " RmtSevrNDMPortNoName = ?, \n" + + " RmtSevrFTPPortNoName = ?, \n" + + " RmtSevrFTPUID = ?, \n" + + " RmtSevrFTPUserPwdName = ?, \n" + + " RmtSevrRootDirName = ?, \n" + + " RmtFileEvntCpyDstcd = ?, \n" + + " ThisMsgUseYn = ?, \n" + + " ThisMsgAmndrID = ?, \n" + + " ThisMsgAmndHMS = ? \n" + + "WHERE RmtSevrID = ?"; + + //REMOTE 서버 삭제 + public static final String DELETE_REMOTE_SERVER = + "DELETE FROM " + Keys.TABLE_OWNER + "TSEAIBU01 \n" + + "WHERE RmtSevrID = ?"; + +} \ No newline at end of file diff --git a/src/com/eactive/eai/inbound/remote/RemoteServerVO.java b/src/com/eactive/eai/inbound/remote/RemoteServerVO.java new file mode 100644 index 0000000..b8e7425 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteServerVO.java @@ -0,0 +1,67 @@ +package com.eactive.eai.inbound.remote; + +import java.io.Serializable; + +public class RemoteServerVO implements Serializable +{ + + /** + * + */ + private static final long serialVersionUID = 1L; + private String remoteServerId = ""; //리모트서버 ID + private String remoteServerName = ""; //리모트서버 명 + private String processCode = ""; //업무구분코드 + private String processName = ""; //업무구분명 + private String remoteServerIP = ""; //리모트서버 IP + private String remoteNdmPort = ""; //리모트서버 NDM Port Number + private String remoteFtpPort = ""; //리모트서버 FTP Port Number + private String remoteUserId = ""; //리모트서버 FTP User ID + private String remotePassword = ""; //리모트서버 FTP User Password + private String remoteRootDir = ""; //리모트서버 Root Directory + private String autoTransferType = ""; //리포트 파일 이벤트시 파일 복사 방법 + private String useYn = ""; //사용여부 + private String createId = ""; //등록자ID + private String createTime = ""; //등록시간 + private String udpateId = ""; //수정자ID + private String updateTime = ""; //수정시간 + private String remoteNodeName = ""; //리모트서버 노드 명 + + + public void setRemoteServerId (String arg) { remoteServerId = arg; } + public void setRemoteServerName(String arg) { remoteServerName = arg; } + public void setProcessCode (String arg) { processCode = arg; } + public void setProcessName (String arg) { processName = arg; } + public void setRemoteServerIP (String arg) { remoteServerIP = arg; } + public void setRemoteNdmPort (String arg) { remoteNdmPort = arg; } + public void setRemoteFtpPort (String arg) { remoteFtpPort = arg; } + public void setRemoteUserId (String arg) { remoteUserId = arg; } + public void setRemotePassword (String arg) { remotePassword = arg; } + public void setRemoteRootDir (String arg) { remoteRootDir = arg; } + public void setAutoTransferType(String arg) { autoTransferType = arg; } + public void setUseYn (String arg) { useYn = arg; } + public void setCreateId (String arg) { createId = arg; } + public void setCreateTime (String arg) { createTime = arg; } + public void setUpdateId (String arg) { udpateId = arg; } + public void setUpdateTime (String arg) { updateTime = arg; } + public void setRemoteNodeName (String arg) { remoteNodeName = arg; } + + + public String getRemoteServerId () { return remoteServerId ; } + public String getRemoteServerName() { return remoteServerName ; } + public String getProcessCode () { return processCode ; } + public String getProcessName () { return processName ; } + public String getRemoteServerIP () { return remoteServerIP ; } + public String getRemoteNdmPort () { return remoteNdmPort ; } + public String getRemoteFtpPort () { return remoteFtpPort ; } + public String getRemoteUserId () { return remoteUserId ; } + public String getRemotePassword () { return remotePassword ; } + public String getRemoteRootDir () { return remoteRootDir ; } + public String getAutoTransferType() { return autoTransferType ; } + public String getUseYn () { return useYn ; } + public String getCreateId () { return createId ; } + public String getCreateTime () { return createTime ; } + public String getUpdateId () { return udpateId ; } + public String getUpdateTime () { return updateTime ; } + public String getRemoteNodeName () { return remoteNodeName ; } +} \ No newline at end of file diff --git a/src/com/eactive/eai/inbound/remote/RemoteTransfer.java b/src/com/eactive/eai/inbound/remote/RemoteTransfer.java new file mode 100644 index 0000000..d6f7a84 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteTransfer.java @@ -0,0 +1,316 @@ +package com.eactive.eai.inbound.remote; + +import java.io.File; +import java.util.Properties; + +import com.eactive.eai.adapter.ftp.Transfer; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.EzgatorUtil; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO; +import com.eactive.eai.batch.rule.dirInfo.DirInfoManager; +import com.eactive.eai.batch.rule.sysInfo.SysInfoManager; +import com.eactive.eai.batch.rule.sysInfo.SysInfoVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; +import com.eactive.eai.common.util.UCMsgSenderUtil; +import com.eactive.eai.common.util.UUIDGenerator; + +public class RemoteTransfer { + + // FileLoger + static Logger logger = Logger.getLogger(Logger.LOGGER_FILEEVENT); + + private String CBS_DIR_INFO = "CBSDirInfo"; + private String DEFAULT_SYS_CODE = "default.sys"; + private String DEFAULT_APP_CODE = "default.app"; + private String SEND_ROOT = "send.root"; + private RemoteTransferLogVO loginfo; + + public String sendFile(String procCode, String instCode, String fileName, String startPtrnDstcd, String userId, boolean cbsYn){ + BatchJobInfoVO bjvo = null; + try { + + loginfo = new RemoteTransferLogVO(); + loginfo.setFileTrsmtLogID(UUIDGenerator.getUUID()); + loginfo.setSendRecvYn(RemoteTransferLogKeys.SEND); + loginfo.setFileTrsmtStartPtrnDstcd(startPtrnDstcd); + loginfo.setThisMsgRegsntID(userId); + loginfo.setBjobBzwkDstcd(procCode); + loginfo.setOsidInstiDstcd(instCode); + + String srcFilePath = BatchDirUtil.getResponseArchDir() + + File.separatorChar + + procCode + + File.separatorChar + + instCode; + loginfo.setFileTrsmtPathName(srcFilePath); + loginfo.setTrsmtFileName(fileName); + String srcFileName = srcFilePath + File.separatorChar + fileName; + File file = new File(srcFileName); + if ( !file.exists() ){ + String msg = "E:수신 파일이 존재 하지 않습니다. + [" + srcFileName + "]"; + logger.error(msg); + return msg; + } + + loginfo.setFileTrsmtSize(file.length()); + + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(procCode, instCode); + bizCodeStartIndex = organInfo.getBizCdStartIdx(); + bizCodeEndIndex = organInfo.getBizCdEndIdx(); + + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex == 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + if (bizCodeEndIndex < 0 && 0 < fileName.length() + bizCodeEndIndex ) bizCodeEndIndex = fileName.length() + bizCodeEndIndex; + + + // 거래 구분 코드 길이가 가변인 경우( END INDEX가 0인 경우) + if ( organInfo.getBizCdEndIdx() == 0 ){ + String delStr = null; + try { + Properties orgInfo = PropManager.getInstance().getProperties( + "TelegramInfo{" + procCode + "_" + instCode + "}"); + delStr = orgInfo.getProperty( "del.string" ); + if ( delStr != null && !delStr.trim().equals("")){ + int delIndex = fileName.indexOf(delStr); + if ( delIndex > -1 ) { + bizCodeEndIndex = delIndex; + } + } + }catch( Exception e) {} + } + + String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex); + loginfo.setBjobMsgDstcd(bizCode); + bjvo = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode); + + String sysCd = PropManager.getInstance().getProperty(CBS_DIR_INFO, DEFAULT_SYS_CODE); + String applCd = PropManager.getInstance().getProperty(CBS_DIR_INFO, DEFAULT_APP_CODE); + + + String tarSysCode = ""; + String tarAppCode = ""; + + if ( sysCd != null && !sysCd.equals("")) + tarSysCode = sysCd; + + if ( applCd != null && !applCd.equals("")) + tarAppCode = applCd; + + if ( bjvo != null ){ + if ( bjvo.getSysCd()!= null && !bjvo.getSysCd().trim().equals("")) + tarSysCode = bjvo.getSysCd(); + if ( bjvo.getUapplCd()!= null && !bjvo.getUapplCd().trim().equals("")) + tarAppCode = bjvo.getUapplCd().toLowerCase(); + } + if ( cbsYn ){ + tarSysCode = sysCd; + }else{ + if ( tarSysCode.equals(sysCd) ){ + return ""; + } + } + + // 계정계로 보내는 경우 시스템코드가 null 이 아니고 업무코드가 null 이면 보내지 않는다. + if ( cbsYn && bjvo != null && bjvo.getSysCd()!= null && !bjvo.getSysCd().trim().equals("") && + ( bjvo.getUapplCd() == null || bjvo.getUapplCd().trim().equals("")) ){ + return ""; + } + + SysInfoVO vo = SysInfoManager.getInstance().getSysInfo(tarSysCode); + + if ( vo == null ){ + return "E:미등록 시스템 구분 코드입니다."; + } + + String rmtFileTrsmtPathName = vo.getRecvDir().replaceAll("#APP#", tarAppCode); + String rmtTrsmtFileName = procCode + "_" + instCode + "_" + fileName; + loginfo.setRmtFileTrsmtPathName(rmtFileTrsmtPathName); + loginfo.setRmtTrsmtFileName(rmtTrsmtFileName); + loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_START); + loginfo.setFileTrsmtStartHMS(DatetimeUtil.getCurrentTimeMillis()); + try { + RemoteTransferLogManager.getInstance().insertRemoteTransferLog(loginfo); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + try { + EzgatorUtil.rename(vo.getSysIp(), vo.getSysPort(), rmtFileTrsmtPathName + "/" + rmtTrsmtFileName, rmtFileTrsmtPathName + "/" + rmtTrsmtFileName +"_"+DatetimeUtil.getCurrentTimeMillis()); + } catch (Exception e) { + } + + EzgatorUtil.store(vo.getSysIp(), vo.getSysPort(), rmtFileTrsmtPathName + "/" + rmtTrsmtFileName, srcFileName); + + File chkFile = new File(srcFileName+BatchDirUtil.getResponseRootExt()); + chkFile.createNewFile(); + + EzgatorUtil.store(vo.getSysIp(), vo.getSysPort(), rmtFileTrsmtPathName + "/" + rmtTrsmtFileName+BatchDirUtil.getResponseRootExt(), srcFileName+BatchDirUtil.getResponseRootExt()); + + try { + loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_SUCCESS); + loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis()); + RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + + } catch (Throwable t) { + logger.error(t.getMessage(), t); + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIIFE005"); + logger.error(errMsg, t); //Local 수신 File Event Listener 에서 오류가 발생하였습니다. + UCMsgSenderUtil.setUcMsg(bjvo, procCode + "_" + instCode + "_" + fileName , false, t.getMessage()); + loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_ERROR); + loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis()); + StringBuffer sb = new StringBuffer(); + sb.append(t.getMessage()+"\n"); + sb.append(t.getClass().getCanonicalName()+"\n"); + StackTraceElement[] ste = t.getStackTrace(); + for (int inx = 0; inx < ste.length; inx++) { + sb.append("\tat "+ ste[inx].getClassName() +"(" +ste[inx].getFileName()).append(":"+ ste[inx].getLineNumber() +")\n"); + } + loginfo.setObstclOccurCausCtnt(new String(sb)); + RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo); + + } catch (Throwable e) { + logger.error("[Req Recv File Event] ★★★★★ 수신 File Event Listner 예외 처리 중 에러 !! ★★★★★", e); + } + } + return "S:송신 성공[" + fileName + "]"; + } + + public String recvFile( String fullFileName, String startPtrnDstcd, String userId ) { + BatchJobInfoVO bjvo = null; + try { + + loginfo = new RemoteTransferLogVO(); + loginfo.setFileTrsmtLogID(UUIDGenerator.getUUID()); + loginfo.setSendRecvYn(RemoteTransferLogKeys.RECV); + loginfo.setFileTrsmtStartPtrnDstcd(startPtrnDstcd); + loginfo.setThisMsgRegsntID(userId); + + String fileName = fullFileName; + String filePath = "/"; + int index = fullFileName.lastIndexOf("/"); + if ( index > -1 ){ + fileName = fullFileName.substring(index + 1); + filePath = fullFileName.substring(0,index); + } + loginfo.setTrsmtFileName(fileName); + + if ( fileName.length() < 11 ){ + return "E:파일명 길이가 충분하지 않습니다. 받은 파일명:[" + fileName + "], 파일명:[업무구분(5)_기관구분(4)_기관파일명]" ; + } + String procCode = fileName.substring(0,5); + String instCode = fileName.substring(6, 10); + loginfo.setBjobBzwkDstcd(procCode); + loginfo.setOsidInstiDstcd(instCode); + + String localFileName = fileName.substring(11); + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(procCode, instCode); + if ( organInfo == null ){ + return "E:미등록 업무/기관 코드입니다. 업무구분[" + procCode + "]기관코드[" + instCode + "]" ; + } + bizCodeStartIndex = organInfo.getBizCdStartIdx(); + bizCodeEndIndex = organInfo.getBizCdEndIdx(); + + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= localFileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > localFileName.length()) bizCodeEndIndex = localFileName.length(); + String bizCode = localFileName.substring(bizCodeStartIndex, bizCodeEndIndex); + + loginfo.setBjobMsgDstcd(bizCode); + bjvo = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode); + + String sysCd = PropManager.getInstance().getProperty(CBS_DIR_INFO, DEFAULT_SYS_CODE); + String tarSysCode = ""; + if ( sysCd != null && !sysCd.equals("")) + tarSysCode = sysCd; + if ( bjvo != null ){ + if ( bjvo.getSysCd()!= null && !bjvo.getSysCd().trim().equals("")) + tarSysCode = bjvo.getSysCd(); + }else{ + return "E:미등록 업무 구분(파일) 코드입니다."; + } + + SysInfoVO vo = SysInfoManager.getInstance().getSysInfo(tarSysCode); + + if ( vo == null ){ + return "E:미등록 시스템 구분 코드입니다."; + } + + String sendRootDir= PropManager.getInstance().getProperty(CBS_DIR_INFO, SEND_ROOT); + + loginfo.setFileTrsmtPathName(sendRootDir); + loginfo.setRmtFileTrsmtPathName(filePath); + loginfo.setRmtTrsmtFileName(localFileName); + loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_START); + loginfo.setFileTrsmtStartHMS(DatetimeUtil.getCurrentTimeMillis()); + try { + RemoteTransferLogManager.getInstance().insertRemoteTransferLog(loginfo); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + long size = -1; + try{ + size = FTPUtil.retrieve(vo.getSysIp(), vo.getSysPort(), vo.getUserId(), vo.getUserPassword(), fullFileName, sendRootDir, vo.getSftpYn().equals("1"), logger, Transfer.AUTH_TYPE_ID); + }catch( Exception t){ + try { + // 파일로그 처리 + String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIIFE005"); + logger.error(errMsg, t); //Local 수신 File Event Listener 에서 오류가 발생하였습니다. + UCMsgSenderUtil.setUcMsg(bjvo, fileName , false, t.getMessage()); + loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_ERROR); + loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis()); + StringBuffer sb = new StringBuffer(); + sb.append(t.getMessage()+"\n"); + sb.append(t.getClass().getCanonicalName()+"\n"); + StackTraceElement[] ste = t.getStackTrace(); + for (int inx = 0; inx < ste.length; inx++) { + sb.append("\tat "+ ste[inx].getClassName() +"(" +ste[inx].getFileName()).append(":"+ ste[inx].getLineNumber() +")\n"); + } + loginfo.setObstclOccurCausCtnt(new String(sb)); + RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo); + + } catch (Throwable e) { + logger.error("[Req Recv File Event] ★★★★★ 수신 File Event Listner 예외 처리 중 에러 !! ★★★★★", e); + } + + return "E:" + t.getMessage(); + } + + try { + loginfo.setFileTrsmtSize(size); + loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_SUCCESS); + loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis()); + RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } catch (Throwable t) { + logger.error(t.getMessage(), t); + return "E:수신 실패[" + t.getMessage() +"]"; + + } + + return "S:수신 성공[" + fullFileName +"]"; + } + +} + diff --git a/src/com/eactive/eai/inbound/remote/RemoteTransferLogDAO.java b/src/com/eactive/eai/inbound/remote/RemoteTransferLogDAO.java new file mode 100644 index 0000000..c592a8d --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteTransferLogDAO.java @@ -0,0 +1,138 @@ +package com.eactive.eai.inbound.remote; + +import java.sql.ResultSet; + +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.common.dao.BaseDAO; +import com.eactive.eai.common.dao.DAOException; +import com.eactive.eai.common.exception.ExceptionUtil; + +public class RemoteTransferLogDAO extends BaseDAO implements RemoteTransferLogQuery +{ + + //------------------------------------------------------------------------------------------- + // + //------------------------------------------------------------------------------------------- + public int insertRemoteTransferLog(RemoteTransferLogVO logVO) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + this.connect(INSERT_REMOTE_TRANSFER_LOG); + //logger.debug(">>> 리모트 파일 전송로그 등록 SQL : \n"+ INSERT_REMOTE_TRANSFER_LOG); + + index = 1; + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtLogID (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getFileTrsmtLogID (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtStartPtrnDstcd(), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getFileTrsmtStartPtrnDstcd(), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtStartHMS (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getFileTrsmtStartHMS (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtEndHMS (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getFileTrsmtEndHMS (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getBjobBzwkDstcd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getBjobBzwkDstcd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getOsidInstiDstcd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getOsidInstiDstcd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getBjobMsgDstcd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getBjobMsgDstcd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtPathName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getFileTrsmtPathName (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getTrsmtFileName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getTrsmtFileName (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getRmtFileTrsmtPathName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getRmtFileTrsmtPathName (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getRmtTrsmtFileName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getRmtTrsmtFileName (), " ") +"]"); + this.preparedStatement.setLong (index++, logVO.getFileTrsmtSize() ); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getFileTrsmtSize (), "0") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getThisMsgRegsntID (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getThisMsgRegsntID (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getThisStgePrcssRsultCd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getThisStgePrcssRsultCd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getSendRecvYn (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getThisStgePrcssRsultCd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getObstclOccurCausCtnt (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.getObstclOccurCausCtnt (), " ") +"]"); + + retValue = this.executeUpdate(); + //logger.info(">>> 리모트 파일 전송로그 등록 건수 : "+ retValue); + + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + + public int updateRemoteTransferLog(RemoteTransferLogVO logVO) throws DAOException { + + int retValue = 0; + int index = 0; + + try { + + this.connect(UPDATE_REMOTE_TRANSFER_LOG); + //logger.debug(">>> 리모트 파일 전송로그 수정 SQL : \n"+ UPDATE_REMOTE_TRANSFER_LOG); + + index = 1; + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtStartPtrnDstcd(), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geFileTrsmtStartPtrnDstcd(), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtStartHMS (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geFileTrsmtStartHMS (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtEndHMS (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geFileTrsmtEndHMS (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getBjobBzwkDstcd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geBjobBzwkDstcd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getOsidInstiDstcd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geOsidInstiDstcd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getBjobMsgDstcd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geBjobMsgDstcd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtPathName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geFileTrsmtPathName (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getTrsmtFileName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geTrsmtFileName (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getRmtFileTrsmtPathName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geRmtFileTrsmtPathName (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getRmtTrsmtFileName (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geRmtTrsmtFileName (), " ") +"]"); + this.preparedStatement.setLong (index++, logVO.getFileTrsmtSize() ); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geFileTrsmtSize (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getThisMsgRegsntID (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geThisMsgRegsntID (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getThisStgePrcssRsultCd (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geThisStgePrcssRsultCd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getSendRecvYn (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geThisStgePrcssRsultCd (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getObstclOccurCausCtnt (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geObstclOccurCausCtnt (), " ") +"]"); + this.preparedStatement.setString(index++, StringUtil.nvlTrim(logVO.getFileTrsmtLogID (), " ")); //logger.debug(">>> 바인드("+(index-1)+") : ["+ StringUtil.nvlTrim(logVO.geFileTrsmtLogID (), " ") +"]"); + + retValue = this.executeUpdate(); + //logger.info(">>> 리모트 파일 전송로그 등록 수정 : "+ retValue); + + if ( retValue == 0 ){ + retValue = insertRemoteTransferLog(logVO); + } + return retValue; + + } catch (DAOException ex) { + throw ex; + } catch (Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {}); + throw new DAOException(errMsg); //<-------------- + } finally { + disconnect(); + } + } + public RemoteTransferLogVO getRemoteTransferLog( String fileTrsmtLogID ) throws DAOException { + RemoteTransferLogVO vo = null; + ResultSet rs = null; + try { + this.connect(SELECT_REMOTE_TRANSFER_LOG); + this.preparedStatement.setString(1, fileTrsmtLogID); + rs = executeQuery(); + vo = new RemoteTransferLogVO(); + while (rs.next()) + { + vo.setFileTrsmtStartPtrnDstcd(rs.getString("FileTrsmtStartPtrnDstcd")); + vo.setFileTrsmtStartHMS (rs.getString("FileTrsmtStartHMS" )); + vo.setFileTrsmtEndHMS (rs.getString("FileTrsmtEndHMS" )); + vo.setBjobBzwkDstcd (rs.getString("BjobBzwkDstcd" )); + vo.setOsidInstiDstcd (rs.getString("OsidInstiDstcd" )); + vo.setBjobMsgDstcd (rs.getString("BjobMsgDstcd" )); + vo.setFileTrsmtPathName (rs.getString("FileTrsmtPathName" )); + vo.setTrsmtFileName (rs.getString("TrsmtFileName" )); + vo.setRmtFileTrsmtPathName (rs.getString("RmtFileTrsmtPathName" )); + vo.setRmtTrsmtFileName (rs.getString("RmtTrsmtFileName" )); + vo.setFileTrsmtSize (rs.getInt ("FileTrsmtSize" )); + vo.setThisMsgRegsntID (rs.getString("ThisMsgRegsntID" )); + vo.setThisStgePrcssRsultCd (rs.getString("ThisStgePrcssRsultCd" )); + vo.setSendRecvYn (rs.getString("SendRecvYn" )); + vo.setObstclOccurCausCtnt (rs.getString("ObstclOccurCausCtnt" )); + } + } catch(Exception e) { + logger.error(e.getMessage(), e); +// throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMFR017", new String[] {strRuleCode, strPhaseCode})); + } finally { + this.disconnect(); + } + return vo; + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/inbound/remote/RemoteTransferLogKeys.java b/src/com/eactive/eai/inbound/remote/RemoteTransferLogKeys.java new file mode 100644 index 0000000..18bad29 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteTransferLogKeys.java @@ -0,0 +1,14 @@ +package com.eactive.eai.inbound.remote; + +public class RemoteTransferLogKeys { + public static final String START_BY_EVENT = "E"; + public static final String START_BY_UI = "U"; + public static final String START_BY_API = "A"; + public static final String STARTER_SYSTEM = "SYSTEM"; + public static final String STATUS_START = "S"; + public static final String STATUS_SUCCESS = "T"; + public static final String STATUS_ERROR = "E"; + public static final String SEND = "S"; + public static final String RECV = "R"; + +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteTransferLogManager.java b/src/com/eactive/eai/inbound/remote/RemoteTransferLogManager.java new file mode 100644 index 0000000..ad2dabf --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteTransferLogManager.java @@ -0,0 +1,31 @@ +package com.eactive.eai.inbound.remote; + +import com.eactive.eai.common.dao.DAOFactory; + +public class RemoteTransferLogManager +{ + + //singleton 객체 생성 + private static RemoteTransferLogManager instance = new RemoteTransferLogManager(); + //singleton 객체 리턴 + public static RemoteTransferLogManager getInstance() { + return instance; + } + + //생성자 (다른 클래스에서 new 불가) + private RemoteTransferLogManager() {} + + public int insertRemoteTransferLog(RemoteTransferLogVO remoteTransferLogVO) throws Exception { + RemoteTransferLogDAO dao = (RemoteTransferLogDAO)DAOFactory.newInstance().create(RemoteTransferLogDAO.class); + return dao.insertRemoteTransferLog(remoteTransferLogVO); + } + + public int updateRemoteTransferLog(RemoteTransferLogVO remoteTransferLogVO) throws Exception { + RemoteTransferLogDAO dao = (RemoteTransferLogDAO)DAOFactory.newInstance().create(RemoteTransferLogDAO.class); + return dao.updateRemoteTransferLog(remoteTransferLogVO); + } + public RemoteTransferLogVO getRemoteTransferLog( String fileTrsmtLogID ) throws Exception { + RemoteTransferLogDAO dao = (RemoteTransferLogDAO)DAOFactory.newInstance().create(RemoteTransferLogDAO.class); + return dao.getRemoteTransferLog(fileTrsmtLogID); + } +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteTransferLogQuery.java b/src/com/eactive/eai/inbound/remote/RemoteTransferLogQuery.java new file mode 100644 index 0000000..28dbeba --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteTransferLogQuery.java @@ -0,0 +1,83 @@ +package com.eactive.eai.inbound.remote; + +import com.eactive.eai.common.dao.Keys; + +public interface RemoteTransferLogQuery +{ + + public static final String INSERT_REMOTE_TRANSFER_LOG = + "INSERT INTO " + Keys.TABLE_OWNER + "TSEAIBU03 ( \n" + + " FileTrsmtLogID ,\n" + + " FileTrsmtStartPtrnDstcd ,\n" + + " FileTrsmtStartHMS ,\n" + + " FileTrsmtEndHMS ,\n" + + " BjobBzwkDstcd ,\n" + + " OsidInstiDstcd ,\n" + + " BjobMsgDstcd ,\n" + + " FileTrsmtPathName ,\n" + + " TrsmtFileName ,\n" + + " RmtFileTrsmtPathName ,\n" + + " RmtTrsmtFileName ,\n" + + " FileTrsmtSize ,\n" + + " ThisMsgRegsntID ,\n" + + " ThisMsgRegiHMS ,\n" + + " ThisStgePrcssRsultCd ,\n" + + " SendRecvYn ,\n" + + " ObstclOccurCausCtnt )\n" + + "VALUES ( \n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " ? ,\n" + + " TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3'),\n" + + " ? ,\n" + + " ? ,\n" + + " ? )"; + + public static final String UPDATE_REMOTE_TRANSFER_LOG = + "UPDATE " + Keys.TABLE_OWNER + "TSEAIBU03\n" + + "SET FileTrsmtStartPtrnDstcd = ?, \n" + + " FileTrsmtStartHMS = ?, \n" + + " FileTrsmtEndHMS = ?, \n" + + " BjobBzwkDstcd = ?, \n" + + " OsidInstiDstcd = ?, \n" + + " BjobMsgDstcd = ?, \n" + + " FileTrsmtPathName = ?, \n" + + " TrsmtFileName = ?, \n" + + " RmtFileTrsmtPathName = ?, \n" + + " RmtTrsmtFileName = ?, \n" + + " FileTrsmtSize = ?, \n" + + " ThisMsgRegsntID = ?, \n" + + " ThisStgePrcssRsultCd = ?, \n" + + " SendRecvYn = ?, \n" + + " ObstclOccurCausCtnt = ? \n" + + "WHERE FileTrsmtLogID = ? "; + + public static final String SELECT_REMOTE_TRANSFER_LOG = + "SELECT FileTrsmtStartPtrnDstcd ,\n" + + " FileTrsmtStartHMS ,\n" + + " FileTrsmtEndHMS ,\n" + + " BjobBzwkDstcd ,\n" + + " OsidInstiDstcd ,\n" + + " BjobMsgDstcd ,\n" + + " FileTrsmtPathName ,\n" + + " TrsmtFileName ,\n" + + " RmtFileTrsmtPathName ,\n" + + " RmtTrsmtFileName ,\n" + + " FileTrsmtSize ,\n" + + " ThisMsgRegsntID ,\n" + + " ThisStgePrcssRsultCd ,\n" + + " SendRecvYn ,\n" + + " ObstclOccurCausCtnt \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBU03\n" + + "WHERE FileTrsmtLogID = ? "; +} diff --git a/src/com/eactive/eai/inbound/remote/RemoteTransferLogVO.java b/src/com/eactive/eai/inbound/remote/RemoteTransferLogVO.java new file mode 100644 index 0000000..7d11a2d --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/RemoteTransferLogVO.java @@ -0,0 +1,147 @@ +package com.eactive.eai.inbound.remote; + +import java.io.Serializable; + +public class RemoteTransferLogVO implements Serializable +{ + private static final long serialVersionUID = 1L; + private String fileTrsmtLogID = ""; //파일전송로그ID + private String fileTrsmtStartPtrnDstcd = ""; //파일전송시작유형구분코드 + private String fileTrsmtStartHMS = ""; //파일전송시작시각 + private String fileTrsmtEndHMS = ""; //파일전송종료시각 + private String bjobBzwkDstcd = ""; //BATCH작업업무구분코드 + private String osidInstiDstcd = ""; //대외기관구분코드 + private String bjobMsgDstcd = ""; //BATCH작업메시지구분코드 + private String fileTrsmtPathName = ""; //파일전송경로명 + private String trsmtFileName = ""; //전송파일명 + private String rmtFileTrsmtPathName = ""; //원격파일전송경로명 + private String rmtTrsmtFileName = ""; //원격전송파일명 + private long fileTrsmtSize = 0L; //파일전송크기 + private String thisMsgRegsntID = ""; //당메시지등록자ID + private String thisMsgRegiHMS = ""; //당메시지등록시각 + private String thisStgePrcssRsultCd = ""; //당단계처리결과코드 + private String obstclOccurCausCtnt = ""; //장애발생원인내용 + private String SendRecvYn = ""; //송수신구분 + + public String getFileTrsmtLogID() { + return fileTrsmtLogID; + } + public void setFileTrsmtLogID(String fileTrsmtLogID) { + this.fileTrsmtLogID = fileTrsmtLogID; + } + public String getFileTrsmtStartPtrnDstcd() { + return fileTrsmtStartPtrnDstcd; + } + public void setFileTrsmtStartPtrnDstcd(String fileTrsmtStartPtrnDstcd) { + this.fileTrsmtStartPtrnDstcd = fileTrsmtStartPtrnDstcd; + } + public String getFileTrsmtStartHMS() { + return fileTrsmtStartHMS; + } + public void setFileTrsmtStartHMS(String fileTrsmtStartHMS) { + this.fileTrsmtStartHMS = fileTrsmtStartHMS; + } + public String getFileTrsmtEndHMS() { + return fileTrsmtEndHMS; + } + public void setFileTrsmtEndHMS(String fileTrsmtEndHMS) { + this.fileTrsmtEndHMS = fileTrsmtEndHMS; + } + public String getBjobBzwkDstcd() { + return bjobBzwkDstcd; + } + public void setBjobBzwkDstcd(String bjobBzwkDstcd) { + this.bjobBzwkDstcd = bjobBzwkDstcd; + } + public String getOsidInstiDstcd() { + return osidInstiDstcd; + } + public void setOsidInstiDstcd(String osidInstiDstcd) { + this.osidInstiDstcd = osidInstiDstcd; + } + public String getBjobMsgDstcd() { + return bjobMsgDstcd; + } + public void setBjobMsgDstcd(String bjobMsgDstcd) { + this.bjobMsgDstcd = bjobMsgDstcd; + } + public String getFileTrsmtPathName() { + return fileTrsmtPathName; + } + public void setFileTrsmtPathName(String fileTrsmtPathName) { + this.fileTrsmtPathName = fileTrsmtPathName; + } + public String getTrsmtFileName() { + return trsmtFileName; + } + public void setTrsmtFileName(String trsmtFileName) { + this.trsmtFileName = trsmtFileName; + } + public String getRmtFileTrsmtPathName() { + return rmtFileTrsmtPathName; + } + public void setRmtFileTrsmtPathName(String rmtFileTrsmtPathName) { + this.rmtFileTrsmtPathName = rmtFileTrsmtPathName; + } + public String getRmtTrsmtFileName() { + return rmtTrsmtFileName; + } + public void setRmtTrsmtFileName(String rmtTrsmtFileName) { + this.rmtTrsmtFileName = rmtTrsmtFileName; + } + public long getFileTrsmtSize() { + return fileTrsmtSize; + } + public void setFileTrsmtSize(long fileTrsmtSize) { + this.fileTrsmtSize = fileTrsmtSize; + } + public String getThisMsgRegsntID() { + return thisMsgRegsntID; + } + public void setThisMsgRegsntID(String thisMsgRegsntID) { + this.thisMsgRegsntID = thisMsgRegsntID; + } + public String getThisMsgRegiHMS() { + return thisMsgRegiHMS; + } + public void setThisMsgRegiHMS(String thisMsgRegiHMS) { + this.thisMsgRegiHMS = thisMsgRegiHMS; + } + public String getThisStgePrcssRsultCd() { + return thisStgePrcssRsultCd; + } + public void setThisStgePrcssRsultCd(String thisStgePrcssRsultCd) { + this.thisStgePrcssRsultCd = thisStgePrcssRsultCd; + } + public String getObstclOccurCausCtnt() { + return obstclOccurCausCtnt; + } + public void setObstclOccurCausCtnt(String obstclOccurCausCtnt) { + this.obstclOccurCausCtnt = obstclOccurCausCtnt; + } + public String getSendRecvYn() { + return SendRecvYn; + } + public void setSendRecvYn(String sendRecvYn) { + SendRecvYn = sendRecvYn; + } + + @Override + public String toString() { + return "RemoteTransferLogVO [fileTrsmtLogID=" + fileTrsmtLogID + + ", fileTrsmtStartPtrnDstcd=" + fileTrsmtStartPtrnDstcd + + ", fileTrsmtStartHMS=" + fileTrsmtStartHMS + + ", fileTrsmtEndHMS=" + fileTrsmtEndHMS + ", bjobBzwkDstcd=" + + bjobBzwkDstcd + ", osidInstiDstcd=" + osidInstiDstcd + + ", bjobMsgDstcd=" + bjobMsgDstcd + ", fileTrsmtPathName=" + + fileTrsmtPathName + ", trsmtFileName=" + trsmtFileName + + ", rmtFileTrsmtPathName=" + rmtFileTrsmtPathName + + ", rmtTrsmtFileName=" + rmtTrsmtFileName + + ", fileTrsmtSize=" + + fileTrsmtSize + ", thisMsgRegsntID=" + thisMsgRegsntID + + ", thisMsgRegiHMS=" + thisMsgRegiHMS + + ", thisStgePrcssRsultCd=" + thisStgePrcssRsultCd + + ", obstclOccurCausCtnt=" + obstclOccurCausCtnt + "]"; + } + +} diff --git a/src/com/eactive/eai/inbound/remote/TargetFileVO.java b/src/com/eactive/eai/inbound/remote/TargetFileVO.java new file mode 100644 index 0000000..3630e83 --- /dev/null +++ b/src/com/eactive/eai/inbound/remote/TargetFileVO.java @@ -0,0 +1,30 @@ +package com.eactive.eai.inbound.remote; + +import java.io.Serializable; + +public class TargetFileVO implements Serializable +{ + /** + * + */ + private static final long serialVersionUID = 1L; + private String name = ""; + private long size = 0; + private long lastModified = 0; + private boolean directory = false; + private boolean file = false; + + + public void setName (String arg) { name = arg; } + public void setSize (long arg) { size = arg; } + public void setLastModified(long arg) { lastModified = arg; } + public void setDirectory (boolean arg) { directory = arg; } + public void setFile (boolean arg) { file = arg; } + + + public String getName () { return name ; } + public long getSize () { return size ; } + public long getLastModified() { return lastModified; } + public boolean isDirectory () { return directory ; } + public boolean isFile () { return file ; } +} diff --git a/src/com/eactive/eai/test/DatePatternTester.java b/src/com/eactive/eai/test/DatePatternTester.java new file mode 100644 index 0000000..760b19c --- /dev/null +++ b/src/com/eactive/eai/test/DatePatternTester.java @@ -0,0 +1,52 @@ +package com.eactive.eai.test; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +public class DatePatternTester { + + /** + * @param args + */ + + public static String getString(String patern) + { + SimpleDateFormat formatter = new SimpleDateFormat(patern); + String curDate = formatter.format(Calendar.getInstance().getTime()); + return curDate; + } + + public static void main(String[] args) { +// String pattern = args[0]; +// System.out.print( "[TEST결과]" + pattern + "-->" + getString(pattern) ); +// for ( int year = 1971; year < 3000; year++){ +// if ( LunarCalendar.toSolar(year+"0815").substring(4).equals("0908")) +// System.out.println(LunarCalendar.toSolar(year+"0815")); +// } +// System.out.println(LunarCalendar.toLunar("19421205")); +// System.out.println(LunarCalendar.toSolar("20121029")); + boolean res = isRightDate("20130731"); + System.out.println("res-->" + res); + + } +// private static boolean isDateValue(String srcValue) { +// try { (new SimpleDateFormat( "yyyyMMdd")).parse(srcValue); } catch (Exception e) { e.printStackTrace(); return false; } +// return true; +// } + private static boolean isRightDate(String date) { + String sdate = null; + sdate = date.substring(0,4) + "-" + date.substring(4,6) + "-" + date.substring(6); + + java.sql.Date dt = null; + try { + dt = java.sql.Date.valueOf(sdate); + } catch (Exception e) { + return false; + } + + if ( dt.toString().equals(sdate) ) return true; + else return false; + } + + +} diff --git a/src/datasource.properties b/src/datasource.properties new file mode 100644 index 0000000..c817b14 --- /dev/null +++ b/src/datasource.properties @@ -0,0 +1,2 @@ +# oracle/mariadb/postgresql +db.vendor=oracle \ No newline at end of file