init
This commit is contained in:
@@ -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 );
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 수준의 송수신전문 및 에러 메인처리내용의 모든수준의 로깅을 수행한다.
|
||||
|
||||
}
|
||||
@@ -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 <code>INTERNAL_ERROR</code>.
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
|
||||
}
|
||||
@@ -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)");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
||||
package com.eactive.eai.adapter.socket.outbound;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.service.SocketLogManager;
|
||||
import com.eactive.eai.adapter.socket.service.SocketService;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class OutboundSocketClient implements SocketService {
|
||||
|
||||
//파일로거
|
||||
private static Logger logger = SocketLogManager.getInstance().getLogger();
|
||||
|
||||
private boolean active;
|
||||
|
||||
private int currentState;
|
||||
|
||||
private long firstActivity;
|
||||
private long lastActivity;
|
||||
|
||||
private Socket socket;
|
||||
|
||||
private String remoteIPAddress;
|
||||
private String port;
|
||||
|
||||
|
||||
public OutboundSocketClient(Socket socket) {
|
||||
this.active = true;
|
||||
|
||||
this.currentState = CommonLib.PROCESSING_PROTOCOL;
|
||||
|
||||
this.firstActivity = System.currentTimeMillis();
|
||||
this.lastActivity = System.currentTimeMillis();
|
||||
|
||||
this.socket = socket;
|
||||
|
||||
this.remoteIPAddress = socket.getInetAddress().getHostAddress();
|
||||
this.port = socket.getPort() + "";
|
||||
|
||||
}
|
||||
|
||||
public String getPort() {
|
||||
return this.port;
|
||||
}
|
||||
|
||||
public String getRemoteIPAddress() {
|
||||
return this.remoteIPAddress;
|
||||
}
|
||||
|
||||
public ConfigurationContext getContext() {
|
||||
return null;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<SelectionKey> 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<SelectionKey> 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;
|
||||
// }
|
||||
//}
|
||||
@@ -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<SocketService> 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<SocketService>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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<String, LinkedList<SocketService>> stateTable;
|
||||
private Logger logger;
|
||||
private long lastActivity;
|
||||
|
||||
public ConnectionManager(HashMap<String, LinkedList<SocketService>> 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<SocketService> groupList = (LinkedList<SocketService>) 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<SocketService> groupList = (LinkedList<SocketService>) 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<String> iter = stateTable.keySet().iterator(); iter.hasNext();) {
|
||||
Object key = iter.next();
|
||||
sb.append("\n ▣ " + key + " : ");
|
||||
for(Iterator<SocketService> iter2 = (stateTable.get(key)).iterator(); iter2.hasNext();) {
|
||||
sb.append("\n ● " + iter2.next() + " : ");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -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<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
|
||||
if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutsideVO outside = null;
|
||||
if (i==osd_array.size()) {
|
||||
String errMsg = "[IOboundServer] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + 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 = 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");
|
||||
String recvdMsg = new String(incomingMessage.array());
|
||||
if ( adapter.getContext().isUsePollMsg() ){
|
||||
recvdMsg = new String(incomingMessage.array()) + new String(pollingMessage.array());
|
||||
}
|
||||
batchMsgDoc.getBatchMsg().getBody().setRecvedMsg(recvdMsg);
|
||||
|
||||
String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
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 + "]");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(outside.getBlkSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.getPacketSize()); // 20060411 추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(context.getHostName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(context.getPortNumber()+"");
|
||||
//----------------------------------------------------------------
|
||||
logger.info("**** USER ID > [" + 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutsideVO outside = null;
|
||||
if (i==osd_array.size()) {
|
||||
String errMsg = "[InboundClient] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + 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(rcvFlowRuleCode);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(adapter.getBatchSystemConnCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleCode(rcvFlowRuleCode);
|
||||
RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(rcvFlowRuleCode);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo!=null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02");
|
||||
String recvdMsg = new String(incomingMessage.array());
|
||||
if ( adapter.getContext().isUsePollMsg() ){
|
||||
recvdMsg = new String(incomingMessage.array()) + new String(pollingMessage.array());
|
||||
}
|
||||
batchMsgDoc.getBatchMsg().getBody().setRecvedMsg(recvdMsg);
|
||||
|
||||
|
||||
// // 응답송신기능의 추가를 위해 일부 기능 수정 함.
|
||||
// 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<fileList.length; i1++) {
|
||||
// if ( fileList[i1].isFile()) {
|
||||
// strFileName = fileList[i1].getName();
|
||||
// lnFileSize = fileList[i1].length();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFlowCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleDesc(RuleInfoManager.getInstance().getRuleInfo(outside.getSendRuleCode()).getDesc());
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileSize(lnFileSize);
|
||||
// }
|
||||
// else {
|
||||
// //응답 수신 디렉토리 설정
|
||||
// String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
// if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
// strPathName = strPathName + '/';
|
||||
// }
|
||||
// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
//
|
||||
// sb.append(btVO.getProcessName()).append("_").append(btVO.getProcessCode());
|
||||
// sb.append("/");
|
||||
// sb.append(btVO.getOrganName()).append("_").append(btVO.getOrganCode());
|
||||
// strPathName = strPathName + sb.toString();
|
||||
// logger.debug("[응답수신] PATH NAME = [" + strPathName + "]");
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// // <<< 응답수신 디렉토리 설정
|
||||
// }
|
||||
|
||||
//응답 수신 디렉토리 설정
|
||||
String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
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 + "]");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// <<< 응답수신 디렉토리 설정
|
||||
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(outside.getBlkSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.getPacketSize()); // 20060411 추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(context.getHostName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(context.getPortNumber()+"");
|
||||
//----------------------------------------------------------------
|
||||
logger.info("**** USER ID > [" + 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<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutsideVO outside = null;
|
||||
if (i==osd_array.size()) {
|
||||
String errMsg = "[InboundClient] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + 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);
|
||||
}
|
||||
|
||||
//해당 작업을 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(outside.getBlkSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.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("[InboundClient] ■ BatchRunningJobManager 등록완료 ");
|
||||
String strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID();
|
||||
|
||||
// BatchRunningJobManager 에 Running Job 등록
|
||||
logger.info("InboundClient : BatchRunningJobManager 에 응답송수신 작업 등록......");
|
||||
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc);
|
||||
|
||||
try {
|
||||
// TimeoutException 기관로거 설정
|
||||
Logger.addInstLog(batchMsgDoc);
|
||||
//===================================================
|
||||
logger.info("InboundClient : FlowController JPD 호출 시작......");
|
||||
ByteBuffer tmpBuf = null;
|
||||
try {
|
||||
tmpBuf = ByteBuffer.allocate(4096);
|
||||
processReadMessage( tmpBuf.array(), 500);
|
||||
} catch (Exception e) {
|
||||
if(tmpBuf != null)
|
||||
logger.warn( e.getMessage()+ new String(tmpBuf.array()), e );
|
||||
else // 20250910 npe
|
||||
logger.warn( e.getMessage(), e );
|
||||
}
|
||||
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 호출결과 EEND 소켓 연결 종료" );
|
||||
waitRecoverConnection();
|
||||
}
|
||||
//===================================================
|
||||
|
||||
} finally {
|
||||
// BatchRunningJobManager 에서 Running Job 제거
|
||||
logger.info("InboundClient : BatchRunningJobManager 에서 요구답송수신 작업 제거......");
|
||||
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
} catch ( Exception e){
|
||||
logger.error(e.getMessage(), e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean byteCompare( byte[] arr1, byte[]arr2){
|
||||
for ( int inx = 0; inx < Math.min(arr1.length,arr2.length); inx++)
|
||||
if ( arr1[inx] != arr2[inx])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.batch.doc.BatchDoc;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class InboundControl implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private String adapterGroupName;
|
||||
private String adapterName;
|
||||
private boolean ready;
|
||||
private String responseType;
|
||||
private long timeout;
|
||||
private Throwable lastError;
|
||||
private BatchDoc batchMsgDoc;
|
||||
|
||||
public InboundControl(String adapterGroupName, String adapterName) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
this.adapterName = adapterName;
|
||||
this.lastError = null;
|
||||
this.ready = false;
|
||||
}
|
||||
|
||||
public InboundControl(String adapterGroupName, String adapterName, long timeout) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
this.adapterName = adapterName;
|
||||
this.lastError = null;
|
||||
this.ready = false;
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
public BatchDoc getBatchMsgDoc() {
|
||||
return batchMsgDoc;
|
||||
}
|
||||
public void setBatchMsgDoc(BatchDoc batchMsgDoc) {
|
||||
this.batchMsgDoc = batchMsgDoc;
|
||||
}
|
||||
public void initBatchMsgDocStage() {
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setSubLayerCode("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseType("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setSndMsgCode("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setRcvMsgCode("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime("");
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 responseType.
|
||||
*/
|
||||
public String getResponseType() {
|
||||
return responseType;
|
||||
}
|
||||
/**
|
||||
* @param responseType The responseType to set.
|
||||
*/
|
||||
public void setResponseType(String responseType) {
|
||||
this.responseType = responseType;
|
||||
}
|
||||
|
||||
public boolean isSyncMode() {
|
||||
return this.responseType.equals( ConfigurationContext.SYNC_MODE );
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 request.
|
||||
*/
|
||||
public byte[] getRequest() {
|
||||
return new byte[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param request The request to set.
|
||||
*/
|
||||
public void setRequest(byte[] request) throws Exception {
|
||||
|
||||
}
|
||||
/**
|
||||
* @return Returns the response.
|
||||
*/
|
||||
public byte[] getResponse() {
|
||||
return new byte[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param response The response to set.
|
||||
*/
|
||||
public void setResponse(byte[] response) {
|
||||
|
||||
}
|
||||
|
||||
public byte[] request() throws Exception {
|
||||
logger.debug("[ELINK]################ InboundControl.request() 호출됨.");
|
||||
long srtTime = 0;
|
||||
srtTime = System.currentTimeMillis();
|
||||
|
||||
// Session pool에서 사용할 session을 얻어온다.
|
||||
// SessionManager는 SocketAdapterManager 에서 생성하여 사용함.
|
||||
SessionManager mgr = SessionManager.getInstance();
|
||||
SessionService service = null;
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
long waitTime = 0;
|
||||
|
||||
while ( true ) {
|
||||
service = mgr.getSession( this.adapterGroupName );
|
||||
if ( service != null ) break;
|
||||
|
||||
waitTime = System.currentTimeMillis() - start;
|
||||
if ( waitTime >= 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;
|
||||
}
|
||||
}
|
||||
@@ -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<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
/*
|
||||
logger.info("OSD CODE > [" + 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<fileList.length; i1++) {
|
||||
// if ( fileList[i1].isFile()) {
|
||||
// strFileName = fileList[i1].getName();
|
||||
// lnFileSize = fileList[i1].length();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFlowCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleDesc(RuleInfoManager.getInstance().getRuleInfo(outside.getSendRuleCode()).getDesc());
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileSize(lnFileSize);
|
||||
// }
|
||||
// else {
|
||||
// //응답 수신 디렉토리 설정
|
||||
// String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
// 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 + "]");
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// // <<< 응답수신 디렉토리 설정
|
||||
// }
|
||||
|
||||
//응답 수신 디렉토리 설정
|
||||
String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
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 + "]");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// <<< 응답수신 디렉토리 설정
|
||||
|
||||
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(outside.getBlkSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.getPacketSize()); // 20060411 추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(remoteIPAddress);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(remotePort);
|
||||
//----------------------------------------------------------------
|
||||
logger.info("**** USER ID > [" + 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<SelectionKey> 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;
|
||||
// }
|
||||
}
|
||||
@@ -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<SelectionKey> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<SocketService> connectionList;
|
||||
|
||||
public OutboundChannel(long sessionTimeout) {
|
||||
connectionList = new Vector<SocketService>();
|
||||
}
|
||||
|
||||
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<SocketService> iter = connectionList.iterator(); iter.hasNext();) {
|
||||
Object key = iter.next();
|
||||
sb.append("\n ▣ " + key);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -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<String,OutboundChannel> pool = new HashMap<String,OutboundChannel>() ;
|
||||
|
||||
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<String> 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();
|
||||
}
|
||||
}
|
||||
@@ -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 '<SYNC>|<ASYN>'
|
||||
// * 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;
|
||||
// }
|
||||
//}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
// }
|
||||
//}
|
||||
@@ -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<SelectionKey> 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<SelectionKey> 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;
|
||||
// }
|
||||
//}
|
||||
@@ -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<SocketService> errorTable;
|
||||
private Logger logger = SocketLogManager.getInstance().getLogger();
|
||||
|
||||
public RecoveryManager(LinkedList<SocketService> 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<SocketService> iter = errorTable.iterator(); iter.hasNext();) {
|
||||
sb.append("\n ▣ " + iter.next() + " : ");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -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<SessionService> 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<SessionService>();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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<String, SessionChannel> pool = new HashMap<String, SessionChannel>();
|
||||
// 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<String> iter = pool.keySet().iterator(); iter.hasNext();) {
|
||||
Object key = iter.next();
|
||||
sb.append("\n ▣ " + key + " : " + pool.get(key));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<SocketService> threadPool;
|
||||
private boolean active;
|
||||
private Selector selector;
|
||||
private ServerSocketChannel serverSocketChannel;
|
||||
private ServerSocket serverSocket;
|
||||
private Logger logger;
|
||||
private HashMap<String, Integer> 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<SocketService>();
|
||||
logger = (Logger) SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName() );
|
||||
ipTable = new HashMap<String, Integer>();
|
||||
}
|
||||
|
||||
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<SelectionKey> 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<SelectionKey> 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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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;
|
||||
// }
|
||||
//}
|
||||
@@ -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<SelectionKey> 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;
|
||||
// }
|
||||
//}
|
||||
Reference in New Issue
Block a user