This commit is contained in:
Rinjae
2025-09-05 18:57:45 +09:00
commit aacc1a389e
1229 changed files with 167963 additions and 0 deletions
@@ -0,0 +1,546 @@
package com.eactive.eai.common.web;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.rmi.RemoteException;
import javax.sql.DataSource;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.rmi.RmiServiceExporter;
import com.eactive.eai.adapter.socket2.config.SocketAdapterManager;
import com.eactive.eai.common.dao.Keys;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleManager;
import com.eactive.eai.common.logger.async.AsyncLoggingPoolManager;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.routing.rmi.RemoteProxy;
import com.eactive.eai.common.routing.rmi.RemoteProxyImpl;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.server.EAIServerVO;
import com.eactive.eai.common.state.ElinkStateManager;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.ServiceLocator;
import com.eactive.eai.common.util.ServiceLocatorException;
import com.eactive.eai.env.ConfigKeys;
import com.eactive.eai.env.ElinkConfig;
import com.eactive.eai.common.logger.async.AsyncHttpLoggingPoolManager;
/**
* eLink FrameWork이 초기화(Deploy)될 때 실행되어야 할 작업을 정의
*/
@SuppressWarnings("deprecation")
public class AppInitializer implements InitializingBean, DisposableBean {
RemoteProxy remoteProxy = new RemoteProxyImpl();
Class serviceInterface = RemoteProxy.class;
RmiServiceExporter rmiServiceExporter = new org.springframework.remoting.rmi.RmiServiceExporter();
@Autowired
private LifecycleManager lifecycleManager;
@Autowired
private EAIServerManager eaiServerManager;
private DataSource dataSource;
private String instName;
private String instPort;
private String tableOwner;
private String scalable;
private boolean isScalable;
private String routerUrl;
private String systemType; // eLink System Type
private String systemMode = "D"; // eLink System Mode : [P/T/D/S
private String eaiServerExtractor = "";
private String jndiName = "";
private int shutdownWaitSecs = 60;
private int shutdownWaitIntervalMs = 500;
private static final String SHUTDOWN_WAIT_SECS = "shutdown.wait.secs";
private static final String SHUTDOWN_WAIT_INTERVALMS = "shutdown.wait.intervalms";
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
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 setScalable(String scalable) {
this.scalable = scalable;
}
public String getScalable() {
return scalable;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public void setSystemMode(String systemMode) {
this.systemMode = systemMode;
}
private String rmiPort;
private String rmiServicePort;
public String getRmiPort() {
return rmiPort;
}
public void setRmiPort(String rmiPort) {
this.rmiPort = rmiPort;
}
public String getRmiServicePort() {
return rmiServicePort;
}
public void setRmiServicePort(String rmiServicePort) {
this.rmiServicePort = rmiServicePort;
}
public String getRouterUrl() {
return routerUrl;
}
public void setRouterUrl(String routerUrl) {
this.routerUrl = routerUrl;
}
public String getInstPort() {
return instPort;
}
public void setInstPort(String instPort) {
this.instPort = instPort;
}
public String getEaiServerExtractor() {
return eaiServerExtractor;
}
public void setEaiServerExtractor(String eaiServerExtractor) {
this.eaiServerExtractor = eaiServerExtractor;
}
public int getShutdownWaitSecs() {
return shutdownWaitSecs;
}
public void setShutdownWaitSecs(int shutdownWaitSecs) {
this.shutdownWaitSecs = shutdownWaitSecs;
}
public int getShutdownWaitIntervalMs() {
return shutdownWaitIntervalMs;
}
public void setShutdownWaitIntervalMs(int shutdownWaitIntervalMs) {
this.shutdownWaitIntervalMs = shutdownWaitIntervalMs;
}
@SuppressWarnings("deprecation")
private void initRmiServer(int registryPort, int servicePort) throws RemoteException {
rmiServiceExporter.setServiceName("RemoteProxy");
rmiServiceExporter.setService(remoteProxy);
rmiServiceExporter.setServiceInterface(serviceInterface);
rmiServiceExporter.setRegistryPort(registryPort);
rmiServiceExporter.setServicePort(servicePort);
rmiServiceExporter.setAlwaysCreateRegistry(true);
rmiServiceExporter.afterPropertiesSet();
}
private void stopRmiServer() {
if(rmiServiceExporter != null) {
try {
rmiServiceExporter.destroy();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* eLink FrameWork의 웹어플리케이션이 될 때 초기화 작업을 수행
**/
private void init() {
ElinkStateManager.getInstance().setWaitMaxMs(shutdownWaitSecs * 1000);
ElinkStateManager.getInstance().setSleepIntervalMs(shutdownWaitIntervalMs);
ElinkStateManager.getInstance().starting();
if (StringUtils.isBlank(System.getProperty(com.eactive.eai.common.server.Keys.EAI_SYSTEM_TYPE))) {
if (StringUtils.isNotBlank(systemType)) {
System.setProperty(com.eactive.eai.common.server.Keys.EAI_SYSTEM_TYPE, systemType);
}
}
if (StringUtils.isBlank(System.getProperty("scalable"))) {
if (StringUtils.isNotBlank(scalable)) {
System.setProperty("scalable", scalable);
}
}
if (StringUtils.isBlank(System.getProperty("router.url"))) {
if (StringUtils.isNotBlank(routerUrl)) {
System.setProperty("router.url", routerUrl);
}
}
if (StringUtils.isBlank(System.getProperty("eai.server.extractor"))) {
if (StringUtils.isNotBlank(eaiServerExtractor)) {
System.setProperty("eai.server.extractor", eaiServerExtractor);
}
}
this.isScalable = BooleanUtils.toBoolean(System.getProperty("scalable"));
if (this.isScalable) {
String uniqueInstName = instName;
if (StringUtils.isBlank(uniqueInstName)) {
uniqueInstName = RandomStringUtils.randomAlphabetic(20);
// }else if(uniqueInstName.length() > 20){
// int l = uniqueInstName.length();
// uniqueInstName = uniqueInstName.substring(l-14, l) + "-" + RandomStringUtils.randomAlphabetic(5);
}
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_KEY, uniqueInstName);
} else {
String serverName = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY);
if (serverName == null) {
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_KEY, instName);
}
}
String instPort = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_PORT);
if (instPort == null) {
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_PORT, this.instPort);
}
/**
* OpenJDK 11 이상 사용 시 -Dfile.encoding 프로퍼티로 ms949, euc-kr
* Charset.defaultCharset()의 값이 지정되지 않는 지정할 수 없는 버그가 존재한다
* 해당 버그를 Charset을 초기화 하여 우회하는 방법으로 처리한다.
*/
Field charset = null;
try {
charset = Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null, null);
} catch (Exception e) {
e.printStackTrace();
}
String serverName = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY);
if (serverName == null) {
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_KEY, 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 {
String datasourceName = System.getProperty(Keys.JDBC_NAME_KEY);
if(StringUtils.isEmpty(datasourceName)) {
System.setProperty(Keys.JDBC_NAME_KEY, this.jndiName);
}
ServiceLocator sl = ServiceLocator.getInstance();
sl.putDataSource(Keys.EAI_DATASOURCE, dataSource);
System.out.println("\n@@ " + Keys.EAI_DATASOURCE + " = " + dataSource);
} catch (ServiceLocatorException e1) {
System.out.println("ServiceLocator error");
}
System.out.println("\n@@ eLink Framework(JSON_TUNE) =====================================================");
System.out.println("@ eLink System Config Initializing -----------------------");
try {
if (StringUtils.isBlank(this.tableOwner)) {
System.out.println("==========================================================================");
System.out.println("# E R R O R : eLink 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 eLink System Mode : -D"
+ com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE + "=");
System.out.println("# eLink System Mode : [P/T/D/S]");
System.out.println("==========================================================================");
throw new Exception(" Rule Table Owner Not Configured ");
}
if (StringUtils.isBlank(this.systemMode)) {
System.out.println("==========================================================================");
System.out.println("# E R R O R : eLink 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 eLink System Mode : -D"
+ com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE + "=");
System.out.println("# eLink System Mode : [P/T/D/S]");
System.out.println("==========================================================================");
throw new Exception(" eLink System Mode Not Configured ");
}
System.out.println("==========================================================================");
System.out.println("# S U C C E S S : eLink System Configuration");
System.out.println("# Rule table Owner : " + this.tableOwner);
System.out.println("# Rule JDBC Name : " + com.eactive.eai.common.dao.Keys.EAI_DATASOURCE);
System.out.println("# eLink System Mode : " + this.systemMode);
System.out.println("# eLink System Mode : [P(Product)/T(Test)/D(Develop)/S(Staging)]");
System.out.println(
String.format("# %s : %s", ConfigKeys.USE_INTERNAL_TOPIC, ElinkConfig.isUseCacheTopic()));
System.out.println("==========================================================================");
System.out.println(
String.format("# %s : %s", SHUTDOWN_WAIT_SECS, shutdownWaitSecs) );
System.out.println(
String.format("# %s : %s", SHUTDOWN_WAIT_INTERVALMS, shutdownWaitIntervalMs) );
} catch (Exception e) {
throw new RuntimeException("eLink System Configuration Error - " + e.toString());
}
try {
PropManager.getInstance().start();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RFCEAICWB001"));
}
try {
Logger.doConfigure();
} catch (Exception e) {
System.out.println("Logger.doConfigure error");
}
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
/**
* 서버정보 입력
*/
if (this.isScalable) {
try {
EAIServerVO vo = new EAIServerVO();
vo.setAddress(InetAddress.getLocalHost().getHostAddress());
vo.setHostName(InetAddress.getLocalHost().getHostName());
vo.setName(System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY));
// scalable merge
// vo.setPort(System.getProperty("tomcat.port.http"));
vo.setPort(System.getProperty("inst.Port"));
vo.setRouterUrl(System.getProperty("router.url"));
System.out.println("----------------------------");
System.out.println(vo.toString());
System.out.println("----------------------------");
//addServer 에서 존재여부 체크해서 updateg함
eaiServerManager.addServer(vo);
logger.info("Success Insert Server Info!!!!");
System.out.println("Success Insert Server Info!!!!");
} catch (Exception e) {
logger.error("Refresh Server Info Error~~", e);
System.out.println("Refresh Server Info Error~~" + e.getMessage());
}
}
// print system config to logger
logger.warn("==========================================================================");
logger.warn("# S U C C E S S : eLink System Configuration");
logger.warn("# Rule table Owner : " + this.tableOwner);
logger.warn("# System Mode : " + this.systemMode);
logger.warn("# System Mode : [P(Product)/T(Test)/D(Develop)/S(Staging)]");
logger.warn("==========================================================================");
// init RMI Server
String pRmiPort = System.getProperty("eai.rmiport");
if (pRmiPort != null) {
this.rmiPort = pRmiPort;
}
String pRmiServicePort = System.getProperty("eai.rmiserviceport");
if (pRmiServicePort != null) {
this.rmiServicePort = pRmiServicePort;
}
try {
logger.warn("\n@@ eLink RMI Register Port : " + rmiPort + ", Service Port : " + rmiServicePort);
initRmiServer(Integer.parseInt(rmiPort), Integer.parseInt(rmiServicePort));
} catch (NumberFormatException e2) {
logger.error("eLink System RMI Server Configuration Error check port", e2);
throw new RuntimeException("eLink System RMI Server Configuration Error check port - " + e2.toString());
} catch (RemoteException e2) {
logger.error("eLink System RMI Server Start Error ", e2);
throw new RuntimeException("eLink System RMI Server Start Error - " + e2.toString());
}
// MonitoringContextFactory 기동
try {
Class clazz = Class.forName("com.eactive.eai.rms.client.context.MonitoringContextFactory");
Object factory = clazz.newInstance();
Method method = clazz.getMethod("create");
method.invoke(factory);
logger.warn("EMSCLIENT AGENT STARTED");
} catch (InvocationTargetException e) {
logger.error("EMSCLIENT AGENT CANNOT START - " + e.getTargetException().toString(), e.getTargetException());
e.getTargetException().printStackTrace();
} catch (Throwable e) {
logger.error("EMSCLIENT AGENT CANNOT START - " + e.toString(), e);
}
logger.warn("@ eLink Application Initializing -------------------------");
logger.warn(ElinkConfig.getConfigLog());
if (ElinkConfig.isUseAsyncLogging()) {
try {
logger.warn("START AsyncLoggingPoolManager");
AsyncLoggingPoolManager.getInstance().start();
logger.warn("SUCCESS AsyncLoggingPoolManager");
} catch (LifecycleException e) {
logger.error("START AsyncLoggingPoolManager failed.", e);
}
try {
logger.warn("START AsyncHttpLoggingPoolManager");
AsyncHttpLoggingPoolManager.getInstance().start();
logger.warn("SUCCESS AsyncHttpLoggingPoolManager");
} catch (LifecycleException e) {
logger.error("START AsyncHttpLoggingPoolManager failed.", e);
}
}
try {
lifecycleManager.start();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB002"));
}
ElinkStateManager.getInstance().started();
}
/**
* eLink FrameWork의 웹어플리케이션이 Undeploy될 때 초기화된 Manager들을 중지시킴
**/
public void destroy() {
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
if (logger.isWarn())
logger.warn("@ eLink Application Check current transactions.");
// Check current transaction & wait specific seconds until finish
ElinkStateManager.getInstance().stop();
if (logger.isWarn())
logger.warn("@ eLink Application destroying.");
logger.warn("stopRmiServer");
stopRmiServer();
// MonitoringContextFactory 중지
try {
Class clazz = Class.forName("com.eactive.eai.rms.client.context.MonitoringContextFactory");
Object factory = clazz.newInstance();
Method method = clazz.getMethod("stop");
method.invoke(factory);
logger.warn("EMSCLIENT AGENT STOPPED");
} catch (InvocationTargetException e) {
logger.error("EMSCLIENT AGENT CANNOT STOP - " + e.getTargetException().toString(), e.getTargetException());
e.getTargetException().printStackTrace();
} catch (Throwable e) {
logger.error("EMSCLIENT AGENT CANNOT STOP - " + e.toString(), e);
}
/**
* 서버정보 삭제
*/
if (this.isScalable) {
String instanceName = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY);
logger.info("Starting, Delete Server Info: " + instanceName);
System.out.println("Starting, Delete Server Info: " + instanceName);
if (StringUtils.isNotBlank(instanceName)) {
try {
eaiServerManager.removeServer(instanceName);
logger.info("Success Delete Server Info: " + instanceName);
System.out.println("Success Delete Server Info: " + instanceName);
} catch (Exception e) {
logger.error("Delete Server Info Error~~", e);
System.out.println("Delete Server Info Error~~" + instanceName + e.getMessage());
}
}
}
try {
lifecycleManager.stop();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB002"));
}
try {
PropManager.getInstance().stop();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB004"));
}
try {
SocketAdapterManager.getInstance().stop();
} catch (Exception e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB005"));
}
if (ElinkConfig.isUseAsyncLogging()) {
try {
logger.warn("STOP AsyncLoggingPoolManager");
AsyncLoggingPoolManager.getInstance().stop();
logger.warn("STOPPED AsyncLoggingPoolManager");
} catch (LifecycleException e) {
logger.error("STOP AsyncLoggingPoolManager failed.", e);
}
}
logger.warn("STOP Logger");
Logger.stop();
System.out.println("\n\n");
}
@Override
public void afterPropertiesSet() throws Exception {
init();
}
}
@@ -0,0 +1,229 @@
package com.eactive.eai.common.web;
//package com.eactive.eai.common.web;
//
//import com.eactive.eai.transformer.function.Function;
//import com.eactive.eai.transformer.function.FunctionDefinition;
//import com.eactive.eai.transformer.function.ParameterDefinition;
//import com.eactive.eai.transformer.layout.Types;
//import com.eactive.eai.common.exception.ExceptionUtil;
//import java.io.DataInputStream;
//import java.io.DataOutputStream;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.sql.Connection;
//import java.sql.PreparedStatement;
//import java.sql.Statement;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//import com.eactive.eai.transformer.tools.loader.AbstractExcelLoader;
//import com.eactive.eai.transformer.tools.loader.ExcelLoader;
//import com.eactive.eai.transformer.tools.util.ConstantUtil;
//import com.eactive.eai.transformer.tools.util.ExcelSheet;
//
//import com.eactive.eai.common.dao.Keys;
//
///**
//* 1. 기능 : 정형화된 EXCEL 문서를 통해 DB의 메시지 테이블에 insert하는 sql문을 생성한다.
//* 2. 처리 개요 : XLS메시지 테이블에 insert하는 sql문을 생성한다.
//*
//* 3. 주의사항
//*
//* @author :
//* @version : v 1.0.0
//* @see : AbstractExcelLoader.java
//* @since :
//* :
//*/
//
//public class ErrorCodeLoader extends AbstractExcelLoader
//{
// private static final int DATA_ROW_OFFSET = 4;
//
// private static final int COL_MSGKEY = 6;
// private static final int COL_MSGTXT = 7;
//
// private static final String QUERY_PREFIX = "INSERT INTO " + Keys.TABLE_OWNER + "TSMSGM001 (MSGKEY, MSGTXT) VALUES ";
//
// private static final String FILE_NAME = "insertQuery.sql";
//
//
// public ErrorCodeLoader() {
// super(ErrorCodeLoader.class.getName().substring(ErrorCodeLoader.class.getName().lastIndexOf('.') + 1));
// }
//
// /**
// * 1. 기능 : AbstractExcelLoader에 선언된 메소드 정의
// * 2. 처리 개요 : AbstractExcelLoader에 선언된 메소드 정의
// * 3. 주의사항
// *
// * @return Obejct
// * @exception
// **/
// public Object parseExcelSheet(ExcelSheet[] sheets)
// {
// return "";
// }
//
// /**
// * 1. 기능 : ExcelSheet를 파싱하여 sql화일 을 생성
// * 2. 처리 개요 : parseExcelSheet를 통해 ExcelSheet를 파싱하여 sql화일을 생성한다.
// * 3. 주의사항
// *
// * @return void
// * @exception
// **/
// public void loadExcelSheet(ExcelSheet[] sheets)
// {
//
// ExcelSheet sheet = sheets[0];
// String directory = null;
// try {
// directory = sheet.getCellString(2,3);
// } catch(Exception e) {
// e.printStackTrace();
// throw new RuntimeException("ErrorCodeLoader] loadExcelSheet>>"+e.getMessage());
// }
// System.out.println("directory : "+ directory);
//
// DataOutputStream out = getOutputFile(FILE_NAME, directory);
// StringBuffer sb = new StringBuffer();
//
// for (int currentRow = DATA_ROW_OFFSET; sheet.existRow(currentRow); ++currentRow) {
// try {
//
// String msgKey = sheet.getCellString(currentRow, COL_MSGKEY);
// String msgTxt = sheet.getCellString(currentRow, COL_MSGTXT);
//
// if (msgKey.trim().length() > 0 && msgTxt.trim().length() > 0) {
// sb.append(QUERY_PREFIX);
// sb.append("( " + quote(msgKey) + " , " + quote(msgTxt) + "); \n");
//
// System.out.println("Query : " + sb.toString());
//
//
// }
// else {
// break;
// }
//
// } catch (Exception e) {
// println("[ERROR] !!!!! " + e.getMessage() + " - ROW: " + currentRow);
// e.printStackTrace();
//
// }
// }
//
// if(out != null){
// try{
// out.write(sb.toString().getBytes());
// }catch (Exception e){
// e.printStackTrace();
// }
//
// }
// else {
// System.out.println("out is null");
// }
//
// }
//
// /**
// * 1. 기능 : 생성할 화일의 DataOutputStream을 생성
// * 2. 처리 개요 : ExcelSheet에 정의된 화일명과 위치를 통해 생성할 화일의 DataOutputStream을 생성하여 리턴한다.
// * 3. 주의사항
// *
// * @return DataOutputStream
// * @exception
// **/
//
// public DataOutputStream getOutputFile(String name, String dir) {
//
// String outFile = "";
// File out = new File(dir);
//
// if(!out.exists()){
// if(!out.mkdir())
// System.out.println(outFile+" Faild make directory");
// }
// outFile = dir+"/"+name;
//
// DataOutputStream outs = null;
//
// try {
// outs = new DataOutputStream( new FileOutputStream(outFile, false));
//
// if(outs != null)
// System.out.println("ErrorCodeLoader ] File Name - " + outFile +" created.");
// else
// System.out.println("ErrorCodeLoader ] File Name - " + outFile +" can't create.");
//
// } catch(Exception _ex) {
// _ex.printStackTrace();
// }
// return outs;
//
// }
//
// /**
// * 1. 기능 : 문자열을 받아서 단일 따옴표로 감싸 반환한다.
// * 2. 처리 개요 : 문자열을 받아서 단일 따옴표로 감싸 반환한다.
// * 이때 문자열 중 단일 따움표(')가 있으면 이중 단일 따옴표('')로 변환한다.
// * 3. 주의사항
// *
// * @param String str
// * @return String 단일 따옴표로 감싼 문자열
// **/
// private String quote(String str){
//
// StringBuffer sqlStr = new StringBuffer();
//
// if(str == null) {
// return "";
// }
// else {
// sqlStr.append("'");
// for(int i = 0; i < str.length(); i++) {
// if(str.charAt(i) == '\'') {
// sqlStr.append("''");
// }
// else {
// sqlStr.append(str.charAt(i));
// }
//
// }
// sqlStr.append("'");
// return sqlStr.toString();
// }
// }
//
// public void clearData(ExcelSheet[] sheets) {
// }
//
// public static void main(String[] argv) {
//
// InputStream in = null;
// ErrorCodeLoader loader = new ErrorCodeLoader();
//
// try {
//
//// in = ErrorCodeLoader.class.getClassLoader().getResourceAsStream(argv[0]);
// in = new DataInputStream(new FileInputStream(argv[0]));
// ExcelSheet[] sheets = ExcelSheet.getExcelSheets(in);
//
//// ExcelLoader loader = (ExcelLoader)Class.forName("ErrorCodeLoader.class").newInstance();
//
// loader.loadExcelSheet(sheets);
//
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// if (in != null) try { in.close(); } catch (Exception e) {};
// }
//
// }
//
//}
@@ -0,0 +1,45 @@
package com.eactive.eai.common.web;
import javax.servlet.*;
import java.io.IOException;
public class FrontFilter implements Filter {
private static int count;
private FilterConfig config;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
try {
increase();
chain.doFilter(req, res);
} catch (Exception e) {
throw new ServletException(e.getMessage());
} finally {
descrease();
}
}
public void init(FilterConfig config) throws ServletException {
this.config = config;
if (this.config != null) {
this.config.getFilterName();
}
}
private synchronized void increase() {
count++;
}
private synchronized void descrease() {
count--;
}
public static int count() {
return count;
}
}
@@ -0,0 +1,526 @@
package com.eactive.eai.common.web;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.rmi.RemoteException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.rmi.RmiServiceExporter;
import com.eactive.eai.adapter.socket2.config.SocketAdapterManager;
import com.eactive.eai.common.dao.Keys;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleManager;
import com.eactive.eai.common.logger.async.AsyncLoggingPoolManager;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.routing.rmi.GWRemoteProxy;
import com.eactive.eai.common.routing.rmi.GWRemoteProxyImpl;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.server.EAIServerVO;
import com.eactive.eai.common.state.ElinkStateManager;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.ServiceLocator;
import com.eactive.eai.common.util.ServiceLocatorException;
import com.eactive.eai.env.ConfigKeys;
import com.eactive.eai.env.ElinkConfig;
/**
* eLink-GW FrameWork이 초기화(Deploy)될 때 실행되어야 할 작업을 정의
*/
@SuppressWarnings("deprecation")
public class GWAppInitializer implements InitializingBean, DisposableBean {
GWRemoteProxy remoteProxy = new GWRemoteProxyImpl();
Class serviceInterface = GWRemoteProxy.class;
RmiServiceExporter rmiServiceExporter = new org.springframework.remoting.rmi.RmiServiceExporter();
@Autowired
private LifecycleManager lifecycleManager;
@Autowired
private EAIServerManager eaiServerManager;
private DataSource dataSource;
private String instName;
private String instPort;
private String tableOwner;
private String scalable;
private boolean isScalable;
private String routerUrl;
private String systemType; // eLink System Type
private String systemMode = "D"; // eLink-GW System Mode : [P/T/D/S]
private String eaiServerExtractor = "";
private String jndiName = "";
private int shutdownWaitSecs = 60;
private int shutdownWaitIntervalMs = 500;
private static final String SHUTDOWN_WAIT_SECS = "shutdown.wait.secs";
private static final String SHUTDOWN_WAIT_INTERVALMS = "shutdown.wait.intervalms";
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
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 setScalable(String scalable) {
this.scalable = scalable;
}
public String getScalable() {
return scalable;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public void setSystemMode(String systemMode) {
this.systemMode = systemMode;
}
private String rmiPort;
private String rmiServicePort;
public String getRmiPort() {
return rmiPort;
}
public void setRmiPort(String rmiPort) {
this.rmiPort = rmiPort;
}
public String getRmiServicePort() {
return rmiServicePort;
}
public void setRmiServicePort(String rmiServicePort) {
this.rmiServicePort = rmiServicePort;
}
public String getRouterUrl() {
return routerUrl;
}
public void setRouterUrl(String routerUrl) {
this.routerUrl = routerUrl;
}
public String getInstPort() {
return instPort;
}
public void setInstPort(String instPort) {
this.instPort = instPort;
}
public String getEaiServerExtractor() {
return eaiServerExtractor;
}
public void setEaiServerExtractor(String eaiServerExtractor) {
this.eaiServerExtractor = eaiServerExtractor;
}
public int getShutdownWaitSecs() {
return shutdownWaitSecs;
}
public void setShutdownWaitSecs(int shutdownWaitSecs) {
this.shutdownWaitSecs = shutdownWaitSecs;
}
public int getShutdownWaitIntervalMs() {
return shutdownWaitIntervalMs;
}
public void setShutdownWaitIntervalMs(int shutdownWaitIntervalMs) {
this.shutdownWaitIntervalMs = shutdownWaitIntervalMs;
}
@SuppressWarnings("deprecation")
private void initRmiServer(int registryPort, int servicePort) throws RemoteException {
rmiServiceExporter.setServiceName("RemoteProxy");
rmiServiceExporter.setService(remoteProxy);
rmiServiceExporter.setServiceInterface(serviceInterface);
rmiServiceExporter.setRegistryPort(registryPort);
rmiServiceExporter.setServicePort(servicePort);
rmiServiceExporter.setAlwaysCreateRegistry(true);
rmiServiceExporter.afterPropertiesSet();
}
private void stopRmiServer() {
if(rmiServiceExporter != null) {
try {
rmiServiceExporter.destroy();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* 기능 : eLink-GW FrameWork의 웹어플리케이션이 될 때 초기화 작업을 수행
**/
private void init() {
ElinkStateManager.getInstance().setWaitMaxMs(shutdownWaitSecs * 1000);
ElinkStateManager.getInstance().setSleepIntervalMs(shutdownWaitIntervalMs);
ElinkStateManager.getInstance().starting();
if (StringUtils.isBlank(System.getProperty(com.eactive.eai.common.server.Keys.EAI_SYSTEM_TYPE))) {
if (StringUtils.isNotBlank(systemType)) {
System.setProperty(com.eactive.eai.common.server.Keys.EAI_SYSTEM_TYPE, systemType);
}
}
if (StringUtils.isBlank(System.getProperty("scalable"))) {
if (StringUtils.isNotBlank(scalable)) {
System.setProperty("scalable", scalable);
}
}
if (StringUtils.isBlank(System.getProperty("router.url"))) {
if (StringUtils.isNotBlank(routerUrl)) {
System.setProperty("router.url", routerUrl);
}
}
this.isScalable = BooleanUtils.toBoolean(System.getProperty("scalable"));
if (this.isScalable) {
String uniqueInstName = instName;
if (StringUtils.isBlank(uniqueInstName)) {
uniqueInstName = RandomStringUtils.randomAlphabetic(20);
// }else if(uniqueInstName.length() > 20){
// int l = uniqueInstName.length();
// uniqueInstName = uniqueInstName.substring(l-14, l) + "-" + RandomStringUtils.randomAlphabetic(5);
}
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_KEY, uniqueInstName);
} else {
String serverName = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY);
if (serverName == null) {
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_KEY, instName);
}
}
String instPort = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_PORT);
if (instPort == null) {
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_PORT, this.instPort);
}
/**
* OpenJDK 11 이상 사용 시 -Dfile.encoding 프로퍼티로 ms949, euc-kr
* Charset.defaultCharset()의 값이 지정되지 않는 지정할 수 없는 버그가 존재한다
* 해당 버그를 Charset을 초기화 하여 우회하는 방법으로 처리한다.
*/
Field charset = null;
try {
charset = Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null, null);
} catch (Exception e) {
e.printStackTrace();
}
String serverName = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY);
if (serverName == null) {
System.setProperty(com.eactive.eai.common.server.Keys.SERVER_KEY, 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 {
String datasourceName = System.getProperty(Keys.JDBC_NAME_KEY);
if(StringUtils.isEmpty(datasourceName)) {
System.setProperty(Keys.JDBC_NAME_KEY, this.jndiName);
}
ServiceLocator sl = ServiceLocator.getInstance();
sl.putDataSource(Keys.EAI_DATASOURCE, dataSource);
System.out.println("\n@@ " + Keys.EAI_DATASOURCE + " = " + dataSource);
} catch (ServiceLocatorException e1) {
System.out.println("ServiceLocator error");
}
System.out.println("@ eLink-GW System Config Initializing -----------------------");
try {
if (StringUtils.isBlank(this.tableOwner)) {
System.out.println("==========================================================================");
System.out.println("# E R R O R : eLink 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 eLink System Mode : -D"
+ com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE + "=");
System.out.println("# eLink System Mode : [P/T/D/S]");
System.out.println("==========================================================================");
throw new Exception(" Rule Table Owner Not Configured ");
}
if (StringUtils.isBlank(this.systemMode)) {
System.out.println("==========================================================================");
System.out.println("# E R R O R : eLink 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 eLink System Mode : -D"
+ com.eactive.eai.common.server.Keys.EAI_SYSTEMMODE + "=");
System.out.println("# eLink System Mode : [P/T/D/S]");
System.out.println("==========================================================================");
throw new Exception(" eLink System Mode Not Configured ");
}
System.out.println("==========================================================================");
System.out.println("# S U C C E S S : eLink System Configuration");
System.out.println("# Rule table Owner : " + this.tableOwner);
System.out.println("# Rule JDBC Name : " + com.eactive.eai.common.dao.Keys.EAI_DATASOURCE);
System.out.println("# eLink System Mode : " + this.systemMode);
System.out.println("# eLink System Mode : [P(Product)/T(Test)/D(Develop)/S(Staging)]");
System.out.println(
String.format("# %s : %s", ConfigKeys.USE_INTERNAL_TOPIC, ElinkConfig.isUseCacheTopic()));
System.out.println("==========================================================================");
System.out.println(
String.format("# %s : %s", SHUTDOWN_WAIT_SECS, shutdownWaitSecs) );
System.out.println(
String.format("# %s : %s", SHUTDOWN_WAIT_INTERVALMS, shutdownWaitIntervalMs) );
} catch (Exception e) {
throw new RuntimeException("eLink-GW System Configuration Error - " + e.toString());
}
try {
PropManager.getInstance().start();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RFCEAICWB001"));
}
try {
Logger.doConfigure();
} catch (Exception e) {
System.out.println("Logger.doConfigure error");
}
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
/**
* 서버정보 입력
*/
if (this.isScalable) {
try {
EAIServerVO vo = new EAIServerVO();
vo.setAddress(InetAddress.getLocalHost().getHostAddress());
vo.setHostName(InetAddress.getLocalHost().getHostName());
vo.setName(System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY));
// scalable merge
// vo.setPort(System.getProperty("tomcat.port.http"));
vo.setPort(System.getProperty("inst.Port"));
vo.setRouterUrl(System.getProperty("router.url"));
String failoverSvr = getFailoverSvr(System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY));
if (failoverSvr != null) {
vo.setFailoverSvr(failoverSvr);
}
System.out.println("----------------------------");
System.out.println(vo.toString());
System.out.println("----------------------------");
//addServer 에서 존재여부 체크해서 updateg함
eaiServerManager.addServer(vo);
logger.info("Success Insert Server Info!!!!");
System.out.println("Success Insert Server Info!!!!");
} catch (Exception e) {
logger.error("Refresh Server Info Error~~", e);
System.out.println("Refresh Server Info Error~~"+ e.getMessage());
}
}
// print system config to logger
logger.warn("==========================================================================");
logger.warn("# S U C C E S S : eLink-GW System Configuration");
logger.warn("# Rule table Owner : " + this.tableOwner);
logger.warn("# System Mode : " + this.systemMode);
logger.warn("# eLink-GW System Mode : [P(Product)/T(Test)/D(Develop)/S(Staging)]");
logger.warn("==========================================================================");
// init RMI Server
String pRmiPort = System.getProperty("eai.rmiport");
if (pRmiPort != null) {
this.rmiPort = pRmiPort;
}
String pRmiServicePort = System.getProperty("eai.rmiserviceport");
if (pRmiServicePort != null) {
this.rmiServicePort = pRmiServicePort;
}
try {
logger.warn("\n@@ eLink-GW RMI Register Port : " + rmiPort + ", Service Port : " + rmiServicePort);
initRmiServer(Integer.parseInt(rmiPort), Integer.parseInt(rmiServicePort));
} catch (NumberFormatException e2) {
logger.error("eLink-GW System RMI Server Configuration Error check port", e2);
throw new RuntimeException("eLink-GW System RMI Server Configuration Error check port - " + e2.toString());
} catch (RemoteException e2) {
logger.error("eLink-GW System RMI Server Start Error ", e2);
throw new RuntimeException("eLink-GW System RMI Server Start Error - " + e2.toString());
}
// MonitoringContextFactory 기동
try {
Class clazz = Class.forName("com.eactive.eai.rms.client.context.MonitoringContextFactory");
Object factory = clazz.newInstance();
Method method = clazz.getMethod("create");
method.invoke(factory);
logger.warn("EMSCLIENT AGENT STARTED");
} catch (InvocationTargetException e) {
logger.error("EMSCLIENT AGENT CANNOT START - " + e.getTargetException().toString(), e.getTargetException());
e.getTargetException().printStackTrace();
} catch (Throwable e) {
logger.error("EMSCLIENT AGENT CANNOT START - " + e.toString(), e);
}
logger.warn("@ eLink-GW Application Initializing -------------------------");
logger.warn(ElinkConfig.getConfigLog());
try {
lifecycleManager.start();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB002"));
}
ElinkStateManager.getInstance().started();
}
/**
* eLink-GW FrameWork의 웹어플리케이션이 Undeploy될 때 초기화된 Manager들을 중지시킴
**/
public void destroy() {
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
if (logger.isWarn())
logger.warn("@ eLink Application destroying.");
// Check current transaction & wait specific seconds until finish
ElinkStateManager.getInstance().stop();
logger.warn("stopRmiServer");
stopRmiServer();
// MonitoringContextFactory 중지
try {
Class clazz = Class.forName("com.eactive.eai.rms.client.context.MonitoringContextFactory");
Object factory = clazz.newInstance();
Method method = clazz.getMethod("stop");
method.invoke(factory);
logger.warn("EMSCLIENT AGENT STOPPED");
} catch (InvocationTargetException e) {
logger.error("EMSCLIENT AGENT CANNOT STOP - " + e.getTargetException().toString(), e.getTargetException());
e.getTargetException().printStackTrace();
} catch (Throwable e) {
logger.error("EMSCLIENT AGENT CANNOT STOP - " + e.toString(), e);
}
// /**
// * 서버정보 삭제 GW 일경우 서버정보 삭제 안함- statefulset 형태로 fgw-0, fgw-1 의 host 명 으로 됨
// */
// if (this.isScalable) {
// String instanceName = System.getProperty(Keys.SERVER_KEY);
// logger.info("Starting, Delete Server Info: " + instanceName);
// System.out.println("Starting, Delete Server Info: " + instanceName);
//
// if (StringUtils.isNotBlank(instanceName)) {
// try {
// eaiServerManager.removeServer(instanceName);
//
// logger.info("Success Delete Server Info: " + instanceName);
// System.out.println("Success Delete Server Info: " + instanceName);
// } catch (Exception e) {
// logger.error("Delete Server Info Error~~", e);
// System.out.println("Delete Server Info Error~~" + instanceName + e.getMessage());
// }
// }
// }
try {
lifecycleManager.stop();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB002"));
}
try {
PropManager.getInstance().stop();
} catch (LifecycleException e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB004"));
}
try {
SocketAdapterManager.getInstance().stop();
} catch (Exception e) {
throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAICWB005"));
}
System.out.println("\n\n");
}
@Override
public void afterPropertiesSet() throws Exception {
init();
}
private String getFailoverSvr(String instName) {
Matcher matcher = Pattern.compile("([\\S]*)-([0-9]{1,2})$").matcher(instName);
String failover = "";
while (matcher.find()) {
String name = matcher.group(1).trim();
String index = matcher.group(2).trim();
int size = index.length();
int num = Integer.parseInt(index);
if (num %2 == 1) {
num = num - 1;
}else {
num = num + 1;
}
failover = name + "-" + StringUtils.leftPad(Integer.toString(num), size, '0');
}
return failover;
}
}
@@ -0,0 +1,232 @@
package com.eactive.eai.common.web;
//package com.eactive.eai.common.web;
//
//import com.eactive.eai.transformer.function.Function;
//import com.eactive.eai.transformer.function.FunctionDefinition;
//import com.eactive.eai.transformer.function.ParameterDefinition;
//import com.eactive.eai.transformer.layout.Types;
//import com.eactive.eai.common.exception.ExceptionUtil;
//import java.io.DataInputStream;
//import java.io.DataOutputStream;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.sql.Connection;
//import java.sql.PreparedStatement;
//import java.sql.Statement;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//import com.eactive.eai.transformer.tools.loader.AbstractExcelLoader;
//import com.eactive.eai.transformer.tools.loader.ExcelLoader;
//import com.eactive.eai.transformer.tools.util.ConstantUtil;
//import com.eactive.eai.transformer.tools.util.ExcelSheet;
//
///**
//* 1. 기능 : 정형화된 EXCEL 문서를 통해 관리자화면의 help 풍선도움말을 만들기 위한 XML화일을 생성
//* 2. 처리 개요 : 입력받은 xml화일을 파싱하여 정형화된 XML화일을 생성한다.
//*
//* 3. 주의사항
//*
//* @author :
//* @version : v 1.0.0
//* @see : AbstractExcelLoader.java
//* @since :
//* :
//*/
//
//public class HelpLoader extends AbstractExcelLoader
//{
// private static final int DATA_ROW_OFFSET = 7;
//
// private static final int COL_ID = 1;
// private static final int COL_TYPE = 2;
// private static final int COL_DESC = 3;
//
// private static final String PAGE_TITLE_TYPE = "pageTitle";
// private static final String LABEL_TYPE = "Label";
//
//
// public HelpLoader() {
// super(HelpLoader.class.getName().substring(HelpLoader.class.getName().lastIndexOf('.') + 1));
// }
//
// /**
// * 1. 기능 : ExcelSheet를 파싱하여 ArrayList를 생성
// * 2. 처리 개요 : ExcelSheet를 파싱하여 ArrayList에 HelpVO를 생성해서 리턴한다.
// * 3. 주의사항
// *
// * @return ArrayList HelpVO를 가진 ArrayList
// * @exception
// **/
// public Object parseExcelSheet(ExcelSheet[] sheets)
// {
// ExcelSheet sheet = sheets[0];
//
// ArrayList helpList = new ArrayList();
//
// for (int currentRow = DATA_ROW_OFFSET; sheet.existRow(currentRow); currentRow++) {
// try {
// HelpVO vo = new HelpVO();
//
// String type = sheet.getCellString(currentRow, COL_TYPE);
// String id = sheet.getCellString(currentRow, COL_ID);
// String desc = sheet.getCellString(currentRow, COL_DESC);
//
// if (id.trim().length() > 0) {
// vo.setId(id);
// vo.setDescription(desc);
// vo.setType(type);
//
// helpList.add(vo);
//
// }
// else {
// break;
// }
//
// } catch (Exception e) {
// println("[ERROR] !!!!! " + e.getMessage() + " - ROW: " + currentRow);
// e.printStackTrace();
//
// }
// }
//
// return helpList;
// }
//
// /**
// * 1. 기능 : ExcelSheet를 파싱하여 XML을 생성
// * 2. 처리 개요 : parseExcelSheet를 통해 ExcelSheet를 파싱하여 XML 화일을 생성한다.
// * 3. 주의사항
// *
// * @return void
// * @exception
// **/
// public void loadExcelSheet(ExcelSheet[] sheets)
// {
// List helpList = (List)parseExcelSheet(sheets);
// int helpSize = helpList.size();
//
// println("Load할 Help 수: " + helpSize);
//
// String name = null;
// try {
// name = sheets[0].getCellString(2, 1);
// } catch(Exception e) {
// e.printStackTrace();
// throw new RuntimeException("HelpLoader] loadExcelSheet>> "+e.getMessage());
// }
// String directory = null;
// try {
// directory = sheets[0].getCellString(3,1);
// } catch(Exception e) {
// e.printStackTrace();
// throw new RuntimeException("HelpLoader] loadExcelSheet>> "+e.getMessage());
// }
//
// DataOutputStream out = getOutputFile(name, directory);
// StringBuffer sb = new StringBuffer();
//
// try{
// sb.append("<?xml version=\"1.0\" encoding=\"euc-kr\"?>\n");
// sb.append("\n<help>");
//
// // </PageTitle>");
// HelpVO vo = new HelpVO();
// for(int i=0; i < helpSize; i++){
// vo = (HelpVO)helpList.get(i);
//
// if(this.PAGE_TITLE_TYPE.equalsIgnoreCase(vo.getType())){
// sb.append( "\n\t<PageTitle id=\"");
// sb.append(vo.getId()+"\">");
// sb.append(vo.getDescription()+"</PageTitle>");
// }
// else{
// sb.append("\n\t<label id=\"");
// sb.append(vo.getId()+"\">");
// sb.append(vo.getDescription()+"</label>");
// }
//
// }
// sb.append("\n</help>");
// System.out.println(sb.toString());
// if(out != null)
// out.write(sb.toString().getBytes());
// else
// System.out.println("out is null");
//
// } catch (Exception e) {
//
// e.printStackTrace();
// } finally {
//
// }
// }
//
// /**
// * 1. 기능 : 생성할 XML화일의 DataOutputStream을 생성
// * 2. 처리 개요 : ExcelSheet에 정의된 화일명과 위치를 통해 생성할 XML화일의 DataOutputStream을 생성하여 리턴한다.
// * 3. 주의사항
// *
// * @return DataOutputStream
// * @exception
// **/
//
// public DataOutputStream getOutputFile(String name, String dir) {
//
// String outFile = "";
// File out = new File(dir);
//
// if(!out.exists()){
// if(!out.mkdir())
// System.out.println(outFile+" Faild make directory");
// }
// outFile = dir+"/"+name;
//
// DataOutputStream outs = null;
//
// try {
// outs = new DataOutputStream( new FileOutputStream(outFile, false));
//
// if(outs != null)
// System.out.println("HelpLoader ] File Name - " + outFile +" created.");
// else
// System.out.println("HelpLoader ] File Name - " + outFile +" can't create.");
//
// } catch(Exception _ex) {
// _ex.printStackTrace();
// }
// return outs;
//
// }
//
// public void clearData(ExcelSheet[] sheets) {
// }
//
// public static void main(String[] argv) {
//
// InputStream in = null;
// HelpLoader loader = new HelpLoader();
//
// try {
//
//// in = HelpLoader.class.getClassLoader().getResourceAsStream(argv[0]);
// in = new DataInputStream(new FileInputStream(argv[0]));
// ExcelSheet[] sheets = ExcelSheet.getExcelSheets(in);
//
//// ExcelLoader loader = (ExcelLoader)Class.forName("HelpLoader.class").newInstance();
//
// loader.loadExcelSheet(sheets);
//
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// if (in != null) try { in.close(); } catch (Exception e) {};
// }
//
// }
//
//}
@@ -0,0 +1,43 @@
package com.eactive.eai.common.web;
/**
* 1. 기능 : 관리자 화면의 Help 풍선도움말을 표현한 Java Value Object
*
* @author :
* @version : v 1.0.0
* @see :
* @since : :
*/
public class HelpVO {
private String id;
private String description;
private String type;
public HelpVO() {
}
public void setId(String id) {
this.id = id;
}
public void setDescription(String des) {
this.description = des;
}
public String getId() {
return this.id;
}
public String getDescription() {
return this.description;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
@@ -0,0 +1,12 @@
package com.eactive.eai.common.web;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;
public class MakeSelectDataTEI extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[] { new VariableInfo(data.getAttributeString("id"), data.getAttributeString("type"),
true, VariableInfo.NESTED), };
}
}
@@ -0,0 +1,145 @@
package com.eactive.eai.common.web;
import com.eactive.eai.common.dao.Keys;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 1. 기능 : 관리자화면에서 select Tag를 생성해주는 Custom Tag Class
* 2. 처리 개요 : 필드 추출 Rule 정보테이블에 대한 Create, Read, Update, Delete 를 처리한다.
* <kbeai:MakeSelectData dataSource="" table="" value="" label="" id="" />
*
* @author :
* @version : v 1.0.0
* @see :
* @since : :
*/
public class MakeSelectDataTag extends BodyTagSupport {
private String dataSource;
private String table;
private String where;
private String value;
private String label;
// private String type;
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
}
public void setTable(String table) {
this.table = Keys.TABLE_OWNER + table;
}
public void setWhere(String where) {
this.where = where;
}
public void setValue(String value) {
this.value = value;
}
public void setLabel(String label) {
this.label = label;
}
// public void setType(String type) {
// this.type = type;
// }
public int doStartTag() throws JspTagException {
if (dataSource == null) {
return SKIP_BODY;
}
try {
pageContext.setAttribute(id, selectFromTable(), PageContext.PAGE_SCOPE);
} catch (Exception e) {
throw new JspTagException(e.toString());
}
return EVAL_BODY_TAG;
}
public int doEndTag() throws JspTagException {
try {
if (bodyContent != null)
bodyContent.writeOut(bodyContent.getEnclosingWriter());
} catch (java.io.IOException e) {
throw new JspTagException("IO Error: " + e.toString());
}
return EVAL_PAGE;
}
/**
* 1. 기능 : 입력받은 Tag Value를 통해 html select Tag를 생성하기 위한 KEY, VALUE를 조회한다. 2. 처리
* 개요 : Query를 생성하여 설정된 DataSource를 통해 key, value를 조회한다. 3. 주의사항
*
* @return HashMap label, value 쌍을 가진 HashMap
* @exception Excepiton SQLException
**/
public Map selectFromTable() throws Exception {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = getConnection();
StringBuffer query = new StringBuffer();
query.append("select ").append(label).append(", ").append(value).append(" ").append(" from ").append(table)
.append(" ");
if (where != null) {
query.append("where ").append(where).append(" ");
}
query.append("order by ").append(label);
// System.out.println("query>> "+query.toString());
stmt = con.prepareStatement(query.toString());
rs = stmt.executeQuery();
Map map = new LinkedHashMap();
while (rs.next()) {
map.put(rs.getString(1), rs.getString(2));
}
return map;
} catch (SQLException e) {
throw e;
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (stmt != null)
stmt.close();
} catch (Exception e) {
}
try {
if (con != null)
con.close();
} catch (Exception e) {
}
}
}
public Connection getConnection() throws Exception {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(dataSource);
return ds.getConnection();
} catch (Exception e) {
throw e;
}
}
}
@@ -0,0 +1,79 @@
package com.eactive.eai.common.web;
import java.io.Serializable;
import java.util.Vector;
/**
* 1. 기능 : 관리자 화면에서 Page List를 구성하기위한 정보를 저장
* 2. 처리 개요 : 관리자 화면에서 Page List를 구성하기위한 정보를 저장
*
* @author :
* @version : v 1.0.0
* @see :
* @since : :
*/
public class PageInfo implements Serializable {
private int page;
private int rowsPerPage;
private Vector whereItem;
private Vector orderItem;
/** 한페이지에 보여줄 라인 카운트 */
public static int ROWS_PER_PAGE = 10;
public void setPage(int page) {
this.page = page;
}
public int getPage() {
return this.page;
}
public void setRowPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerPage;
}
public int getRowPerPage() {
return this.rowsPerPage;
}
public void setWhereItem(Vector whereItem) {
this.whereItem = whereItem;
}
public Vector getWhereItem() {
return this.whereItem;
}
public void setOrderItem(Vector orderItem) {
this.orderItem = orderItem;
}
public Vector getOrderItem() {
return this.orderItem;
}
/**
* view page의 start row를 반환하는 method
*
* @return view page의 start row
*/
public int startrow() {
page = page < 1 ? 1 : page;
if (this.rowsPerPage == 0)
rowsPerPage = ROWS_PER_PAGE;
return (page - 1) * rowsPerPage + 1;
}
/**
* view page의 end row를 반환하는 method
*
* @return view page의 end row
*/
public int endrow() {
page = page < 1 ? 1 : page;
if (this.rowsPerPage == 0)
rowsPerPage = ROWS_PER_PAGE;
return (page - 1) * rowsPerPage + rowsPerPage;
}
}
@@ -0,0 +1,317 @@
package com.eactive.eai.common.web;
/*
* @@(#)PageListTag.java
* @@author Jeon HongSeong
* @@version 1.0
* Copyright (c) 1998-2001 InfoTops Co., Ltd. All Rights Reserved.
*/
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
/**
* 1. 기능 : 관리자 화면에서 페이지 리스트를 만들어 준다.
* 2. 처리 개요 : 관리자 화면에서 Page List를 구성하기위한 정보를 저장
* totalCount 전체 레코드 갯수
* viewPage 현재 페이지 번호
* rowPerPage 한 페이지당 레코드 건수
* pageListCount 한 페이지 리스트당 페이지 갯수
* viewPageColor 현재 페이지 색깔
* javaScript 페이지 이동 자바스크립트 함수 / 페이지 이동 href
* first, prev, next, last 버튼 (처음, 이전 블럭, 다음 블럭, 마지막)
* |◀ ◀ [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] ▶ ▶|
* 3. 주의사항
*
* @author :
* @version : v 1.0.0
* @see :
* @since :
* :
*/
public class PageListTag extends TagSupport
{
private int totalCount;
private int viewPage;
private int rowPerPage;
private int pageListCount;
private String javaScript;
private String viewPageColor;
private String first;
private String prev;
private String next;
private String last;
// private final static int DEFAULT_ROW_PER_PAGE = 10;
// private final static int DEFAULT_PAGE_LIST_COUNT = 10;
// private final static String DEFAULT_JAVA_SCRIPT = "gotoPage";
// private final static String DEFAULT_VIEW_PAGE_COLOR = "#FF6300";
private final static String DEFAULT_FIRST_BUTTON = "|◀";
private final static String DEFAULT_PREV_BUTTON = "";
private final static String DEFAULT_NEXT_BUTTON = "";
private final static String DEFAULT_LAST_BUTTON = "▶|";
//mendatory : total row count
public void setTotalCount(int totalCount)
{
this.totalCount = totalCount;
}
//view page number
public void setViewPage(int viewPage)
{
this.viewPage = (viewPage < 1) ? 1 : viewPage;
}
//row per page
public void setRowPerPage(int rowPerPage)
{
this.rowPerPage = rowPerPage;
}
//page list count
public void setPageListCount(int pageListCount)
{
this.pageListCount = pageListCount;
}
//java script function name
public void setJavaScript(String javaScript)
{
this.javaScript = javaScript;
}
//view page color
public void setViewPageColor(String viewPageColor)
{
this.viewPageColor = viewPageColor;
}
//first button
public void setFirst(String first)
{
this.first = first;
}
//previous button
public void setPrev(String prev)
{
this.prev = prev;
}
//next button
public void setNext(String next)
{
this.next = next;
}
//last button
public void setLast(String last)
{
this.last = last;
}
private String getPageList(
int rowCount, //전체 레코드 갯수
int viewPage, //현재 페이지 번호
int rowPerPage, //한 페이지당 레코드 갯수
int pageListCount, //한 페이지당 하단 페이지 갯수
String javascript_name, //자바스크립트
String current_page_color, //현재 페이지 색깔
String first_button,
String prev_button,
String next_button,
String last_button
)
{
int intTotPage = 0; //전체 페이지 갯수
int intStartPage = 0; //페이지 리스트를 시작할 페이지 번호
int intEndPage = 0; //페이지 리스트가 끝나는 페이지 번호
//페이지 리스트를 시작할 페이지를 계산한다.
intStartPage = (int) Math.ceil((viewPage - 1) / pageListCount);
intStartPage = (intStartPage * pageListCount) + 1;
if (intStartPage % pageListCount == 0) intStartPage = intStartPage - pageListCount + 1 ;
//전체 페이지 갯수를 계산한다.
// intTotPage = ( (rowCount % rowPerPage) > 0 ) ? 1 : 0;
// intTotPage = (int) Math.ceil(rowCount / rowPerPage) + intTotPage;
intTotPage = getTotalPage(rowCount, rowPerPage);
//페이지 리스트가 끝나는 페이지를 계산한다.
intEndPage = (intTotPage >= (pageListCount + intStartPage))
? intStartPage + pageListCount - 1
: intStartPage + (intTotPage - intStartPage);
StringBuffer sb = new StringBuffer();
//첫번째 페이지(리스트)로 이동 : |◀
//<a href="javascript:gotoPage(1);">|◀</a>
//if ( viewPage > 1 )
//if ( intStartPage > (pageListCount * 2) )
//System.out.println( intStartPage+"====="+pageListCount+"****************");
if ( intStartPage > pageListCount )
{
sb.append("<a href=\"javascript:");
sb.append(javascript_name);
sb.append("(1);\">");
sb.append( first_button );
sb.append("</a>");
sb.append("\n");
}
else
{
sb.append( first_button );
sb.append("\n");
}
//이전 페이지 리스트로 이동 : ◀
//<a href="javascript:gotoPage(11);">◀</a> --16 - 5 = 11
if (intStartPage > pageListCount)
{
sb.append("<a href=\"javascript:");
sb.append(javascript_name).append("(");
sb.append(intStartPage - pageListCount);
sb.append(");\">");
sb.append( prev_button );
sb.append("</a>");
sb.append("</a>");
sb.append("\n");
sb.append("&nbsp;");
sb.append("\n");
}
else
{
sb.append( prev_button );
sb.append("\n");
sb.append("&nbsp;");
sb.append("\n");
}
//해당 페이지로 이동 : [16][17][18][19][20] -- 현재페이지 = 17
for (int i=intStartPage; i<=intEndPage; i++)
{
if (viewPage == i)
{
sb.append("<font size=\"2\" color=\"");
sb.append(current_page_color);
sb.append("\"><b>[");
sb.append(i);
sb.append("]</b></font>");
sb.append("\n");
}
else
{
sb.append("<a href=\"javascript:");
sb.append(javascript_name);
sb.append("(");
sb.append(i);
sb.append(");\">[");
sb.append(i);
sb.append("]</a>");
sb.append("\n");
}
}
//다음 페이지 리스트로 이동 : ▶
//<a href="javascript:gotoPage(21);">▶</a> --16 + 5 = 21
if (intTotPage > intEndPage )
{
sb.append("&nbsp;");
sb.append("\n");
sb.append("<a href=\"javascript:");
sb.append(javascript_name);
sb.append("(");
sb.append(intStartPage + pageListCount);
sb.append(");\">");
sb.append( next_button );
sb.append("</a>");
//sb.append("</a>&nbsp;");
sb.append("\n");
}
else
{
sb.append("&nbsp;");
sb.append("\n");
sb.append( next_button );
//sb.append("&nbsp;");
sb.append("\n");
}
//마지막 페이지 리스트로 이동 : ▶|
//<a href="javascript:gotoPage(41);">▶|</a> --intTotPage
//if (intTotPage >= ( intStartPage + (pageListCount * 2) ))
if (intTotPage > intEndPage )
{
sb.append("<a href=\"javascript:");
sb.append(javascript_name);
sb.append("(");
sb.append(intTotPage);
sb.append(");\">");
sb.append(last_button);
sb.append("</a>");
//sb.append("\n");
}
else
{
sb.append(last_button);
}
return sb.toString();
}
public int doStartTag()
throws JspTagException
{
try {
if (totalCount <=0 )
return SKIP_BODY;
JspWriter out = pageContext.getOut();
out.println(
getPageList(
totalCount,
(viewPage <= 0)? 1 : viewPage,
(rowPerPage > 0) ? rowPerPage : 10,
(pageListCount > 0) ? pageListCount : 5,
javaScript,
(viewPageColor != null && viewPageColor.length() > 0)? viewPageColor : "#FF9933",
(first != null && first.length() > 0) ? first : DEFAULT_FIRST_BUTTON,
(prev != null && prev.length() > 0) ? prev : DEFAULT_PREV_BUTTON,
(next != null && next.length() > 0) ? next : DEFAULT_NEXT_BUTTON,
(last != null && last.length() > 0) ? last : DEFAULT_LAST_BUTTON
)
);
return SKIP_BODY;
}
catch (IOException e)
{
throw new JspTagException( "IOException:" +e.toString() );
}
catch (Exception e)
{
throw new JspTagException( "Exception:" +e.toString() );
}
}
private int getTotalPage(int rowCount, int rowPerPage)
{
return ( (int)(Math.ceil(rowCount/rowPerPage)) + ( (rowCount%rowPerPage)>0?1:0) );
}
}