From 8976f34e7aab8683abcc1996f49318ff625fd229 Mon Sep 17 00:00:00 2001 From: dsjang Date: Thu, 18 Jul 2024 06:16:12 +0900 Subject: [PATCH] =?UTF-8?q?Report=20=EA=B8=B0=EB=8A=A5=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=EC=A4=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../client/config/RunnerConfiguration.java | 35 +- .../munjaon/client/config/ServerConfig.java | 8 - .../mariadb/service/MariaDBService.java | 8 +- .../com/munjaon/client/model/MunjaonMsg.java | 4 +- .../client/server/config/ServerConfig.java | 13 + .../munjaon/client/server/packet/Bind.java | 100 +++++ .../client/server/packet/CommonMessage.java | 183 ++++++++ .../munjaon/client/server/packet/Header.java | 110 +++++ .../client/server/packet/LinkCheck.java | 31 ++ .../munjaon/client/server/packet/Packet.java | 46 ++ .../munjaon/client/server/packet/Report.java | 142 ++++++ .../client/server/packet/SmsMessage.java | 55 +++ .../server/service/CollectClientService.java | 186 ++++++++ .../client/server/service/PropertyLoader.java | 2 +- .../server/service/ReportClientService.java | 140 ++++++ .../munjaon/client/server/service/Server.java | 193 ++++++++ .../client/server/service/Service.java | 148 ++++++ .../com/munjaon/client/util/ByteUtil.java | 423 ++++++++++++++++++ .../com/munjaon/client/util/CommonUtil.java | 359 +++++++++++++++ .../com/munjaon/client/util/FileUtil.java | 37 ++ .../java/com/munjaon/client/util/LogUtil.java | 95 ++++ .../com/munjaon/client/util/ServiceUtil.java | 32 ++ .../com/munjaon/client/util/StringUtil.java | 167 +++++++ .../java/com/munjaon/client/util/XmlUtil.java | 125 ++++++ .../resources/sqlmap/mariadb/mariadb_sql.xml | 13 +- 25 files changed, 2626 insertions(+), 29 deletions(-) create mode 100644 src/main/java/com/munjaon/client/server/config/ServerConfig.java create mode 100644 src/main/java/com/munjaon/client/server/packet/Bind.java create mode 100644 src/main/java/com/munjaon/client/server/packet/CommonMessage.java create mode 100644 src/main/java/com/munjaon/client/server/packet/Header.java create mode 100644 src/main/java/com/munjaon/client/server/packet/LinkCheck.java create mode 100644 src/main/java/com/munjaon/client/server/packet/Packet.java create mode 100644 src/main/java/com/munjaon/client/server/packet/Report.java create mode 100644 src/main/java/com/munjaon/client/server/packet/SmsMessage.java create mode 100644 src/main/java/com/munjaon/client/server/service/CollectClientService.java create mode 100644 src/main/java/com/munjaon/client/server/service/ReportClientService.java create mode 100644 src/main/java/com/munjaon/client/server/service/Server.java create mode 100644 src/main/java/com/munjaon/client/server/service/Service.java create mode 100644 src/main/java/com/munjaon/client/util/ByteUtil.java create mode 100644 src/main/java/com/munjaon/client/util/CommonUtil.java create mode 100644 src/main/java/com/munjaon/client/util/FileUtil.java create mode 100644 src/main/java/com/munjaon/client/util/LogUtil.java create mode 100644 src/main/java/com/munjaon/client/util/ServiceUtil.java create mode 100644 src/main/java/com/munjaon/client/util/StringUtil.java create mode 100644 src/main/java/com/munjaon/client/util/XmlUtil.java diff --git a/src/main/java/com/munjaon/client/config/RunnerConfiguration.java b/src/main/java/com/munjaon/client/config/RunnerConfiguration.java index 1ac6d0a..6140ee0 100644 --- a/src/main/java/com/munjaon/client/config/RunnerConfiguration.java +++ b/src/main/java/com/munjaon/client/config/RunnerConfiguration.java @@ -1,5 +1,6 @@ package com.munjaon.client.config; +import com.munjaon.client.server.service.CollectClientService; import com.munjaon.client.server.service.PropertyLoader; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -17,27 +18,35 @@ public class RunnerConfiguration { @Bean @Order(1) - public CommandLineRunner getRunnerBeanForProperty() { + public CommandLineRunner getRunnerBeanForProperty() throws ConfigurationException { System.setProperty("PROPS", serverConfig.getServerProperyFile()); System.setProperty("ROOTPATH", serverConfig.getServerRootPath()); + System.setProperty("DBMS", serverConfig.getString("DB.DBMS")); PropertyLoader.load(); - try { - String[] array = serverConfig.getStringArray("test.list"); - if (array != null && array.length > 0) { - for (String s : array) { - System.out.println("List : " + s); - } - } - } catch (ConfigurationException e) { - throw new RuntimeException(e); - } +// try { +// String[] array = serverConfig.getStringArray("test.list"); +// if (array != null && array.length > 0) { +// for (String s : array) { +// System.out.println("List : " + s); +// } +// } +// } catch (ConfigurationException e) { +// throw new RuntimeException(e); +// } return args -> System.out.println("Runner Bean #1 : " + serverConfig.getServerProperyFile()); } @Bean @Order(2) - public CommandLineRunner getRunnerBeanForSmsQueue() { - + public CommandLineRunner getRunnerBeanForSms() { + try { + String serviceName = "SMS"; + String serviceType = serverConfig.getString(serviceName + ".SERVICE_TYPE"); + CollectClientService collectClientService = new CollectClientService(serviceName, serviceType); + collectClientService.start(); + } catch (Exception e) { + throw new RuntimeException(e); + } return args -> System.out.println("Runner Bean #2"); } } diff --git a/src/main/java/com/munjaon/client/config/ServerConfig.java b/src/main/java/com/munjaon/client/config/ServerConfig.java index 3e366b9..48cad49 100644 --- a/src/main/java/com/munjaon/client/config/ServerConfig.java +++ b/src/main/java/com/munjaon/client/config/ServerConfig.java @@ -34,14 +34,6 @@ public class ServerConfig { void init() throws ConfigurationException { // this.serverRootPath = System.getProperty("SERVICE_HOME"); this.serverProperyFile = serverRootPath + File.separator + "config" + File.separator + "munjaonAgent.conf"; - log.debug("serverProperyFile : {}", serverProperyFile); - log.debug("serverProperyFile : {}", serverProperyFile); - log.debug("serverProperyFile : {}", serverProperyFile); - System.out.println(serverProperyFile); - System.out.println(serverProperyFile); - System.out.println(serverProperyFile); - System.out.println(serverProperyFile); - System.out.println(serverProperyFile); builder = new ReloadingFileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(new Parameters().fileBased().setFile(new File(serverProperyFile))); builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, new EventListener() { diff --git a/src/main/java/com/munjaon/client/mariadb/service/MariaDBService.java b/src/main/java/com/munjaon/client/mariadb/service/MariaDBService.java index ea881b4..4ee0ea8 100644 --- a/src/main/java/com/munjaon/client/mariadb/service/MariaDBService.java +++ b/src/main/java/com/munjaon/client/mariadb/service/MariaDBService.java @@ -17,9 +17,11 @@ public class MariaDBService { public boolean checkTableExists() { boolean isExist = false; try { - mariaDBMapper.checkTableForMessage(); - mariaDBMapper.checkTableForLog(); - isExist = true; + int msgCount = mariaDBMapper.checkTableForMessage(); + int logCount = mariaDBMapper.checkTableForLog(); + if (msgCount == 1 && logCount == 1) { + isExist = true; + } } catch (Exception e) { log.error("Check table exists error : {}", e); } diff --git a/src/main/java/com/munjaon/client/model/MunjaonMsg.java b/src/main/java/com/munjaon/client/model/MunjaonMsg.java index 062bb98..d0619d3 100644 --- a/src/main/java/com/munjaon/client/model/MunjaonMsg.java +++ b/src/main/java/com/munjaon/client/model/MunjaonMsg.java @@ -11,16 +11,18 @@ public class MunjaonMsg { private String msgId; private String msgType; private String sendStatus; + private String reserveDate; private String requestDate; private String recvPhone; private String sendPhone; private String subject; private String message; private String telecom; + private String agentCode; private String filename01; private String filename02; private String filename03; private String deliverDate; - private String sentDate; + private String sendDate; private String reportDate; } diff --git a/src/main/java/com/munjaon/client/server/config/ServerConfig.java b/src/main/java/com/munjaon/client/server/config/ServerConfig.java new file mode 100644 index 0000000..3fb6320 --- /dev/null +++ b/src/main/java/com/munjaon/client/server/config/ServerConfig.java @@ -0,0 +1,13 @@ +package com.munjaon.client.server.config; + +public final class ServerConfig { + /* 서버 타임아웃 체크 시간 */ + public static final int CYCLE_SOCKET_TIMEOUT = 3000; + /* 서버 연결후 로그인 만료 시간 */ + public static final int LIMIT_BIND_TIMEOUT = 5000; + /* Session Check 만료 시간 */ + public static final int LIMIT_LINK_CHECK_TIMEOUT = 35000; + + /* 서버 프로퍼티 reload interval 시간 */ + public static final Long INTERVAL_PROPERTY_RELOAD_TIME = 3000L; +} diff --git a/src/main/java/com/munjaon/client/server/packet/Bind.java b/src/main/java/com/munjaon/client/server/packet/Bind.java new file mode 100644 index 0000000..6ac4b2e --- /dev/null +++ b/src/main/java/com/munjaon/client/server/packet/Bind.java @@ -0,0 +1,100 @@ +package com.munjaon.client.server.packet; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +public final class Bind { + public static final int BIND_BODY_LENGTH = 41; + + public static final int BIND_ID_LENGTH = 20; + public static final int BIND_ID_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + public static final int BIND_PWD_LENGTH = 20; + public static final int BIND_PWD_POSITION = BIND_ID_POSITION + BIND_ID_LENGTH; + public static final int BIND_ENCRYPTION_LENGTH = 1; + public static final int BIND_ENCRYPTION_POSITION = BIND_PWD_POSITION + BIND_PWD_LENGTH; + + public static final int BIND_ACK_BODY_LENGTH = 2; + public static final int BIND_ACK_RESULT_CODE_LENGTH = 2; + public static final int BIND_ACK_RESULT_CODE_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + + public static final String ENCRYPTION = "0"; + + public static ByteBuffer makeBindBuffer(String id, String pwd) { + ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + BIND_BODY_LENGTH); + Packet.setDefaultByte(buffer); + Header.putHeader(buffer, Header.COMMAND_BIND, BIND_BODY_LENGTH); + /* ID */ + if (id != null) { + buffer.put(BIND_ID_POSITION, id.getBytes()); + } + /* PWD */ + if (pwd != null) { + buffer.put(BIND_PWD_POSITION, pwd.getBytes()); + } + /* ENCRYPTION */ + buffer.put(BIND_ENCRYPTION_POSITION, ENCRYPTION.getBytes()); +// buffer.limit(buffer.capacity()); + + return buffer; + } + + public static ByteBuffer makeBindAckBuffer(String resultCode) { + ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + BIND_ACK_BODY_LENGTH); + Packet.setDefaultByte(buffer); + Header.putHeader(buffer, Header.COMMAND_BIND_ACK, BIND_ACK_BODY_LENGTH); + /* resultCode */ + if (resultCode != null) { + buffer.put(BIND_ACK_RESULT_CODE_POSITION, resultCode.getBytes()); + } + + return buffer; + } + + public static String getBindId(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(BIND_ID_POSITION); + byte[] destArray = new byte[BIND_ID_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static String getBindPwd(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(BIND_PWD_POSITION); + byte[] destArray = new byte[BIND_PWD_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static String getBindEncryption(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(BIND_ENCRYPTION_POSITION); + byte[] destArray = new byte[BIND_ENCRYPTION_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static String getBindAckResultCode(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(BIND_ACK_RESULT_CODE_POSITION); + byte[] destArray = new byte[BIND_ACK_RESULT_CODE_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } +} diff --git a/src/main/java/com/munjaon/client/server/packet/CommonMessage.java b/src/main/java/com/munjaon/client/server/packet/CommonMessage.java new file mode 100644 index 0000000..beebf3b --- /dev/null +++ b/src/main/java/com/munjaon/client/server/packet/CommonMessage.java @@ -0,0 +1,183 @@ +package com.munjaon.client.server.packet; + +import com.munjaon.client.util.CommonUtil; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +public final class CommonMessage { + /* DELIVER */ + /* MSG_ID */ + public static final int DELIVER_MESSAGE_ID_LENGTH = 20; + public static final int DELIVER_MESSAGE_ID_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + /* SENDER */ + public static final int DELIVER_SENDER_LENGTH = 15; + public static final int DELIVER_SENDER_POSITION = DELIVER_MESSAGE_ID_POSITION + DELIVER_MESSAGE_ID_LENGTH; + /* RECEIVER */ + public static final int DELIVER_RECEIVER_LENGTH = 15; + public static final int DELIVER_RECEIVER_POSITION = DELIVER_SENDER_POSITION + DELIVER_SENDER_LENGTH; + /* RESERVE_TIME */ + public static final int DELIVER_RESERVE_TIME_LENGTH = 14; + public static final int DELIVER_RESERVE_TIME_POSITION = DELIVER_RECEIVER_POSITION + DELIVER_RECEIVER_LENGTH; + /* REQUEST_TIME */ + public static final int DELIVER_REQUEST_TIME_LENGTH = 14; + public static final int DELIVER_REQUEST_TIME_POSITION = DELIVER_RESERVE_TIME_POSITION + DELIVER_RESERVE_TIME_LENGTH; + /* MSG_TYPE */ + public static final int DELIVER_MSG_TYPE_LENGTH = 1; + public static final int DELIVER_MSG_TYPE_POSITION = DELIVER_REQUEST_TIME_POSITION + DELIVER_REQUEST_TIME_LENGTH; + + /* DELIVER_ACK */ + /* MSG_ID */ + public static final int DELIVER_ACK_MESSAGE_ID_LENGTH = 20; + public static final int DELIVER_ACK_MESSAGE_ID_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + /* RESULT */ + public static final int DELIVER_ACK_RESULT_LENGTH = 1; + public static final int DELIVER_ACK_RESULT_POSITION = DELIVER_ACK_MESSAGE_ID_POSITION + DELIVER_ACK_MESSAGE_ID_LENGTH; + + public static void putMessageIdForDeliver(ByteBuffer buffer, String messageId) { + if (buffer == null || messageId == null) { + return; + } + buffer.put(DELIVER_MESSAGE_ID_POSITION, messageId.getBytes()); + } + public static String getMessageIdForDeliver(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_MESSAGE_ID_POSITION); + byte[] destArray = new byte[DELIVER_MESSAGE_ID_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putSenderForDeliver(ByteBuffer buffer, String sender) { + if (buffer == null || sender == null) { + return; + } + sender = CommonUtil.cutString(CommonUtil.doNumber(sender), DELIVER_SENDER_LENGTH); + buffer.put(DELIVER_SENDER_POSITION, sender.getBytes()); + } + public static String getSenderForDeliver(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_SENDER_POSITION); + byte[] destArray = new byte[DELIVER_SENDER_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putReceiverForDeliver(ByteBuffer buffer, String receiver) { + if (buffer == null || receiver == null) { + return; + } + receiver = CommonUtil.cutString(CommonUtil.doNumber(receiver), DELIVER_RECEIVER_LENGTH); + buffer.put(DELIVER_RECEIVER_POSITION, receiver.getBytes()); + } + public static String getReceiverForDeliver(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_RECEIVER_POSITION); + byte[] destArray = new byte[DELIVER_RECEIVER_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putReserveTimeForDeliver(ByteBuffer buffer, String reserveTime) { + if (buffer == null || reserveTime == null) { + return; + } + buffer.put(DELIVER_RESERVE_TIME_POSITION, reserveTime.getBytes()); + } + public static String getReserveTimeForDeliver(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_RESERVE_TIME_POSITION); + byte[] destArray = new byte[DELIVER_RESERVE_TIME_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putRequestTimeForDeliver(ByteBuffer buffer, String requestTime) { + if (buffer == null || requestTime == null) { + return; + } + buffer.put(DELIVER_REQUEST_TIME_POSITION, requestTime.getBytes()); + } + public static String getRequestTimeForDeliver(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_REQUEST_TIME_POSITION); + byte[] destArray = new byte[DELIVER_REQUEST_TIME_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putMsgTypeForDeliver(ByteBuffer buffer, String msgType) { + if (buffer == null || msgType == null) { + return; + } + buffer.put(DELIVER_MSG_TYPE_POSITION, msgType.getBytes()); + } + public static String getMsgTypeForDeliver(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_MSG_TYPE_POSITION); + byte[] destArray = new byte[DELIVER_MSG_TYPE_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + + public static void putMessageIdForDeliverAck(ByteBuffer buffer, String messageId) { + if (buffer == null || messageId == null) { + return; + } + buffer.put(DELIVER_ACK_MESSAGE_ID_POSITION, messageId.getBytes()); + } + public static String getMessageIdForDeliverAck(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_ACK_MESSAGE_ID_POSITION); + byte[] destArray = new byte[DELIVER_ACK_MESSAGE_ID_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putResultForDeliverAck(ByteBuffer buffer, String result) { + if (buffer == null || result == null) { + return; + } + buffer.put(DELIVER_ACK_RESULT_POSITION, result.getBytes()); + } + public static String getResultForDeliverAck(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_ACK_RESULT_POSITION); + byte[] destArray = new byte[DELIVER_ACK_RESULT_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } +} diff --git a/src/main/java/com/munjaon/client/server/packet/Header.java b/src/main/java/com/munjaon/client/server/packet/Header.java new file mode 100644 index 0000000..9f24dca --- /dev/null +++ b/src/main/java/com/munjaon/client/server/packet/Header.java @@ -0,0 +1,110 @@ +package com.munjaon.client.server.packet; + +import com.munjaon.client.util.ByteUtil; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +public final class Header { + public static final int HEADER_LENGTH = 10; + + public static final String VERSION = "ITN10"; + public static final int VERSION_LENGTH = 5; + public static final int VERSION_POSITION = 0; + + public static final int COMMAND_LENGTH = 1; + public static final int COMMAND_POSITION = VERSION_POSITION + VERSION_LENGTH; + + public static final String COMMAND_BIND = "1"; + public static final String COMMAND_BIND_ACK = "2"; + public static final String COMMAND_DELIVER = "3"; + public static final String COMMAND_DELIVER_ACK = "4"; + public static final String COMMAND_REPORT = "5"; + public static final String COMMAND_REPORT_ACK = "6"; + public static final String COMMAND_LINK_CHECK = "7"; + public static final String COMMAND_LINK_CHECK_ACK = "8"; + + public static final int BODY_LENGTH = 4; + public static final int BODY_POSITION = COMMAND_POSITION + COMMAND_LENGTH; + + public static final int BODY_BIND_LENGTH = 41; + public static final int BODY_BIND_ACK_LENGTH = 2; + public static final int BODY_LINK_CHECK_LENGTH = 3; + public static final int BODY_LINK_CHECK_ACK_LENGTH = 3; + public static final int BODY_DELIVER_SMS_LENGTH = 239; + public static final int BODY_DELIVER_SMS_ACK_LENGTH = 21; + public static final int BODY_DELIVER_LMS_LENGTH = 2091; + public static final int BODY_DELIVER_LMS_ACK_LENGTH = 21; + public static final int BODY_DELIVER_MMS_LENGTH = 2091; + public static final int BODY_DELIVER_MMS_ACK_LENGTH = 21; + public static final int BODY_REPORT_LENGTH = 58; + public static final int BODY_REPORT_ACK_LENGTH = 1; + + public static void putVersion(final ByteBuffer buffer) { + if (buffer == null) { + return; + } + buffer.put(VERSION_POSITION, VERSION.getBytes()); + } + public static String getVersion(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(VERSION_POSITION); + byte[] destArray = new byte[VERSION_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putCommand(final ByteBuffer buffer, String command) { + if (buffer == null) { + return; + } + buffer.put(COMMAND_POSITION, command.getBytes()); + } + public static String getCommand(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(COMMAND_POSITION); + byte[] destArray = new byte[COMMAND_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putBodyLength(final ByteBuffer buffer, int bodyLength) { + putBodyLength(buffer, Integer.toString(bodyLength)); + } + public static String getBodyLength(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(BODY_POSITION); + byte[] destArray = new byte[BODY_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void putBodyLength(final ByteBuffer buffer, String bodyLength) { + if (buffer == null) { + return; + } + System.out.println(ByteUtil.byteToHex(bodyLength.getBytes(), true)); + + buffer.put(BODY_POSITION, bodyLength.getBytes()); + } + public static void putHeader(final ByteBuffer buffer, String command, int bodyLength) { + putHeader(buffer, command, Integer.toString(bodyLength)); + } + public static void putHeader(final ByteBuffer buffer, String command, String bodyLength) { + putVersion(buffer); + putCommand(buffer, command); + putBodyLength(buffer, bodyLength); + } +} diff --git a/src/main/java/com/munjaon/client/server/packet/LinkCheck.java b/src/main/java/com/munjaon/client/server/packet/LinkCheck.java new file mode 100644 index 0000000..4fb9105 --- /dev/null +++ b/src/main/java/com/munjaon/client/server/packet/LinkCheck.java @@ -0,0 +1,31 @@ +package com.munjaon.client.server.packet; + +import java.nio.ByteBuffer; + +public final class LinkCheck { + public static final int LINK_CHECK_BODY_LENGTH = 3; + public static final int LINK_CHECK_BODY_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + public static final int LINK_CHECK_ACK_BODY_LENGTH = 3; + public static final int LINK_CHECK_ACK_BODY_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + + public static String LINK_CHECK_VALUE = "100"; + public static String LINK_CHECK_ACK_VALUE = "100"; + + public static ByteBuffer makeLinkCheckBuffer() { + ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + LINK_CHECK_BODY_LENGTH); + Packet.setDefaultByte(buffer); + Header.putHeader(buffer, Header.COMMAND_LINK_CHECK, LINK_CHECK_BODY_LENGTH); + buffer.put(LINK_CHECK_BODY_POSITION, LINK_CHECK_VALUE.getBytes()); + + return buffer; + } + + public static ByteBuffer makeLinkCheckAckBuffer() { + ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + LINK_CHECK_ACK_BODY_LENGTH); + Packet.setDefaultByte(buffer); + Header.putHeader(buffer, Header.COMMAND_LINK_CHECK, LINK_CHECK_ACK_BODY_LENGTH); + buffer.put(LINK_CHECK_ACK_BODY_POSITION, LINK_CHECK_ACK_VALUE.getBytes()); + + return buffer; + } +} diff --git a/src/main/java/com/munjaon/client/server/packet/Packet.java b/src/main/java/com/munjaon/client/server/packet/Packet.java new file mode 100644 index 0000000..0d9fb53 --- /dev/null +++ b/src/main/java/com/munjaon/client/server/packet/Packet.java @@ -0,0 +1,46 @@ +package com.munjaon.client.server.packet; + +import java.nio.ByteBuffer; + +public final class Packet { + public static final byte SET_DEFAULT_BYTE = (byte) 0x00; + public static final long LINK_CHECK_CYCLE = 3000L; +// public static final long LINK_CHECK_CYCLE = 30000L; + + public static void setDefaultByte(ByteBuffer buffer) { + if (buffer == null) { + return; + } +// buffer.clear(); + for (int i = 0; i < buffer.capacity(); i++) { + buffer.put(i, SET_DEFAULT_BYTE); + } +// buffer.position(0); + } + + public static String getString(byte[] srcArray) { + if (srcArray == null) { + return null; + } + int size = 0; + for (int i = 0, len = srcArray.length; i < len; i++) { + if (srcArray[i] == SET_DEFAULT_BYTE) { + continue; + } + size++; + } + byte[] destArray = null; + if (size > 0) { + destArray = new byte[size]; + int index = 0; + for (int i = 0, len = srcArray.length; i < len; i++) { + if (srcArray[i] == SET_DEFAULT_BYTE) { + continue; + } + destArray[index++] = srcArray[i]; + } + } + + return destArray == null ? null : new String(destArray); + } +} diff --git a/src/main/java/com/munjaon/client/server/packet/Report.java b/src/main/java/com/munjaon/client/server/packet/Report.java new file mode 100644 index 0000000..70c8b95 --- /dev/null +++ b/src/main/java/com/munjaon/client/server/packet/Report.java @@ -0,0 +1,142 @@ +package com.munjaon.client.server.packet; + +import com.munjaon.client.model.MunjaonMsg; + +import java.nio.ByteBuffer; + +public final class Report { + public static final int REPORT_BODY_LENGTH = 44; + + public static final int REPORT_MSG_ID_LENGTH = 20; + public static final int REPORT_MSG_ID_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + public static final int REPORT_AGENT_CODE_LENGTH = 2; + public static final int REPORT_AGENT_CODE_POSITION = REPORT_MSG_ID_POSITION + REPORT_MSG_ID_LENGTH; + public static final int REPORT_SEND_TIME_LENGTH = 14; + public static final int REPORT_SEND_TIME_POSITION = REPORT_AGENT_CODE_POSITION + REPORT_AGENT_CODE_LENGTH; + public static final int REPORT_TELECOM_LENGTH = 3; + public static final int REPORT_TELECOM_POSITION = REPORT_SEND_TIME_POSITION + REPORT_SEND_TIME_LENGTH; + public static final int REPORT_RESULT_LENGTH = 5; + public static final int REPORT_RESULT_POSITION = REPORT_TELECOM_POSITION + REPORT_TELECOM_LENGTH; + + public static final int REPORT_ACK_BODY_LENGTH = 1; + public static final int REPORT_ACK_RESULT_CODE_LENGTH = 1; + public static final int REPORT_ACK_RESULT_CODE_POSITION = Header.BODY_POSITION + Header.BODY_LENGTH; + + public static ByteBuffer makeReport(MunjaonMsg msgData) { + ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + REPORT_BODY_LENGTH); + Packet.setDefaultByte(buffer); + Header.putHeader(buffer, Header.COMMAND_REPORT, REPORT_BODY_LENGTH); + /* 1. MSG_ID */ + makeReportForMsgId(buffer, msgData.getMsgId()); + /* 2. AGENT_CODE */ + makeReportForAgentCode(buffer, msgData.getAgentCode()); + /* 3. SEND TIME */ + makeReportForSendTime(buffer, msgData.getSendDate()); + /* 4. TELECOM */ + makeReportForTelecom(buffer, msgData.getTelecom()); + /* 5. RESULT */ + makeReportForResult(buffer, msgData.getSendStatus()); + + return buffer; + } + + public static void makeReportForMsgId(final ByteBuffer buffer, final String msgId) { + if (buffer == null || msgId == null) { + return; + } + + buffer.put(REPORT_MSG_ID_POSITION, msgId.getBytes()); + } + + public static String getReportForMsgId(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(REPORT_MSG_ID_POSITION); + byte[] destArray = new byte[REPORT_MSG_ID_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void makeReportForAgentCode(final ByteBuffer buffer, final String agentCode) { + if (buffer == null || agentCode == null) { + return; + } + + buffer.put(REPORT_AGENT_CODE_POSITION, agentCode.getBytes()); + } + + public static String getReportForAgentCode(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(REPORT_AGENT_CODE_POSITION); + byte[] destArray = new byte[REPORT_AGENT_CODE_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void makeReportForSendTime(final ByteBuffer buffer, final String sendTime) { + if (buffer == null || sendTime == null) { + return; + } + + buffer.put(REPORT_SEND_TIME_POSITION, sendTime.getBytes()); + } + + public static String getReportForSendTime(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(REPORT_SEND_TIME_POSITION); + byte[] destArray = new byte[REPORT_SEND_TIME_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void makeReportForTelecom(final ByteBuffer buffer, final String telecom) { + if (buffer == null || telecom == null) { + return; + } + + buffer.put(REPORT_TELECOM_POSITION, telecom.getBytes()); + } + + public static String getReportForTelecom(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(REPORT_TELECOM_POSITION); + byte[] destArray = new byte[REPORT_TELECOM_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + + public static void makeReportForResult(final ByteBuffer buffer, final String result) { + if (buffer == null || result == null) { + return; + } + + buffer.put(REPORT_RESULT_POSITION, result.getBytes()); + } + + public static String getReportForResult(final ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(REPORT_RESULT_POSITION); + byte[] destArray = new byte[REPORT_RESULT_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } +} diff --git a/src/main/java/com/munjaon/client/server/packet/SmsMessage.java b/src/main/java/com/munjaon/client/server/packet/SmsMessage.java new file mode 100644 index 0000000..a5611a7 --- /dev/null +++ b/src/main/java/com/munjaon/client/server/packet/SmsMessage.java @@ -0,0 +1,55 @@ +package com.munjaon.client.server.packet; + +import com.munjaon.client.model.MunjaonMsg; +import com.munjaon.client.util.CommonUtil; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +public final class SmsMessage { + public static final int DELIVER_SMS_BODY_LENGTH = 239; + public static final int DELIVER_SMS_ACK_BODY_LENGTH = 21; + + /* DELIVER */ + /* MESSAGE */ + public static final int DELIVER_MESSAGE_LENGTH = 160; + public static final int DELIVER_MESSAGE_POSITION = CommonMessage.DELIVER_MSG_TYPE_POSITION + CommonMessage.DELIVER_MSG_TYPE_LENGTH; + + public static void putMessageForDeliver(ByteBuffer buffer, String message) { + if (buffer == null || message == null) { + return; + } + message = CommonUtil.cutString(message, DELIVER_MESSAGE_LENGTH); + buffer.put(DELIVER_MESSAGE_POSITION, message.getBytes()); + } + public static String getMessageForDeliver(ByteBuffer buffer) { + if (buffer == null) { + return null; + } + + buffer.position(DELIVER_MESSAGE_POSITION); + byte[] destArray = new byte[DELIVER_MESSAGE_LENGTH]; + buffer.get(destArray); + + return Packet.getString(destArray); + } + public static void makeDataForDeliver(ByteBuffer buffer, MunjaonMsg data) { + if (buffer == null || data == null) { + return; + } + /* MSG_ID */ + CommonMessage.putMessageIdForDeliver(buffer, data.getMsgId()); + /* SENDER */ + CommonMessage.putSenderForDeliver(buffer, data.getSendPhone()); + /* RECEIVER */ + CommonMessage.putReceiverForDeliver(buffer, data.getRecvPhone()); + /* RESERVE_TIME */ + CommonMessage.putReserveTimeForDeliver(buffer, data.getReserveDate()); + /* REQUEST_TIME */ + CommonMessage.putRequestTimeForDeliver(buffer, data.getRequestDate()); + /* MSG_TYPE */ + CommonMessage.putMsgTypeForDeliver(buffer, data.getMsgType()); + /* MSG */ + putMessageForDeliver(buffer, data.getMessage()); + } +} diff --git a/src/main/java/com/munjaon/client/server/service/CollectClientService.java b/src/main/java/com/munjaon/client/server/service/CollectClientService.java new file mode 100644 index 0000000..d07fcb6 --- /dev/null +++ b/src/main/java/com/munjaon/client/server/service/CollectClientService.java @@ -0,0 +1,186 @@ +package com.munjaon.client.server.service; + +import com.munjaon.client.model.MunjaonMsg; +import com.munjaon.client.server.packet.*; +import com.munjaon.client.service.DatabaseTypeWorker; +import org.json.simple.JSONObject; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.List; + +public class CollectClientService extends Service { + private final String serviceType; + private SocketChannel socketChannel; + private long lastPacketSendTime = 0; + private String address; + private int port; + private String id; + private String pwd; + + public CollectClientService(String serviceName, String serviceType) { + super(serviceName); + this.serviceType = serviceType; + } + + @Override + public void checkReady() { + DatabaseTypeWorker worker = DatabaseTypeWorker.find(System.getProperty("DBMS")); + if (worker == null) { + return; + } + this.IS_READY_YN = worker.checkTableExists(); + } + + @Override + public void initResources() { + this.address = getProp("HOST"); + this.port = Integer.parseInt(getProp("DELIVER.PORT")); + this.id = getProp("ID"); + this.pwd = getProp("PASSWORD"); + saveSystemLog("Try Connect to " + this.address + ":" + this.port); + try { + socketChannel = SocketChannel.open(new InetSocketAddress(this.address, this.port)); + socketChannel.configureBlocking(false); + } catch (IOException e) { + saveSystemLog("Connect Fail " + this.address + ":" + this.port); + throw new RuntimeException(e); + } + } + + @Override + public void releaseResources() { + if (socketChannel != null) { + try { + socketChannel.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + @Override + public void doService() { + bind(); + while (isRun()) { + try { + messageService(); + linkCheckService(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + private void bind() { + ByteBuffer sendBuffer = Bind.makeBindBuffer(id, pwd); + ByteBuffer recvBuffer = ByteBuffer.allocate(Header.HEADER_LENGTH + Bind.BIND_ACK_BODY_LENGTH); + try { + saveSystemLog("sendBuffer " + sendBuffer.position() + ":" + sendBuffer.limit()); + saveSystemLog("Bind Try Connect to " + this.address + ":" + this.port); + socketChannel.write(sendBuffer); + saveSystemLog("Bind Read to " + this.address + ":" + this.port); + while (true) { + int recvCount = socketChannel.read(recvBuffer); + if (recvCount == -1) { + throw new RuntimeException("BIND ERROR"); + } else if (recvCount > 0) { + String resultCode = Bind.getBindAckResultCode(recvBuffer); + saveSystemLog("resultCode " + resultCode); + if ("00".equals(resultCode)) { + lastPacketSendTime = System.currentTimeMillis(); + saveSystemLog("Bind OK"); + break; + } else { + saveSystemLog("Bind FAIL"); + throw new RuntimeException("Bind FAIL"); + } + } + } + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private void messageService() { + DatabaseTypeWorker worker = DatabaseTypeWorker.find(System.getProperty("DBMS")); + if (worker == null) { + return; + } + List list = worker.selectToDeliver("S"); + if (list == null || list.isEmpty()) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + return; + } + for (MunjaonMsg data : list) { + ByteBuffer sendBuffer = ByteBuffer.allocate(Header.HEADER_LENGTH + SmsMessage.DELIVER_SMS_BODY_LENGTH); + ByteBuffer recvBuffer = ByteBuffer.allocate(Header.HEADER_LENGTH + SmsMessage.DELIVER_SMS_ACK_BODY_LENGTH); +// sendBuffer.flip(); + try { + Header.putHeader(sendBuffer, Header.COMMAND_DELIVER, SmsMessage.DELIVER_SMS_BODY_LENGTH); + SmsMessage.makeDataForDeliver(sendBuffer, data); +// CommonMessage.putMessageIdForDeliver(sendBuffer, data.getMsgId()); +// CommonMessage.putSenderForDeliver(sendBuffer, data.getSendPhone()); +// +// CommonMessage.putReceiverForDeliver(sendBuffer, data.getRecvPhone()); +// CommonMessage.putReserveTimeForDeliver(sendBuffer, data.getReserveDate()); +// CommonMessage.putRequestTimeForDeliver(sendBuffer, data.getRequestDate()); +// CommonMessage.putMsgTypeForDeliver(sendBuffer, data.getMsgType()); +// CommonMessage.putSenderForDeliver(sendBuffer, data.getSendPhone()); + saveSystemLog("Deliver Send"); + socketChannel.write(sendBuffer); + while (true) { + int recvCount = socketChannel.read(recvBuffer); + if (recvCount == -1) { + throw new RuntimeException("DELIVER ERROR"); + } else if (recvCount > 0) { + worker.updateToDeliver(data.getMsgId()); + saveSystemLog("Deliver OK"); + lastPacketSendTime = System.currentTimeMillis(); + break; + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + private void linkCheckService() { + if (System.currentTimeMillis() - lastPacketSendTime < Packet.LINK_CHECK_CYCLE) { + saveSystemLog("LinkCheck Is Not"); + return; + } + + ByteBuffer recvBuffer = ByteBuffer.allocate(Header.HEADER_LENGTH + LinkCheck.LINK_CHECK_ACK_BODY_LENGTH); + try { + saveSystemLog("LinkCheck Send"); + socketChannel.write(LinkCheck.makeLinkCheckBuffer()); + while (true) { + int recvCount = socketChannel.read(recvBuffer); + if (recvCount == -1) { + throw new RuntimeException("LINK_CHECK ERROR"); + } else if (recvCount > 0) { + saveSystemLog("LinkCheck OK"); + lastPacketSendTime = System.currentTimeMillis(); + break; + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public JSONObject monitorService() { + return null; + } +} diff --git a/src/main/java/com/munjaon/client/server/service/PropertyLoader.java b/src/main/java/com/munjaon/client/server/service/PropertyLoader.java index 1b4eee7..e670874 100644 --- a/src/main/java/com/munjaon/client/server/service/PropertyLoader.java +++ b/src/main/java/com/munjaon/client/server/service/PropertyLoader.java @@ -30,7 +30,7 @@ public class PropertyLoader extends Thread { System.err.println("Not Defined : [" + key + "]"); } else { - value = value.replaceAll("\\$WORK_HOME", System.getProperty("WORK_HOME")); + value = value.replaceAll("\\$SERVICE_HOME", System.getProperty("SERVICE_HOME")); } return value; diff --git a/src/main/java/com/munjaon/client/server/service/ReportClientService.java b/src/main/java/com/munjaon/client/server/service/ReportClientService.java new file mode 100644 index 0000000..83e2d1e --- /dev/null +++ b/src/main/java/com/munjaon/client/server/service/ReportClientService.java @@ -0,0 +1,140 @@ +package com.munjaon.client.server.service; + +import com.munjaon.client.server.packet.Bind; +import com.munjaon.client.server.packet.Header; +import com.munjaon.client.server.packet.LinkCheck; +import com.munjaon.client.server.packet.Packet; +import com.munjaon.client.service.DatabaseTypeWorker; +import org.json.simple.JSONObject; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +public class ReportClientService extends Service { + private SocketChannel socketChannel; + private long lastPacketSendTime = 0; + private String address; + private int port; + private String id; + private String pwd; + + public ReportClientService(String serviceName) { + super(serviceName); + } + + @Override + public void checkReady() { + DatabaseTypeWorker worker = DatabaseTypeWorker.find(System.getProperty("DBMS")); + if (worker == null) { + return; + } + this.IS_READY_YN = worker.checkTableExists(); + } + + @Override + public void initResources() { + this.address = getProp("HOST"); + this.port = Integer.parseInt(getProp("PORT")); + this.id = getProp("ID"); + this.pwd = getProp("PASSWORD"); + saveSystemLog("Try Connect to " + this.address + ":" + this.port); + try { + socketChannel = SocketChannel.open(new InetSocketAddress(this.address, this.port)); + socketChannel.configureBlocking(false); + } catch (IOException e) { + saveSystemLog("Connect Fail " + this.address + ":" + this.port); + throw new RuntimeException(e); + } + } + + @Override + public void releaseResources() { + if (socketChannel != null) { + try { + socketChannel.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + @Override + public void doService() { + + } + + private void bind() { + ByteBuffer sendBuffer = Bind.makeBindBuffer(id, pwd); + ByteBuffer recvBuffer = ByteBuffer.allocate(Header.HEADER_LENGTH + Bind.BIND_ACK_BODY_LENGTH); + try { + saveSystemLog("sendBuffer " + sendBuffer.position() + ":" + sendBuffer.limit()); + saveSystemLog("Bind Try Connect to " + this.address + ":" + this.port); + socketChannel.write(sendBuffer); + saveSystemLog("Bind Read to " + this.address + ":" + this.port); + while (true) { + int recvCount = socketChannel.read(recvBuffer); + if (recvCount == -1) { + throw new RuntimeException("BIND ERROR"); + } else if (recvCount > 0) { + String resultCode = Bind.getBindAckResultCode(recvBuffer); + saveSystemLog("resultCode " + resultCode); + if ("00".equals(resultCode)) { + lastPacketSendTime = System.currentTimeMillis(); + saveSystemLog("Bind OK"); + break; + } else { + saveSystemLog("Bind FAIL"); + throw new RuntimeException("Bind FAIL"); + } + } + } + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private void messageService() { + bind(); + while (isRun()) { + try { + messageService(); + linkCheckService(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + private void linkCheckService() { + if (System.currentTimeMillis() - lastPacketSendTime < Packet.LINK_CHECK_CYCLE) { + saveSystemLog("LinkCheck Is Not"); + return; + } + + ByteBuffer recvBuffer = ByteBuffer.allocate(Header.HEADER_LENGTH + LinkCheck.LINK_CHECK_ACK_BODY_LENGTH); + try { + saveSystemLog("LinkCheck Send"); + socketChannel.write(LinkCheck.makeLinkCheckBuffer()); + while (true) { + int recvCount = socketChannel.read(recvBuffer); + if (recvCount == -1) { + throw new RuntimeException("LINK_CHECK ERROR"); + } else if (recvCount > 0) { + saveSystemLog("LinkCheck OK"); + lastPacketSendTime = System.currentTimeMillis(); + break; + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public JSONObject monitorService() { + return null; + } +} diff --git a/src/main/java/com/munjaon/client/server/service/Server.java b/src/main/java/com/munjaon/client/server/service/Server.java new file mode 100644 index 0000000..974591a --- /dev/null +++ b/src/main/java/com/munjaon/client/server/service/Server.java @@ -0,0 +1,193 @@ +package com.munjaon.client.server.service; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +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.concurrent.Executors; + +public class Server implements Runnable { + private InetSocketAddress listenAddress; + // 메시지는 개행으로 구분한다. + private static char CR = (char) 0x0D; + private static char LF = (char) 0x0A; + // ip와 port 설정 + public Server(String address, int port) { + listenAddress = new InetSocketAddress(address, port); + } + // Thread 실행. + public void run() { + // 셀렉터 설정 + try (Selector selector = Selector.open()) { + // 채널 설정 + try (ServerSocketChannel serverChannel = ServerSocketChannel.open()) { + System.out.println("ServerSocketChannel is open"); + // non-Blocking 설정 + serverChannel.configureBlocking(false); + System.out.println("serverChannel.configureBlocking(false) >> "); + // 서버 ip, port 설정 + serverChannel.socket().bind(listenAddress); + System.out.println("serverChannel.socket().bind(listenAddress) >> "); + // 채널에 accept 대기 설정 + serverChannel.register(selector, SelectionKey.OP_ACCEPT); + System.out.println("serverChannel.register(selector, SelectionKey.OP_ACCEPT) >> "); + // 셀렉터가 있을 경우. +// while (selector.select() > 0) { + while (true) { + if (selector.select(10000) == 0) { + System.out.println("selector.select() == 0"); + continue; + } + System.out.println("selector.select() > 0 >> "); + // 셀렉터 키 셋를 가져온다. + Iterator keys = selector.selectedKeys().iterator(); + // 키가 있으면.. + while (keys.hasNext()) { + SelectionKey key = keys.next(); + //키 셋에서 제거. + keys.remove(); + if (!key.isValid()) { + continue; + } + // 접속일 경우.. + if (key.isAcceptable()) { + this.accept(selector, key); + // 수신일 경우.. + } else if (key.isReadable()) { + this.receive(selector, key); + // 발신일 경우.. + } else if (key.isWritable()) { + this.send(selector, key); + } + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + // 접속시 호출 함수.. + private void accept(Selector selector, SelectionKey key) { + try { + // 키 채널을 가져온다. + ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); + // accept을 해서 Socket 채널을 가져온다. + SocketChannel channel = serverChannel.accept(); + channel.configureBlocking(false); + // 소켓 취득 + Socket socket = channel.socket(); + SocketAddress remoteAddr = socket.getRemoteSocketAddress(); + System.out.println("Connected to: " + remoteAddr); + // 접속 Socket 단위로 사용되는 Buffer; + StringBuffer sb = new StringBuffer(); + sb.append("Welcome server!\r\n>"); + // Socket 채널을 channel에 송신 등록한다 + channel.register(selector, SelectionKey.OP_WRITE, sb); + } catch (IOException e) { + e.printStackTrace(); + } + } + // 수신시 호출 함수.. + private void receive(Selector selector, SelectionKey key) { + try { + // 키 채널을 가져온다. + SocketChannel channel = (SocketChannel) key.channel(); + // 연결이 끊겼는지 확인 + if ((channel.isConnected() || channel.isOpen()) == false) { + System.out.println("java connection reset by client: "); + // 키 닫기 + key.cancel(); + // 소켓 채널 닫기 + channel.close(); + // 종료 + return; + } + // 채널 Non-blocking 설정 + channel.configureBlocking(false); + // 소켓 취득 + Socket socket = channel.socket(); + // Byte 버퍼 생성 + ByteBuffer buffer = ByteBuffer.allocate(1024); + // ***데이터 수신*** + int size = channel.read(buffer); + // 수신 크기가 없으면 소켓 접속 종료. + if (size == -1) { + SocketAddress remoteAddr = socket.getRemoteSocketAddress(); + System.out.println("Connection closed by client: " + remoteAddr); + // 소켓 채널 닫기 + channel.close(); + // 소켓 닫기 + socket.close(); + // 키 닫기 + key.attach(null); + key.cancel(); + return; + } + // ByteBuffer -> byte[] + byte[] data = new byte[size]; + System.arraycopy(buffer.array(), 0, data, 0, size); + // StringBuffer 취득 + StringBuffer sb = (StringBuffer) key.attachment(); + // 버퍼에 수신된 데이터 추가 + sb.append(new String(data)); + // 데이터 끝이 개행 일 경우. + if (sb.length() > 2 && sb.charAt(sb.length() - 2) == CR && sb.charAt(sb.length() - 1) == LF) { + // 개행 삭제 + sb.setLength(sb.length() - 2); + // 메시지를 콘솔에 표시한다. + String msg = sb.toString(); + System.out.println(msg); + // exit 경우 접속을 종료한다. + if ("exit".equals(msg)) { + // 소켓 채널 닫기 + channel.close(); + // 소켓 닫기 + socket.close(); + // 키 닫기 + key.cancel(); + return; + } + // Echo - 메시지> 의 형태로 재 전송. + sb.insert(0, "Echo - "); + sb.append("\r\n>"); + // Socket 채널을 channel에 송신 등록한다 + channel.register(selector, SelectionKey.OP_WRITE, sb); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + // 발신시 호출 함수 + private void send(Selector selector, SelectionKey key) { + try { + // 키 채널을 가져온다. + SocketChannel channel = (SocketChannel) key.channel(); + // 채널 Non-blocking 설정 + channel.configureBlocking(false); + // StringBuffer 취득 + StringBuffer sb = (StringBuffer) key.attachment(); + String data = sb.toString(); + // StringBuffer 초기화 + sb.setLength(0); + // byte 형식으로 변환 + ByteBuffer buffer = ByteBuffer.wrap(data.getBytes()); + // ***데이터 송신*** + channel.write(buffer); + // Socket 채널을 channel에 수신 등록한다 + channel.register(selector, SelectionKey.OP_READ, sb); + } catch (IOException e) { + e.printStackTrace(); + } + } + // 시작 함수 + public static void main(String[] args) { + // 포트는 10000을 Listen한다. + Executors.newSingleThreadExecutor().execute(new Server("localhost", 10000)); + } +} diff --git a/src/main/java/com/munjaon/client/server/service/Service.java b/src/main/java/com/munjaon/client/server/service/Service.java new file mode 100644 index 0000000..c80b29b --- /dev/null +++ b/src/main/java/com/munjaon/client/server/service/Service.java @@ -0,0 +1,148 @@ +package com.munjaon.client.server.service; + +import com.munjaon.client.server.config.ServerConfig; +import com.munjaon.client.util.LogUtil; +import org.json.simple.JSONObject; + +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public abstract class Service extends Thread { + public static final SimpleDateFormat sdf = new SimpleDateFormat("[MM-dd HH:mm:ss]"); + public static final String LOG_DATE_FORMAT = "[MM-dd HH:mm:ss]"; + + private String LOG_FILE; + protected LogUtil logger; + private Long LAST_PROPERTY_LOAD_TIME = 0L; + + protected boolean IS_SERVER_RUN; // 서버가 구동중인지 여부 + protected boolean IS_READY_YN; // 서비스 구동준비가 완료되었는지 체크 + protected boolean IS_RUN_YN; + protected boolean IS_STOP_YN; + + public Service() {} + public Service(String serviceName) { + super(serviceName); + LOG_FILE = System.getProperty("ROOTPATH") + getProp("LOG_FILE"); + } + + protected String getProp(String name) { + return getProp(getName(), name); + } + + public static String getProp(String svc, String name) { + return PropertyLoader.getProp(svc, name); + } + + protected void checkRun() { + this.IS_RUN_YN = getProp("RUN_FLAG") != null && "Y".equals(getProp("RUN_FLAG")); + } + + protected void checkClientRun() { + this.IS_SERVER_RUN = getProp("client", "run") != null && "Y".equals(getProp("client", "run")); + } + + public void reloadCheckRun() { + if ((System.currentTimeMillis() - this.LAST_PROPERTY_LOAD_TIME) > ServerConfig.INTERVAL_PROPERTY_RELOAD_TIME) { + checkRun(); + checkClientRun(); + this.LAST_PROPERTY_LOAD_TIME = System.currentTimeMillis(); + } + } + + public boolean isRun() { + return IS_SERVER_RUN && IS_RUN_YN && !IS_STOP_YN; + } + + public boolean isReady() { + return IS_READY_YN; + } + + protected void setLogFile(String sLogFile) { + if ( logger != null ) { + logger.close(); + logger = null; + } + + logger = new LogUtil( sLogFile ); + } + + protected void saveSystemLog(Object obj) { + saveLog(obj, true); + } + + protected void saveLog(Object obj) { + saveLog(obj, false); + } + + protected void saveLog(Object obj, boolean isConsoleOutput) { + if(isConsoleOutput) { + System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern(LOG_DATE_FORMAT)) + " {{"+ getName() +"}} "+obj); + } + if (logger != null) { + logger.log(obj); + } else { + if (obj instanceof Throwable) { + LogUtil.log(LOG_FILE, obj); + } else { + LogUtil.log(LOG_FILE, "{{"+ getName() +"}} "+obj); + } + } + } + + protected void initLogFile() { + LOG_FILE = System.getProperty("ROOTPATH") + getProp("LOG_FILE"); + System.out.println("LOG_FILE: " + LOG_FILE); + setLogFile( LOG_FILE ); + saveSystemLog("Service Log Initializing ... ..."); + } + + @Override + public void run() { + while (true) { + try { + /* 1. 서비스간의 dependency에 따른 체크 */ + checkReady(); + /* 2. 로그 초기화 */ + initLogFile(); + /* 3. Runflag reload */ + reloadCheckRun(); + + if (isRun() && isReady()) { + /* 3. 서비스 초기화 */ + initResources(); + /* 4. 서비스 시작 */ + doService(); + /* 5. 서비스 자원 해제 */ + releaseResources(); + saveSystemLog("Service Stopped."); + } else { + saveSystemLog("Service is Not Running."); + } + /* 6. 3초간 sleep */ + Thread.sleep(3000); + } catch (Exception e) { + saveSystemLog(e); + try { + Thread.sleep(3000); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + } finally { + if(logger != null) { logger.close(); logger = null; } + } + } + } + + /* 서비스간의 dependency에 따른 체크 */ + public abstract void checkReady(); + /* 추가적인 프로퍼티, 서비스 자원 초기화 */ + public abstract void initResources(); + /* 서비스 자원 해제 */ + public abstract void releaseResources(); + /* 서비스 */ + public abstract void doService(); + /* 모니터링을 위한 메소드 */ + public abstract JSONObject monitorService(); +} diff --git a/src/main/java/com/munjaon/client/util/ByteUtil.java b/src/main/java/com/munjaon/client/util/ByteUtil.java new file mode 100644 index 0000000..bf485ae --- /dev/null +++ b/src/main/java/com/munjaon/client/util/ByteUtil.java @@ -0,0 +1,423 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package com.munjaon.client.util; + +/** + * bytes 관련 유틸리티 클래스 + * @author JDS + */ +public final class ByteUtil { + public static final int BYTE_SIZE = 128; + /* 큐에 저장하기전에 바이트를 채울 문자 */ + public static final byte SET_DEFAULT_BYTE = (byte) 0x00; + + /** + * bytes 배열의 핵사값을 16자리씩 개행하여 반환한다.
+ * 핵사 로그 출력을 위해 사용한다. + * @param src + * @param isLine + * @return 16자리씩 개행된 핵사값 + */ + public static String byteToHex(byte[] src, boolean isLine) { + String hex = ""; + // if(src.length > 16) + hex = ""; + for (int i = 0, j = 1; i < src.length; i++, j++) { + hex += pad0(Integer.toHexString(src[i] & 0xff), 2) + " "; + + if (isLine && src.length > 16 && (j % 16) == 0) { + // hex += " " + new String(codes, j-16, 16); + hex += "\r\n"; + } + } + return hex; + } + + /** + * bytes 배열의 핵사값을 16자리씩 개행하여 반환한다.
+ * 핵사 로그 출력을 위해 사용한다. + * @param src + * @return 16자리씩 개행된 핵사값 + */ + public static String byteToHex(byte[] src) { + String hex = ""; + // if(src.length > 16) + //hex = "\r\n"; + for (int i = 0, j = 1; i < src.length; i++, j++) { + hex += pad0(Integer.toHexString(src[i] & 0xff), 2) + " "; + + if (src.length > 16 && (j % 16) == 0) { + // hex += " " + new String(codes, j-16, 16); + hex += "\r\n"; + } + } + return hex; + } + + /** + * bytes 배열의 지정된 위치값에 대해 16자리씩 개행된 핵사값으로 반환한다.
+ * 핵사 로그 출력을 위해 사용한다. + * @param src + * @param srcPos + * @param length + * @return 16자리씩 개행된 핵사값 + */ + public static String byteToHex(byte[] src, int srcPos, int length) { + String hex = ""; + //if(src.length > 16) + hex = "\r\n"; + for (int i = srcPos, j = 1; i < srcPos + length; i++, j++) { + hex += pad0(Integer.toHexString(src[i] & 0xff), 2) + " "; + if (src.length > 16 && (j % 16) == 0) { + hex += "\r\n"; + } + } + return hex; + } + + public static String intToHex(int src) { + String hex = "0x"; + byte[] bSrc = ByteUtil.intToByte(src); + for (int i = 0, j = 1; i < bSrc.length; i++, j++) { + hex += pad0(Integer.toHexString(bSrc[i] & 0xff), 2); + } + return hex; + } + + public static byte[] shortToByte(short s) { + byte dest[] = new byte[2]; + dest[1] = (byte) (s & 0xff); + dest[0] = (byte) (s >>> 8 & 0xff); + return dest; + } + + public static byte[] intToByte(int i) { + byte dest[] = new byte[4]; + dest[3] = (byte) (i & 0xff); + dest[2] = (byte) (i >>> 8 & 0xff); + dest[1] = (byte) (i >>> 16 & 0xff); + dest[0] = (byte) (i >>> 24 & 0xff); + return dest; + } + + public static byte[] longToByte(long l) { + byte dest[] = new byte[8]; + dest[7] = (byte) (int) (l & 255L); + dest[6] = (byte) (int) (l >>> 8 & 255L); + dest[5] = (byte) (int) (l >>> 16 & 255L); + dest[4] = (byte) (int) (l >>> 24 & 255L); + dest[3] = (byte) (int) (l >>> 32 & 255L); + dest[2] = (byte) (int) (l >>> 40 & 255L); + dest[1] = (byte) (int) (l >>> 48 & 255L); + dest[0] = (byte) (int) (l >>> 56 & 255L); + return dest; + } + + public static byte[] floatToByte(float f) { + byte dest[] = new byte[4]; + return setFloat(dest, 0, f); + } + + public static byte[] doubleToByte(double d) { + byte dest[] = new byte[8]; + return setDouble(dest, 0, d); + } + + public static byte getByte(byte src[], int offset) { + return src[offset]; + } + + public static byte[] getBytes(String data) { + byte[] b = null; + + b = data.getBytes(); + + return (b); + } + + public static byte[] getBytes(byte src[], int offset, int length) { + byte dest[] = new byte[length]; + System.arraycopy(src, offset, dest, 0, length); + return dest; + } + + public static short getShort(byte src[], int offset) { + return (short) ((src[offset] & 0xff) << 8 | src[offset + 1] & 0xff); + } + + public static int getInt(byte src[], int offset) { + return (src[offset] & 0xff) << 24 | (src[offset + 1] & 0xff) << 16 + | (src[offset + 2] & 0xff) << 8 | src[offset + 3] & 0xff; + } + + public static long getLong(byte src[], int offset) { + return (long) getInt(src, offset) << 32 + | (long) getInt(src, offset + 4) & 0xffffffffL; + } + + public static float getfloat(byte src[], int offset) { + return Float.intBitsToFloat(getInt(src, offset)); + } + + public static double getdouble(byte src[], int offset) { + return Double.longBitsToDouble(getLong(src, offset)); + } + + public static byte[] setByte(byte dest[], int offset, byte b) { + dest[offset] = b; + return dest; + } + + public static void setBytes(byte[] dest, int offset, String s) { + setBytes(dest, offset, s.getBytes()); + } + + public static byte[] setBytes(byte dest[], int offset, byte src[]) { + System.arraycopy(src, 0, dest, offset, src.length); + return dest; + } + + public static byte[] setBytes(byte dest[], int offset, byte src[], + int len) { + System.arraycopy(src, 0, dest, offset, len); + return dest; + } + + public static byte[] setShort(byte dest[], int offset, short s) { + dest[offset] = (byte) (s >>> 8 & 0xff); + dest[offset + 1] = (byte) (s & 0xff); + return dest; + } + + public static byte[] setInt(byte dest[], int offset, int i) { + dest[offset] = (byte) (i >>> 24 & 0xff); + dest[offset + 1] = (byte) (i >>> 16 & 0xff); + dest[offset + 2] = (byte) (i >>> 8 & 0xff); + dest[offset + 3] = (byte) (i & 0xff); + return dest; + } + + public static byte[] setLong(byte dest[], int offset, long l) { + setInt(dest, offset, (int) (l >>> 32)); + setInt(dest, offset + 4, (int) (l & 0xffffffffL)); + return dest; + } + + public static byte[] setFloat(byte dest[], int offset, float f) { + return setInt(dest, offset, Float.floatToIntBits(f)); + } + + public static byte[] setDouble(byte dest[], int offset, double d) { + return setLong(dest, offset, Double.doubleToLongBits(d)); + } + + public static boolean isEquals(byte b[], String s) { + if (b == null || s == null) + return false; + int slen = s.length(); + if (b.length != slen) + return false; + for (int i = slen; i-- > 0;) + if (b[i] != s.charAt(i)) + return false; + + return true; + } + + public static boolean isEquals(byte a[], byte b[]) { + if (a == null || b == null) + return false; + if (a.length != b.length) + return false; + for (int i = a.length; i-- > 0;) + if (a[i] != b[i]) + return false; + + return true; + } + + public static int hexToInt(byte[] b) { + int sum = 0; + int len = 0; + int pos = 0; + + if (b != null) { + len = b.length; + + for (int i = len - 1; i > 0; i--) { + sum += sqrt(BYTE_SIZE, i) * (int) b[pos]; + pos++; + } + sum += b[pos]; + } + + return (sum); + } + + public static int hexToInt(byte[] b, int start, int len) { + int sum = 0; + int pos = start; + + if (b != null) { + for (int i = len - 1; i > 0; i--) { + sum += sqrt(BYTE_SIZE, i) * (int) b[pos]; + pos++; + } + sum += b[pos]; + } + + return (sum); + } + + public static byte[] intToHex(int num, int digit) { + byte[] b = new byte[digit]; + int[] intArr = makeFunction(num, digit, BYTE_SIZE); + + for (int i = 0; i < digit; i++) { + b[i] = (byte) intArr[i]; + } + + return (b); + } + + private static int[] makeFunction(int num, int digit, int jinso) { + int[] fun = new int[digit]; + int restNum = num; + int pos = 0; + + for (int i = digit - 1; i > 0; i--) { + int quotient = restNum / sqrt(jinso, i); + fun[pos++] = quotient; + restNum -= (quotient * sqrt(jinso, i)); + } + fun[pos++] = restNum; + + return (fun); + } + + private static int sqrt(int num, int count) { + int sum = 0; + + sum = (count >= 1) ? num : 0; + for (int i = 1; i < count; i++) { + sum = sum * num; + } + + return (sum); + } + + public static boolean arrayComp(byte[] src, byte[] obj) { + boolean isSame = true; + + if (src.length != obj.length) { + isSame = false; + } else { + for (int i = 0; i < src.length; i++) { + if (src[i] != obj[i]) { + isSame = false; + break; + } + } + } + + return (isSame); + } + + public static String pad0(String str, int size) { + char[] zeros = new char[size - str.length()]; + for (int i = 0; i < zeros.length; i++) + zeros[i] = '0'; + return new String(zeros) + str; + } + + public static byte[] convertCharArrayToByteArray(char[] ca) { + byte[] ba = new byte[ca.length*2]; + java.nio.ByteBuffer.wrap(ba).asCharBuffer().put(ca); + return ba; + } + + public static char[] convertByteArrayToCharArray(byte[] ba) { + char[] ca = new char[ba.length/2]; + java.nio.ByteBuffer.wrap(ba).asCharBuffer().get(ca); + return ca; + } + + public static byte[] setNull(byte[] b) { + for(int i=0; i> 8 & 0xff); + ret[1] = (byte)(value >> 16 & 0xff); + ret[0] = (byte)(value >> 24 & 0xff); + + return ret; + } + + // Little Endian + public static int toInt2(byte[] value) { + return (int)( + (value[0] & 0xff) | + (value[1] & 0xff) << 8 | + (value[2] & 0xff) << 16 | + (value[3] & 0xff) << 24 ); + } + + // Little Endian + public static byte[] toBytes2(int value) { + byte[] ret = new byte[4]; + + ret[0] = (byte)(value & 0xff); + ret[1] = (byte)(value >> 8 & 0xff); + ret[2] = (byte)(value >> 16 & 0xff); + ret[3] = (byte)(value >> 24 & 0xff); + + return ret; + } + + public static byte[] setSpaceAll(byte[] data) { + return setAll(data, (byte) ' '); + } + + public static byte[] setAll(byte[] data, byte bt) { + int len = data.length; + + for( int i=0; i limit){ + for(int cnt = 0 ; cnt < len ;cnt++){ + if ((str.charAt(cnt) & 0xFF00) == 0) // 1 Byte 문자이면 + sumLength++; + else // 2바이트 문자라면... + sumLength = sumLength + 2; + if(sumLength > limit){ + cutString = str.substring(0, cnt); + break; + } + } + }else{ + cutString = str; + } + + return cutString; + } + // 날짜를 구간별로 자르는 함수 + // (inDate:날짜 >> (입력형식:2012년 12월 20일일 경우 : 20121220)) + public static int substringDate(String inDate, int beginIndex, int lastIndex){ + int subDate = -1; + inDate = doNumber(inDate); + if(inDate.length() == 8){ + if((beginIndex < lastIndex) && (lastIndex <= 8)) + subDate = Integer.parseInt(inDate.substring(beginIndex, lastIndex)); + } + return subDate; + } + // 시간을 구간별로 자르는 함수 + public static int substringTime(String inTime, int beginIndex, int lastIndex){ + int subDate = -1; + inTime = doNumber(inTime); + if(inTime.length() == 6){ + if((beginIndex < lastIndex) && (lastIndex <= 6)) + subDate = Integer.parseInt(inTime.substring(beginIndex, lastIndex)); + } + return subDate; + } + public static boolean validDate(String fullDate){ + boolean validFlag = true; + fullDate = doNumber(fullDate); + + if(fullDate.length() != 14){ + validFlag = false; + }else{ + if(!(isValidDay(fullDate.substring(0, 8)) && isValidTime(fullDate.substring(8, 14)))) + validFlag = false; + } + return validFlag; + } + // 유효한 날짜 형식인지 체크하는 함수 + public static boolean isValidDay(String inDate){ + boolean validFlag = true; + int year = substringDate(inDate, 0, 4); + // 년도에서 앞에 두자리 체크 + if(year < 2013){ + validFlag = false; + } + int month = substringDate(inDate, 4, 6); + int day = substringDate(inDate, 6, 8); + if (month < 1 || month > 12) { // check month range + validFlag = false; + } + if (day < 1 || day > 31) { + validFlag = false; + } + if ((month==4 || month==6 || month==9 || month==11) && day==31) { + validFlag = false; + } + if (month == 2) { // check for february 29th + boolean isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); + if (day>29 || (day==29 && !isleap)) { + validFlag = false; + } + } + return validFlag; + } + // 유효한 날짜 형식인지 체크하는 함수 + public static boolean isValidTime(String inTime){ + boolean validFlag = true; + int hour = substringTime(inTime, 0, 2); + int minute = substringTime(inTime, 2, 4); + int second = substringTime(inTime, 4, 6); + if(hour < 0 || hour > 23) + validFlag = false; + if(minute < 0 || minute > 59) + validFlag = false; + if(second < 0 || second > 59) + validFlag = false; + return validFlag; + } + // 예약일이 하루전인지 체크하는 함수 + // 앞의 날짜가 뒤의 날짜보다 이전이면: true / 그렇지않으면 false) + public static boolean isBeforeDate(String srcDate, String destDate){ + boolean validFlag = false; + Calendar srcCal = getCalendar(srcDate); + Calendar destCal = getCalendar(destDate); + if(srcCal == null || destCal == null){ + validFlag = true; + }else{ + if(srcCal.before(destCal)) + validFlag = true; + } + + return validFlag; + } + + public static Calendar getCalendar(int hour){ + Calendar thisCal = null; + thisCal.add(Calendar.HOUR, hour); + return thisCal; + } + public static Calendar getCalendar(String inDate){ + Calendar thisCal = null; + inDate = doNumber(inDate); + if(inDate.length() == 14 && validDate(inDate)){ + String date = inDate.substring(0, 8); + String time = inDate.substring(8, 14); + int year = substringDate(date, 0, 4); + int month = substringDate(date, 4, 6); + int day = substringDate(date, 6, 8); + int hour = substringTime(time, 0, 2); + int minute = substringTime(time, 2, 4); + int second = substringTime(time, 4, 6); + thisCal = Calendar.getInstance(); + thisCal.set(year, (month-1), day, hour, minute, second); + } + return thisCal; + } + public static String currentTime(){ + Calendar currDate = Calendar.getInstance(); + SimpleDateFormat dateForm = new SimpleDateFormat("HHmmss"); + return dateForm.format(currDate.getTime()); + } + public static String getLastDate(String year, String month, String day){ + String dateStr = null; + String lastDay = null; + Calendar currDate = Calendar.getInstance(); + currDate.set(Integer.parseInt(year),Integer.parseInt(month)-1,Integer.parseInt(day)); + lastDay = Integer.toString(currDate.getActualMaximum(Calendar.DAY_OF_MONTH)); + dateStr = year+month+lastDay; + return dateStr; + } + public static String currentDay(){ + Calendar currDate = Calendar.getInstance(); + SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMdd"); + return dateForm.format(currDate.getTime()); + } + public static String currentDate(){ + Calendar currDate = Calendar.getInstance(); + SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMddHHmmss"); + return dateForm.format(currDate.getTime()); + } + public static String currentLogDate(){ + Calendar currDate = Calendar.getInstance(); + SimpleDateFormat dateForm = new SimpleDateFormat("[yyyy-MM-dd][HH:mm:ss]"); + return dateForm.format(currDate.getTime()); + } + // "yyyyMMddHHmmss" 의 조합 + public static String formatDate(String format){ + Calendar currDate = Calendar.getInstance(); + SimpleDateFormat dateForm = new SimpleDateFormat(format); + return dateForm.format(currDate.getTime()); + } + public static String getTargetDate(int term){ + Calendar currDate = Calendar.getInstance(); + currDate.add(Calendar.HOUR, term); + SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMddHHmmss"); + return dateForm.format(currDate.getTime()); + } + public static String getTargetDay(int term){ + Calendar currDate = Calendar.getInstance(); + currDate.add(Calendar.HOUR, term); + SimpleDateFormat dateForm = new SimpleDateFormat("yyyyMMdd"); + return dateForm.format(currDate.getTime()); + } + public static Date parseDate14(String sDay){ + Date date = null; + if(sDay != null || sDay.length() == 14){ + SimpleDateFormat dateForm = new SimpleDateFormat(DATE_FORMAT_14); + try { + date = dateForm.parse(sDay); + } catch (ParseException e) { + + } + } + + return date; + } + public static int validTimeOut(String sDay){ + int interval = 100000; + Date fromDate = parseDate14(sDay); + Date toDate = parseDate14(currentDate()); + if(fromDate != null && toDate != null){ + long duration = toDate.getTime() - fromDate.getTime(); + interval = (int)(duration / TIMEOUT_DIVIDE); + } + + return interval; + } + // 숫자만 반환하는 함수 + public static String doNumber(String spell){ + String phoneNumber = ""; + if(spell == null){ + return phoneNumber; + } + spell = spell.trim(); + int spell_Length = spell.length(); + if(spell_Length < 1){ + return phoneNumber; + } + for(int i=0;i 0){ + headNum = srcNum.substring(0, index); + tailNum = srcNum.substring((index + 1), srcNum.length()); + + if(tailNum.length() == 0){ + tailNum = "0"; + } + if(tailNum.length() > digit){ + tailNum = tailNum.substring(0, digit); + } + retNum = headNum + "." + tailNum; + } + } + + return retNum; + } + // 수신번호 체크하기 + public static boolean CheckPhone(String src) { + if(src == null || src.trim().length() < 10) { + return false; + } + + if(!src.startsWith("0")) { + return false; + } + + return true; + } + // 문자열 공백 제거 + public static String trim(String obj) { + return StringUtil.trim(obj); + } + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + //System.out.println(QueueUtil.cutFloatNumber("10.2", 2)); + //System.out.println(QueueUtil.isValidTime("20131207173555")); + + /*Calendar currDate = Calendar.getInstance(); + currDate.add(Calendar.HOUR, 0); // 1년후의 시간 + System.out.println("하루전 시간 : " + currDate.getTime());*/ + System.out.println(CommonUtil.isBeforeDate("20131206121212", "20131207121212")); + System.out.println("하루전 : " + CommonUtil.getTargetDay(-24)); + System.out.println(CommonUtil.currentLogDate()); + //Date date = MessageUtil.parseDate14("20141208125958"); + System.out.println("validTimeOut() : " + CommonUtil.validTimeOut("20141209154558")); + } +} diff --git a/src/main/java/com/munjaon/client/util/FileUtil.java b/src/main/java/com/munjaon/client/util/FileUtil.java new file mode 100644 index 0000000..ed4dc46 --- /dev/null +++ b/src/main/java/com/munjaon/client/util/FileUtil.java @@ -0,0 +1,37 @@ +package com.munjaon.client.util; + +import java.io.File; + +/** + * 파일 관련 유틸리티 클래스 + * @author JDS + */ +public class FileUtil { + + public static boolean exists(String sFile) { + return exists( new File(sFile) ); + } + + public static boolean exists(File file) { + return file.exists(); + } + + public static boolean mkdirs(String sPath) { + return mkdirs(sPath, false); + } + + public static boolean mkdirs(String sPath, boolean isFilePath) { + File file = new File(sPath); + + if( isFilePath ) { + file = file.getParentFile(); + } + + if( file.exists() ) { + return true; + } + + return file.mkdirs(); + } + +} diff --git a/src/main/java/com/munjaon/client/util/LogUtil.java b/src/main/java/com/munjaon/client/util/LogUtil.java new file mode 100644 index 0000000..4117ced --- /dev/null +++ b/src/main/java/com/munjaon/client/util/LogUtil.java @@ -0,0 +1,95 @@ +package com.munjaon.client.util; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 로깅 관련 유틸리티 클래스 + * @author JDS + */ +public class LogUtil { + + private final static String sTimeFormat = "[HH:mm:ss.SSS] "; + private final static String sDateFormat = "_yyyyMMdd"; + private final static String sFileExt = ".log"; + + private PrintWriter out; + private String sLogFile; + private String sDate; + + public LogUtil(String sLogFile) { + this.sLogFile = sLogFile; + + if ( sLogFile != null ) { + FileUtil.mkdirs(sLogFile, true); + } + } + + private void open() { + close(); + + if (sLogFile != null) { + try { + out = new PrintWriter( new BufferedWriter( new FileWriter(sLogFile + sDate + sFileExt, true) ), true ); + } catch(Exception e) { + out = null; + } + } + + if( out == null ) { + out = new PrintWriter(System.out, true); + } + } + + public void close() { + if (sLogFile != null && out != null) { + try { + out.close(); + out = null; + } catch (Exception e) { + } + } + } + + public static void log(String sFile, Object oLog) { + LogUtil logger = new LogUtil(sFile); + logger.log(oLog); + logger.close(); + } + + public synchronized void log(Object oLog) { + SimpleDateFormat sdf = new SimpleDateFormat(); + Date date = new Date(); + + sdf.applyPattern(sDateFormat); + String sDates = sdf.format(date); + + sdf.applyPattern(sTimeFormat); + String sTime = sdf.format(date); + + try { + if (!sDates.equals(this.sDate)) { + this.sDate = sDates; + open(); + } + + if (oLog instanceof Exception) { + out.print( sTime ); + ((Exception)oLog).printStackTrace(out); + + if (sLogFile == null) { + ((Exception)oLog).printStackTrace(); + } + } else { + out.println( sTime + oLog ); + } + + out.flush(); + } catch ( Exception e ) { + close(); + } + } +} diff --git a/src/main/java/com/munjaon/client/util/ServiceUtil.java b/src/main/java/com/munjaon/client/util/ServiceUtil.java new file mode 100644 index 0000000..cbfa5e8 --- /dev/null +++ b/src/main/java/com/munjaon/client/util/ServiceUtil.java @@ -0,0 +1,32 @@ +package com.munjaon.client.util; + +public final class ServiceUtil { + /** DB Commit Check Counter */ + public static final int COMMIT_COUNT = 30; + + public static String[] getServiceNames(String[] serviceNames) { + if (serviceNames == null) return null; + for (int i = 0; i < serviceNames.length; i++) { + serviceNames[i] = serviceNames[i].trim(); + } + + return serviceNames; + } + + public static boolean isDuplicate(String[] serviceNames) { + if (serviceNames == null) return false; + + boolean duplicate = false; + for (int i = 0; i < serviceNames.length; i++) { + for (int j = (i + 1); j < serviceNames.length; j++) { + if (serviceNames[i].equals(serviceNames[j])) { + duplicate = true; + break; + } + } + if (duplicate) break; + } + + return duplicate; + } +} diff --git a/src/main/java/com/munjaon/client/util/StringUtil.java b/src/main/java/com/munjaon/client/util/StringUtil.java new file mode 100644 index 0000000..e356786 --- /dev/null +++ b/src/main/java/com/munjaon/client/util/StringUtil.java @@ -0,0 +1,167 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package com.munjaon.client.util; + +import java.text.DecimalFormat; +import java.util.ArrayList; + +/** + * 문자열 관련 유틸리티 클래스 + * @author JDS + */ +public final class StringUtil { + + public static final String SystemEncoding = getSystemEncoding(); + + public static String getSystemEncoding() { + return (new java.io.OutputStreamWriter(System.out)).getEncoding(); + } + + public static String trim(byte[] obj) { + if( obj == null || obj.length == 0 ) { + return ""; + } + + return (new String(obj)).trim(); + } + + public static String trim(Object obj) { + return trim(obj, ""); + } + + public static String trim(Object obj, String dflt) { + if( obj == null ) { + return dflt; + } + + return ((String)obj).trim(); + } + + public static String ltrim(byte[] obj) { + return ltrim(new String(obj)); + } + + public static String ltrim(String obj) { + return ltrim(obj.toCharArray()); + } + + public static String ltrim(char[] obj) { + int len = obj.length; + int idx = 0; + + while( idx < len && obj[idx] <= ' ' ) { + idx++; + } + + return new String(obj, idx, len-idx); + } + + public static String rtrim(byte[] obj) { + return rtrim(new String(obj)); + } + + public static String rtrim(String obj) { + return rtrim(obj.toCharArray()); + } + + public static String rtrim(char[] obj) { + int len = obj.length; + int idx = len-1; + + while( idx >= 0 && obj[idx] <= ' ' ) { + idx--; + } + + return new String(obj, 0, idx+1); + } + + public static String replaceAll(String src, String from, String to) { + StringBuilder sbuf = new StringBuilder(); + + int len = from.length(); + int idx = 0; + int stx = 0; + + while( (idx=src.indexOf(from, stx)) > -1 ) { + sbuf.append(src.substring(stx, idx)); + sbuf.append(to); + stx=idx+len; + } + + sbuf.append(src.substring(stx)); + + return sbuf.toString(); + } + + public static String[] split(String sSrc, String sDelim) { + ArrayList aList = new ArrayList(); + + String sTmp; + int len = sDelim.length(); + int idx = 0; + int stx = 0; + + while( (idx=sSrc.indexOf(sDelim, stx)) > -1 ) { + sTmp = sSrc.substring(stx, idx); + aList.add(sTmp); + stx=idx+len; + } + + if( stx <= sSrc.length() ) { + aList.add(sSrc.substring(stx)); + } + + String[] sRet = new String[aList.size()]; + + for( int i=0; i" + + " \r\n" + + " " + + " Gambardella, Matthew " + + "XML Developer's Guide" + + " Computer" + + " 44.95 " + + "2000-10-01 " + + "An in-depth look at creating applications with XML. " + + "" + + " " + + " Ralls, Kim" + + " Midnight Rain" + + " Fantasy" + + " 5.95" + + " 2000-12-16" + + " A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world." + + " \r\n" + + "\r\n"; + try { + + SAXBuilder sax = new SAXBuilder(); + // String that contains XML + Document doc = (Document) sax.build(new File("C:\\Docs\\JDS\\ITN\\MMS01Header.xml")); +// org.jdom2.Document doc = sax.build(new StringReader(xml)); + + Element rootNode = doc.getRootElement(); + List bookElements = rootNode.getChildren(); + System.out.println("bookElements: " + bookElements); + for(Element bookElement : bookElements){ + String name = bookElement.getName(); + String value = bookElement.getValue(); + System.out.println(name + " : " + value); + } + + } catch (IOException | JDOMException e) { + e.printStackTrace(); + } + return document; + } + + private static void writeSimpleXml() throws JDOMException, IOException { + + String xml = "mkyong"; + SAXBuilder sb = new SAXBuilder(); + Document doc = sb.build(new StringReader(xml)); + + + Document docFile = new Document(); + + Element rootElement = new Element("ReadQueue"); + rootElement.addContent(new Element("createDate").setText("20240527")); + rootElement.addContent(new Element("PopCounter").setText(Integer.toString(0))); + + docFile.setRootElement(rootElement); + + // default in compact mode + // XMLOutputter xmlOutputter = new XMLOutputter(); + + // pretty print format + XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); + + // output to console + FileOutputStream fileOutputStream = new FileOutputStream("C:\\Docs\\JDS\\ITN\\file.xml"); + xmlOutputter.output(docFile, fileOutputStream); + + } + public static void main(String[] args) throws IOException, JDOMException { +// XmlUtil.getDOMParsedDocument("C:\\Docs\\JDS\\ITN\\MMS01Header.xml"); + XmlUtil.getSaxParsedDocument("C:\\Docs\\JDS\\ITN\\MMS01Header.xml"); + XmlUtil.writeSimpleXml(); + } +} diff --git a/src/main/resources/sqlmap/mariadb/mariadb_sql.xml b/src/main/resources/sqlmap/mariadb/mariadb_sql.xml index d9fbeb6..88729ff 100644 --- a/src/main/resources/sqlmap/mariadb/mariadb_sql.xml +++ b/src/main/resources/sqlmap/mariadb/mariadb_sql.xml @@ -7,18 +7,25 @@