Compare commits

..

No commits in common. "master" and "main" have entirely different histories.
master ... main

137 changed files with 302 additions and 10810 deletions

View File

@ -24,7 +24,7 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-batch'
// implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.3'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
@ -45,12 +45,8 @@ dependencies {
implementation 'org.apache.commons:commons-configuration2:2.10.1'
// https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils
implementation 'commons-beanutils:commons-beanutils:1.9.4'
// https://mvnrepository.com/artifact/org.jdom/jdom2
implementation 'org.jdom:jdom2:2.0.6.1'
implementation("com.slack.api:bolt:1.40.3")
implementation("com.slack.api:bolt-servlet:1.40.3")
implementation("com.slack.api:bolt-jetty:1.40.3")
// https://mvnrepository.com/artifact/io.netty/netty-all
implementation 'io.netty:netty-all:4.1.42.Final'
testCompileOnly 'org.projectlombok:lombok'
testAnnotationProcessor 'org.projectlombok:lombok'

View File

@ -2,14 +2,22 @@ package com.munjaon.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableCaching
@EnableScheduling
@SpringBootApplication
public class MunjaonServerApplication {
public class MunjaonServerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(MunjaonServerApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return super.configure(builder);
}
}

View File

@ -0,0 +1,33 @@
package com.munjaon.server.api.controller;
import com.munjaon.server.api.dto.SampleDto;
import com.munjaon.server.api.dto.base.ApiResponse;
import com.munjaon.server.api.service.SampleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RequestMapping("/api")
@RestController
@RequiredArgsConstructor
public class SampleController {
private final SampleService sampleService;
@PostMapping("/sample")
public ResponseEntity postSample(@RequestBody SampleDto sample) throws ConfigurationException {
log.debug("sample : {}", sampleService.get());
System.out.println("command : " + sample.getCommand());
/* 설정 Load */
sampleService.printConfig();
return new ResponseEntity(ApiResponse.toResponse(200, "OK", sample), HttpStatus.OK);
}
}

View File

@ -0,0 +1,12 @@
package com.munjaon.server.api.dto;
import com.munjaon.server.api.dto.base.BaseDto;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class SampleDto extends BaseDto {
}

View File

@ -0,0 +1,31 @@
package com.munjaon.server.api.dto.base;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ApiResponse<T> {
/* 응답코드 */
private Integer code;
/* 응답 메시지 */
private String message;
/* Response 객체 */
private T data;
public ApiResponse(final Integer code, final String message) {
this.code = code;
this.message = message;
}
public static <T> ApiResponse<T> toResponse(final Integer code, final String message, final T t) {
return ApiResponse.<T>builder().code(code)
.message(message)
.data(t)
.build();
}
}

View File

@ -0,0 +1,13 @@
package com.munjaon.server.api.dto.base;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class BaseDto {
protected String command;
protected String authKey;
}

View File

@ -0,0 +1,8 @@
package com.munjaon.server.api.mapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SampleMapper {
int get();
}

View File

@ -0,0 +1,31 @@
package com.munjaon.server.api.service;
import com.munjaon.server.api.mapper.SampleMapper;
import com.munjaon.server.cache.service.MemberService;
import com.munjaon.server.config.ServerConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class SampleService {
private final SampleMapper sampleMapper;
private final ServerConfig serverConfig;
private final MemberService memberService;
public int get() {
return sampleMapper.get();
}
public void printConfig() throws ConfigurationException {
log.info("server.run : {}", serverConfig.getString("server.run"));
log.info("sms.queue.count : {}", serverConfig.getInt("sms.queue.count"));
log.info("member list : {}", memberService.list());
log.info("member get : {}", memberService.get("006star"));
}
}

View File

@ -9,8 +9,9 @@ import lombok.ToString;
@ToString
public class MemberDto {
private String mberId;
private String accessKey;
private String esntlId;
private String mberSttus;
private String dept;
private float shortPrice;
private float longPrice;
private float picturePrice;
@ -20,23 +21,6 @@ public class MemberDto {
private float kakaoFtPrice;
private float kakaoFtImgPrice;
private float kakaoFtWideImgPrice;
private String smsUseYn;
private String lmsUseYn;
private String mmsUseYn;
private String kakaoAtUseYn;
private String kakaoFtUseYn;
private int smsLimitCount;
private int lmsLimitCount;
private int mmsLimitCount;
private int kakaoAtLimitCount;
private int kakaoFtLimitCount;
private String smsAgentCode;
private String lmsAgentCode;
private String mmsAgentCode;
private String kakaoAtAgentCode;
private String kakaoFtAgentCode;
private String ipLimitYn;
private String allowIpBasic;
private String allowIpExtend;
private float faxPrice;
private float userMoney;
}

View File

@ -1,15 +0,0 @@
package com.munjaon.server.cache.enums;
import lombok.Getter;
@Getter
public enum CacheService {
LOGIN_SERVICE,
REPORT_SERVICE;
private Object service;
public void setService(Object service) {
this.service = service;
}
}

View File

@ -11,8 +11,7 @@ public interface MemberMapper {
* 회원테이블 마지막으로 변경된 시간 조회
* @return
*/
String getMemberLastModifiedTime(String tableSchema);
String getConfigLastModifiedTime(String tableSchema);
String getLastModifiedTime(String tableSchema);
/**
* 회원 전체 목록

View File

@ -1,15 +0,0 @@
package com.munjaon.server.cache.mapper;
import com.munjaon.server.server.dto.ReportDto;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface ReportMapper {
ReportDto getReportForUser(String userId);
List<ReportDto> getReportListForUser(String userId);
int deleteReport(String msgId);
int deleteBulkReport(Map<String, Object> reqMap);
}

View File

@ -1,11 +0,0 @@
package com.munjaon.server.cache.mapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SerialNoMapper {
String getSerialNoForLock();
int insert();
int update();
String getSerialNo();
}

View File

@ -1,29 +0,0 @@
package com.munjaon.server.cache.service;
import com.munjaon.server.cache.enums.CacheService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.EnumSet;
@Component
public class CacheServiceInjector {
@Autowired
private MemberService memberService;
@Autowired
private ReportService reportService;
@PostConstruct
public void postConstruct() {
for (CacheService svc : EnumSet.allOf(CacheService.class)) {
switch (svc) {
case LOGIN_SERVICE : svc.setService(memberService);
break;
case REPORT_SERVICE: svc.setService(reportService);
break;
default:break;
}
}
}
}

View File

@ -21,12 +21,8 @@ public class MemberService {
* 회원테이블 마지막으로 변경된 시간 조회
* @return
*/
public String getMemberLastModifiedTime(String tableSchema) {
return memberMapper.getMemberLastModifiedTime(tableSchema);
}
public String getConfigLastModifiedTime(String tableSchema) {
return memberMapper.getConfigLastModifiedTime(tableSchema);
public String getLastModifiedTime(String tableSchema) {
return memberMapper.getLastModifiedTime(tableSchema);
}
/**

View File

@ -1,42 +0,0 @@
package com.munjaon.server.cache.service;
import com.munjaon.server.cache.mapper.ReportMapper;
import com.munjaon.server.server.dto.ReportDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
public class ReportService {
private final ReportMapper reportMapper;
public ReportDto getReportForUser(String userId) {
return reportMapper.getReportForUser(userId);
}
public List<ReportDto> getReportListForUser(String userId) {
return reportMapper.getReportListForUser(userId);
}
public int deleteReport(String msgId) {
return reportMapper.deleteReport(msgId);
}
public int deleteBulkReport(String msgId, String userId) {
Map<String, Object> reqMap = new HashMap<>();
reqMap.put("msgId", msgId);
reqMap.put("userId", userId);
return deleteBulkReport(reqMap);
}
public int deleteBulkReport(Map<String, Object> reqMap) {
return reportMapper.deleteBulkReport(reqMap);
}
}

View File

@ -1,25 +0,0 @@
package com.munjaon.server.cache.service;
import com.munjaon.server.cache.mapper.SerialNoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
public class SerialNoService {
private final SerialNoMapper serialNoMapper;
@Transactional
public String getSerialNo() {
if (serialNoMapper.getSerialNoForLock() == null) {
serialNoMapper.insert();
} else {
serialNoMapper.update();
}
return serialNoMapper.getSerialNo();
}
}

View File

@ -1,6 +1,5 @@
package com.munjaon.server.config;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
@ -29,7 +28,7 @@ public class DataSourceConfig {
@Bean(name = "datasource")
@ConfigurationProperties(prefix = "spring.datasource.server")
public DataSource dataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
return DataSourceBuilder.create().build();
}
@Primary

View File

@ -1,355 +0,0 @@
package com.munjaon.server.config;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.queue.pool.*;
import com.munjaon.server.server.service.*;
import com.munjaon.server.util.ServiceUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
@Slf4j
@Configuration
@RequiredArgsConstructor
public class RunnerConfiguration {
private final ServerConfig serverConfig;
@Bean
@Order(1)
public CommandLineRunner getRunnerBeanForProperty() {
System.setProperty("PROPS", serverConfig.getServerProperyFile());
System.setProperty("ROOTPATH", serverConfig.getServerRootPath());
PropertyLoader.load();
/* Serial queue 초기화 */
SerialQueuePool queueInstance = SerialQueuePool.getInstance();
try {
SerialQueue serialQueue = new SerialQueue();
queueInstance.setSerialQueue(serialQueue);
} catch (Exception e) {
e.printStackTrace();
}
return args -> System.out.println("Runner Bean #1 : " + serverConfig.getServerProperyFile());
}
@Bean
@Order(2)
public CommandLineRunner getRunnerBeanForSmsQueue() {
try {
String[] svcArray = ServiceUtil.getServiceNames(serverConfig.getStringArray("SMS.SERVICE_LIST"));
if (svcArray == null || svcArray.length == 0) {
log.info("SMS service list is empty");
} else {
if (ServiceUtil.isDuplicate(svcArray)) {
log.info("SMS service list is duplicated");
} else {
for (String svc : svcArray) {
log.info("SERVICE CREATE : {}", svc);
QueueInfo queueInfo = QueueInfo.builder().queueName(svc).serviceType("SMS").queuePath(serverConfig.getString("SMS.QUEUE_PATH")).build();
SmsWriteQueue smsWriteQueue = new SmsWriteQueue(queueInfo);
SmsReadQueue smsReadQueue = new SmsReadQueue(queueInfo);
QueueServerService queueServerService = new QueueServerService(svc, smsWriteQueue, smsReadQueue);
ShutdownService shutdownService = new ShutdownService(queueServerService);
Runtime.getRuntime().addShutdownHook(shutdownService);
queueServerService.start();
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean #2");
}
@Bean
@Order(2)
public CommandLineRunner getRunnerBeanForLmsQueue() {
try {
String[] svcArray = ServiceUtil.getServiceNames(serverConfig.getStringArray("LMS.SERVICE_LIST"));
if (svcArray == null || svcArray.length == 0) {
log.info("LMS service list is empty");
} else {
if (ServiceUtil.isDuplicate(svcArray)) {
log.info("LMS service list is duplicated");
} else {
for (String svc : svcArray) {
log.info("SERVICE CREATE : {}", svc);
QueueInfo queueInfo = QueueInfo.builder().queueName(svc).serviceType("LMS").queuePath(serverConfig.getString("LMS.QUEUE_PATH")).build();
LmsWriteQueue lmsWriteQueue = new LmsWriteQueue(queueInfo);
LmsReadQueue lmsReadQueue = new LmsReadQueue(queueInfo);
QueueServerService queueServerService = new QueueServerService(svc, lmsWriteQueue, lmsReadQueue);
ShutdownService shutdownService = new ShutdownService(queueServerService);
Runtime.getRuntime().addShutdownHook(shutdownService);
queueServerService.start();
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean #2");
}
@Bean
@Order(2)
public CommandLineRunner getRunnerBeanForMmsQueue() {
try {
String[] svcArray = ServiceUtil.getServiceNames(serverConfig.getStringArray("MMS.SERVICE_LIST"));
if (svcArray == null || svcArray.length == 0) {
log.info("MMS service list is empty");
} else {
if (ServiceUtil.isDuplicate(svcArray)) {
log.info("MMS service list is duplicated");
} else {
for (String svc : svcArray) {
log.info("SERVICE CREATE : {}", svc);
QueueInfo queueInfo = QueueInfo.builder().queueName(svc).serviceType("MMS").queuePath(serverConfig.getString("MMS.QUEUE_PATH")).build();
MmsWriteQueue mmsWriteQueue = new MmsWriteQueue(queueInfo);
MmsReadQueue mmsReadQueue = new MmsReadQueue(queueInfo);
QueueServerService queueServerService = new QueueServerService(svc, mmsWriteQueue, mmsReadQueue);
ShutdownService shutdownService = new ShutdownService(queueServerService);
Runtime.getRuntime().addShutdownHook(shutdownService);
queueServerService.start();
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean #2");
}
@Bean
@Order(2)
public CommandLineRunner getRunnerBeanForKatQueue() {
try {
String[] svcArray = ServiceUtil.getServiceNames(serverConfig.getStringArray("KAT.SERVICE_LIST"));
if (svcArray == null || svcArray.length == 0) {
log.info("KAT service list is empty");
} else {
if (ServiceUtil.isDuplicate(svcArray)) {
log.info("KAT service list is duplicated");
} else {
for (String svc : svcArray) {
log.info("SERVICE CREATE : {}", svc);
QueueInfo queueInfo = QueueInfo.builder().queueName(svc).serviceType("KAT").queuePath(serverConfig.getString("KAT.QUEUE_PATH")).build();
KakaoAlarmWriteQueue katWriteQueue = new KakaoAlarmWriteQueue(queueInfo);
KakaoAlarmReadQueue katReadQueue = new KakaoAlarmReadQueue(queueInfo);
QueueServerService queueServerService = new QueueServerService(svc, katWriteQueue, katReadQueue);
ShutdownService shutdownService = new ShutdownService(queueServerService);
Runtime.getRuntime().addShutdownHook(shutdownService);
queueServerService.start();
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean #2");
}
@Bean
@Order(2)
public CommandLineRunner getRunnerBeanForKftQueue() {
try {
String[] svcArray = ServiceUtil.getServiceNames(serverConfig.getStringArray("KFT.SERVICE_LIST"));
if (svcArray == null || svcArray.length == 0) {
log.info("KFT service list is empty");
} else {
if (ServiceUtil.isDuplicate(svcArray)) {
log.info("KFT service list is duplicated");
} else {
for (String svc : svcArray) {
log.info("SERVICE CREATE : {}", svc);
QueueInfo queueInfo = QueueInfo.builder().queueName(svc).serviceType("KFT").queuePath(serverConfig.getString("KFT.QUEUE_PATH")).build();
KakaoFriendWriteQueue kftWriteQueue = new KakaoFriendWriteQueue(queueInfo);
KakaoFriendReadQueue kftReadQueue = new KakaoFriendReadQueue(queueInfo);
QueueServerService queueServerService = new QueueServerService(svc, kftWriteQueue, kftReadQueue);
ShutdownService shutdownService = new ShutdownService(queueServerService);
Runtime.getRuntime().addShutdownHook(shutdownService);
queueServerService.start();
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean #2");
}
@Bean
@Order(3)
public CommandLineRunner getRunnerBeanForSmsCollector() {
try {
String serviceName = "SMS_COLLECTOR";
String serviceType = serverConfig.getString(serviceName + ".SERVICE_TYPE");
String msgKeyPath = serverConfig.getString(serviceName + ".MSGID_QUEUE");
int port = serverConfig.getInt(serviceName + ".SERVICE_PORT");
int msgIdQueueSize = serverConfig.getInt(serviceName + ".MSGID_QUEUE_SIZE");
// CollectBackServerService collectServerService = new CollectBackServerService(serviceName, serviceType, port);
CollectServer collectServer = new CollectServer(serviceName, serviceType, port, msgKeyPath, msgIdQueueSize);
ShutdownService shutdownService = new ShutdownService(collectServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
collectServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean SmsCollector #3");
}
@Bean
@Order(3)
public CommandLineRunner getRunnerBeanForLmsCollector() {
try {
String serviceName = "LMS_COLLECTOR";
String serviceType = serverConfig.getString(serviceName + ".SERVICE_TYPE");
String msgKeyPath = serverConfig.getString(serviceName + ".MSGID_QUEUE");
int port = serverConfig.getInt(serviceName + ".SERVICE_PORT");
int msgIdQueueSize = serverConfig.getInt(serviceName + ".MSGID_QUEUE_SIZE");
// CollectBackServerService collectServerService = new CollectBackServerService(serviceName, serviceType, port);
CollectServer collectServer = new CollectServer(serviceName, serviceType, port, msgKeyPath, msgIdQueueSize);
ShutdownService shutdownService = new ShutdownService(collectServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
collectServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean SmsCollector #3");
}
@Bean
@Order(3)
public CommandLineRunner getRunnerBeanForMmsCollector() {
try {
String serviceName = "MMS_COLLECTOR";
String serviceType = serverConfig.getString(serviceName + ".SERVICE_TYPE");
String msgKeyPath = serverConfig.getString(serviceName + ".MSGID_QUEUE");
int port = serverConfig.getInt(serviceName + ".SERVICE_PORT");
int msgIdQueueSize = serverConfig.getInt(serviceName + ".MSGID_QUEUE_SIZE");
// CollectBackServerService collectServerService = new CollectBackServerService(serviceName, serviceType, port);
CollectServer collectServer = new CollectServer(serviceName, serviceType, port, msgKeyPath, msgIdQueueSize);
ShutdownService shutdownService = new ShutdownService(collectServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
collectServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean SmsCollector #3");
}
@Bean
@Order(3)
public CommandLineRunner getRunnerBeanForKatCollector() {
try {
String serviceName = "KAT_COLLECTOR";
String serviceType = serverConfig.getString(serviceName + ".SERVICE_TYPE");
String msgKeyPath = serverConfig.getString(serviceName + ".MSGID_QUEUE");
int port = serverConfig.getInt(serviceName + ".SERVICE_PORT");
int msgIdQueueSize = serverConfig.getInt(serviceName + ".MSGID_QUEUE_SIZE");
// CollectBackServerService collectServerService = new CollectBackServerService(serviceName, serviceType, port);
CollectServer collectServer = new CollectServer(serviceName, serviceType, port, msgKeyPath, msgIdQueueSize);
ShutdownService shutdownService = new ShutdownService(collectServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
collectServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean SmsCollector #3");
}
@Bean
@Order(3)
public CommandLineRunner getRunnerBeanForKftCollector() {
try {
String serviceName = "KFT_COLLECTOR";
String serviceType = serverConfig.getString(serviceName + ".SERVICE_TYPE");
String msgKeyPath = serverConfig.getString(serviceName + ".MSGID_QUEUE");
int port = serverConfig.getInt(serviceName + ".SERVICE_PORT");
int msgIdQueueSize = serverConfig.getInt(serviceName + ".MSGID_QUEUE_SIZE");
// CollectBackServerService collectServerService = new CollectBackServerService(serviceName, serviceType, port);
CollectServer collectServer = new CollectServer(serviceName, serviceType, port, msgKeyPath, msgIdQueueSize);
ShutdownService shutdownService = new ShutdownService(collectServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
collectServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean SmsCollector #3");
}
@Bean
@Order(3)
public CommandLineRunner getRunnerBeanForReporter() {
try {
String serviceName = "REPORTER";
int port = serverConfig.getInt(serviceName + ".SERVICE_PORT");
ReportServer reportServer = new ReportServer(serviceName, port);
ShutdownService shutdownService = new ShutdownService(reportServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
reportServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean Reporter #3");
}
@Bean
@Order(4)
public CommandLineRunner getRunnerBeanForReportQueue() {
try {
String serviceName = "REPORT_QUEUE";
ReportQueueServer reportQueueServer = new ReportQueueServer(serviceName);
ShutdownService shutdownService = new ShutdownService(reportQueueServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
reportQueueServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean ReporterQueue #4");
}
@Bean
@Order(5)
public CommandLineRunner getRunnerBeanForMonitor() {
try {
String serviceName = "HEALTH";
HealthCheckServer healthCheckServer = new HealthCheckServer(serviceName);
ShutdownService shutdownService = new ShutdownService(healthCheckServer);
Runtime.getRuntime().addShutdownHook(shutdownService);
healthCheckServer.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
return args -> System.out.println("Runner Bean Monitor #5");
}
}

View File

@ -1,7 +1,6 @@
package com.munjaon.server.config;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
@ -20,14 +19,9 @@ import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class ServerConfig {
@Getter
@Value("${agent.server-property-file}")
private String serverProperyFile;
@Getter
@Value("${agent.root-path}")
private String serverRootPath;
private ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder;
@PostConstruct
@ -53,13 +47,4 @@ public class ServerConfig {
public int getInt(String key) throws ConfigurationException {
return builder.getConfiguration().getInt(key, 3);
}
public String[] getStringArray(String key) throws ConfigurationException {
return getStringArray(key, ",");
}
public String[] getStringArray(String key, String regExp) throws ConfigurationException {
String value = getString(key);
return value == null ? null : value.split(regExp);
}
}

View File

@ -1,63 +0,0 @@
package com.munjaon.server.config;
import lombok.Getter;
@Getter
public enum ServiceCode {
OK(200, "Success"),
MSG_ERROR_USERID(300, "userId is Null OR is Over Limit Byte"),
MSG_ERROR_FEETYPE(301, "feeType is Null OR is Over Limit Byte"),
MSG_ERROR_UNITCOST(302, "unitCost is Null OR is Over Limit Byte"),
MSG_ERROR_MSGGROUPID(303, "msgGroupID is Null OR is Over Limit Byte"),
MSG_ERROR_USERMSGID(304, "userMsgID is Null OR is Over Limit Byte"),
MSG_ERROR_SERVICETYPE(305, "serviceType is Null OR is Over Limit Byte"),
MSG_ERROR_SENDSTATUS(306, "sendStatus is Null OR is Over Limit Byte"),
MSG_ERROR_USERSENDER(307, "userSender is Null OR is Over Limit Byte"),
MSG_ERROR_USERRECEIVER(308, "userReceiver is Null OR is Over Limit Byte"),
MSG_ERROR_REQUESTDT(309, "requestDt is Null OR is Over Limit Byte"),
MSG_ERROR_REMOTEIP(310, "remoteIP is Null OR is Over Limit Byte"),
MSG_ERROR_ROUTERSEQ(311, "routerSeq is Null OR is Over Limit Byte"),
/* SMS 메시지 */
MSG_ERROR_SMS_MESSAGE(400, "SMS Message is Null OR is Over Limit Byte"),
/* LMS, MMS, KAKAO 제목, 메시지 */
MSG_ERROR_MEDIA_SUBJECT(500, "LMS, MMS, KAKAO Subject is Null OR is Over Limit Byte"),
MSG_ERROR_MEDIA_MESSAGE(501, "LMS, MMS, KAKAO Message is Null OR is Over Limit Byte"),
/* 카카오 알림톡, 친구톡 메시지, KAKAO_SENDER_KEY, KAKAO_TEMPLATE_CODE */
MSG_ERROR_KAKAO_SENDER_KEY(600, "KAKAO_SENDER_KEY is Null OR is Over Limit Byte"),
MSG_ERROR_KAKAO_TEMPLATE_CODE(601, "KAKAO_TEMPLATE_CODE is Null OR is Over Limit Byte"),
/* 리포트 관련 에러 메시지 */
MSG_ERROR_REPORT(800, "REPORT DATA is Null OR is invalid"),
MSG_ERROR_REPORT_MSG_ID(801, "MSG_ID is Null OR is Over Limit Byte"),
MSG_ERROR_REPORT_AGENT_CODE(802, "AGENT_CODE is Null OR is Over Limit Byte"),
MSG_ERROR_REPORT_SEND_TIME(803, "SEND_TIME is Null OR is Over Limit Byte"),
MSG_ERROR_REPORT_TELECOM(804, "TELECOM is Null OR is Over Limit Byte"),
MSG_ERROR_REPORT_RESULT(805, "RESULT is Null OR is Over Limit Byte"),
ETC_ERROR(999, "ETC ERROR");
private Integer code;
private String message;
ServiceCode(Integer code, String msg) {
this.code = code;
this.message = msg;
}
public static String getMessage(Integer code) {
if (code == null) {
return "etc";
}
for (ServiceCode resCode : values()) {
if (resCode.getCode().equals(code)) {
return resCode.getMessage();
}
}
return "etc";
}
}

View File

@ -0,0 +1,15 @@
package com.munjaon.server.netty.config;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.nio.NioEventLoopGroup;
import java.net.InetSocketAddress;
public interface BaseConfig {
NioEventLoopGroup bossGroup();
NioEventLoopGroup workerGroup();
InetSocketAddress port();
ServerBootstrap serverBootstrap();
ChannelInboundHandlerAdapter handler();
}

View File

@ -0,0 +1,21 @@
package com.munjaon.server.netty.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class SampleHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
}
}

View File

@ -0,0 +1,11 @@
package com.munjaon.server.netty.init;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
public class SampleNettyInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel channel) throws Exception {
}
}

View File

@ -1,46 +0,0 @@
package com.munjaon.server.queue.config;
public final class BodyCommonConfig {
/* 회원 아이디 (Length : 20 / Position : 0) */
public static final int USERID_BYTE_LENGTH = 20;
public static final int USERID_BYTE_POSITION = 0;
/* 요금제 정보 (Length : 1 / Position : 20) (선불 : P(Prepayment) / 후불 : D(Detered Payment)) */
public static final int FEETYPE_BYTE_LENGTH = 1;
public static final int FEETYPE_BYTE_POSITION = USERID_BYTE_POSITION + USERID_BYTE_LENGTH;
/* 단가정보 (Length : 10 / Position : 21) */
public static final int UNITCOST_BYTE_LENGTH = 10;
public static final int UNITCOST_BYTE_POSITION = FEETYPE_BYTE_POSITION + FEETYPE_BYTE_LENGTH;
/* 메시지 그룹 아이디 (문자온 메시지 테이블에서 그룹핑할 메시지ID) (Length : 20 / Position : 31) */
public static final int MSGGROUPID_BYTE_LENGTH = 20;
public static final int MSGGROUPID_BYTE_POSITION = UNITCOST_BYTE_POSITION + UNITCOST_BYTE_LENGTH;
/* 고객사 메시지 ID 길이 (Length : 20 / Position : 51) */
public static final int MSGID_BYTE_LENGTH = 20;
public static final int MSGID_BYTE_POSITION = MSGGROUPID_BYTE_POSITION + MSGGROUPID_BYTE_LENGTH;
/* 서비스타입(4:SMS / 6:LMS, MMS / 8:카카오 알림톡 / 9:카카오 친구톡) (Length : 1 / Position : 71) */
public static final int SERVICETYPE_BYTE_LENGTH = 1;
public static final int SERVICETYPE_BYTE_POSITION = MSGID_BYTE_POSITION + MSGID_BYTE_LENGTH;
/* 결과코드 (Length : 5 / Position : 72) */
public static final int SENDSTATUS_BYTE_LENGTH = 5;
public static final int SENDSTATUS_BYTE_POSITION = SERVICETYPE_BYTE_POSITION + SERVICETYPE_BYTE_LENGTH;
/* 회신번호 (Length : 12 / Position : 77) */
public static final int SENDER_BYTE_LENGTH = 12;
public static final int SENDER_BYTE_POSITION = SENDSTATUS_BYTE_POSITION + SENDSTATUS_BYTE_LENGTH;
/* 수신번호 (Length : 12 / Position : 89) */
public static final int RECEIVER_BYTE_LENGTH = 12;
public static final int RECEIVER_BYTE_POSITION = SENDER_BYTE_POSITION + SENDER_BYTE_LENGTH;
/* 예약시간 (Length : 15 / Position : 101) */
public static final int RESERVEDT_BYTE_LENGTH = 15;
public static final int RESERVEDT_BYTE_POSITION = RECEIVER_BYTE_POSITION + RECEIVER_BYTE_LENGTH;
/* 요청시간 (Length : 15 / Position : 116) */
public static final int REQUESTDT_BYTE_LENGTH = 15;
public static final int REQUESTDT_BYTE_POSITION = RESERVEDT_BYTE_POSITION + RESERVEDT_BYTE_LENGTH;
/* 원격접속지 주소 (Length : 25 / Position : 131) */
public static final int REMOTEIP_BYTE_LENGTH = 25;
public static final int REMOTEIP_BYTE_POSITION = REQUESTDT_BYTE_POSITION + REQUESTDT_BYTE_LENGTH;
/* 에이전트 코드 (Length : 5 / Position : 156) */
public static final int AGENT_CODE_BYTE_LENGTH = 5;
public static final int AGENT_CODE_BYTE_POSITION = REMOTEIP_BYTE_POSITION + REMOTEIP_BYTE_LENGTH;
/* Body 전체 길이 */
public static final int COMMON_SUM_BYTE_LENGTH = USERID_BYTE_LENGTH + FEETYPE_BYTE_LENGTH + UNITCOST_BYTE_LENGTH + MSGGROUPID_BYTE_LENGTH + MSGID_BYTE_LENGTH + SERVICETYPE_BYTE_LENGTH + SENDSTATUS_BYTE_LENGTH + SENDER_BYTE_LENGTH + RECEIVER_BYTE_LENGTH + RESERVEDT_BYTE_LENGTH + REQUESTDT_BYTE_LENGTH + REMOTEIP_BYTE_LENGTH + AGENT_CODE_BYTE_LENGTH;
}

View File

@ -1,22 +0,0 @@
package com.munjaon.server.queue.config;
public final class KakaoBodyConfig {
/* 제목 (Length : 60 / Position : 161) */
public static final int SUBJECT_BYTE_LENGTH = 60;
public static final int SUBJECT_BYTE_POSITION = BodyCommonConfig.AGENT_CODE_BYTE_POSITION + BodyCommonConfig.AGENT_CODE_BYTE_LENGTH;
/* LMS/MMS Message (Length : 2000 / Position : 221) */
public static final int MEDIA_MSG_BYTE_LENGTH = 2000;
public static final int MEDIA_MSG_BYTE_POSITION = SUBJECT_BYTE_POSITION + SUBJECT_BYTE_LENGTH;
/* KAKAO_SENDER_KEY (Length : 40 / Position : 2221) */
public static final int KAKAO_SENDER_KEY_BYTE_LENGTH = 40;
public static final int KAKAO_SENDER_KEY_BYTE_POSITION = MEDIA_MSG_BYTE_POSITION + MEDIA_MSG_BYTE_LENGTH;
/* KAKAO_TEMPLATE_CODE (Length : 64 / Position : 2261) */
public static final int KAKAO_TEMPLATE_CODE_BYTE_LENGTH = 64;
public static final int KAKAO_TEMPLATE_CODE_BYTE_POSITION = KAKAO_SENDER_KEY_BYTE_POSITION + KAKAO_SENDER_KEY_BYTE_LENGTH;
/* JSON 파일 (Length : 128 / Position : 2222) */
public static final int FILENAME_JSON_BYTE_LENGTH = 128;
public static final int FILENAME_JSON_BYTE_POSITION = KAKAO_TEMPLATE_CODE_BYTE_POSITION + KAKAO_TEMPLATE_CODE_BYTE_LENGTH;
/* KAKAO Body 길이 */
public static final int KAKAO_SUM_BYTE_LENGTH = BodyCommonConfig.COMMON_SUM_BYTE_LENGTH + SUBJECT_BYTE_LENGTH + MEDIA_MSG_BYTE_LENGTH + KAKAO_SENDER_KEY_BYTE_LENGTH + KAKAO_TEMPLATE_CODE_BYTE_LENGTH + FILENAME_JSON_BYTE_LENGTH;
}

View File

@ -1,27 +0,0 @@
package com.munjaon.server.queue.config;
public final class MediaBodyConfig {
/* 제목 (Length : 60 / Position : 161) */
public static final int SUBJECT_BYTE_LENGTH = 60;
public static final int SUBJECT_BYTE_POSITION = BodyCommonConfig.AGENT_CODE_BYTE_POSITION + BodyCommonConfig.AGENT_CODE_BYTE_LENGTH;
/* LMS/MMS Message (Length : 2000 / Position : 221) */
public static final int MEDIA_MSG_BYTE_LENGTH = 2000;
public static final int MEDIA_MSG_BYTE_POSITION = SUBJECT_BYTE_POSITION + SUBJECT_BYTE_LENGTH;
/* 파일카운트 (Length : 1 / Position : 2221) */
public static final int FILECNT_BYTE_LENGTH = 1;
public static final int FILECNT_BYTE_POSITION = MEDIA_MSG_BYTE_POSITION + MEDIA_MSG_BYTE_LENGTH;
/* 파일명 #1 (Length : 128 / Position : 2222) */
public static final int FILENAME_ONE_BYTE_LENGTH = 128;
public static final int FILENAME_ONE_BYTE_POSITION = FILECNT_BYTE_POSITION + FILECNT_BYTE_LENGTH;
/* 파일명 #2 (Length : 128 / Position : 2350) */
public static final int FILENAME_TWO_BYTE_LENGTH = 128;
public static final int FILENAME_TWO_BYTE_POSITION = FILENAME_ONE_BYTE_POSITION + FILENAME_ONE_BYTE_LENGTH;
/* 파일명 #3 (Length : 128 / Position : 2478) */
public static final int FILENAME_THREE_BYTE_LENGTH = 128;
public static final int FILENAME_THREE_BYTE_POSITION = FILENAME_TWO_BYTE_POSITION + FILENAME_TWO_BYTE_LENGTH;
/* LMS Body 길이 */
public static final int LMS_SUM_BYTE_LENGTH = BodyCommonConfig.COMMON_SUM_BYTE_LENGTH + SUBJECT_BYTE_LENGTH + MEDIA_MSG_BYTE_LENGTH;
/* MMS Body 길이 */
public static final int MMS_SUM_BYTE_LENGTH = BodyCommonConfig.COMMON_SUM_BYTE_LENGTH + SUBJECT_BYTE_LENGTH + MEDIA_MSG_BYTE_LENGTH + FILECNT_BYTE_LENGTH + FILENAME_ONE_BYTE_LENGTH + FILENAME_TWO_BYTE_LENGTH + FILENAME_THREE_BYTE_LENGTH;
}

View File

@ -1,9 +1,5 @@
package com.munjaon.server.queue.config;
import com.munjaon.server.server.packet.common.Packet;
import java.io.UnsupportedEncodingException;
public final class QueueConstants {
/** Queue File Header Length - [Create Date:10 Byte, Push Count:10 Byte] */
public static final int QUEUE_HEADER_LENGTH = 20;
@ -80,31 +76,5 @@ public final class QueueConstants {
public static final int REPORT_TELECOM_LENGTH = 7;
// 큐에 저장하기전에 바이트를 채울 문자
public static final byte SET_DEFAULT_BYTE = (byte) 0x00;
public static String getString(byte[] srcArray) throws UnsupportedEncodingException {
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, Packet.AGENT_CHARACTER_SET);
}
public static final byte SET_DEFAULT_BYTE = (byte) 0x20;
}

View File

@ -1,15 +0,0 @@
package com.munjaon.server.queue.config;
public final class QueueHeaderConfig {
/* 변수 정의 : 전체 길이 : 개별 변수 Length : 개별 변수 Position */
/* 큐생성일 읽을 위치값 : 0 */
public static final int CREATE_DATE_POSITION = 0;
/* 큐생성일 읽을 크기 */
public static final int CREATE_DATE_LENGTH = 10;
/* 큐 쓰기 카운트 읽을 위치값 */
public static final int PUSH_COUNT_POSITION = CREATE_DATE_POSITION + CREATE_DATE_LENGTH;
/* 큐 쓰기 카운트 읽을 크기 */
public static final int PUSH_COUNT_LENGTH = 10;
/* Queue File Header Length - [Create Date:10 Byte, Push Count:10 Byte] */
public static final int QUEUE_HEADER_LENGTH = CREATE_DATE_LENGTH + PUSH_COUNT_LENGTH;
}

View File

@ -1,46 +0,0 @@
package com.munjaon.server.queue.config;
public final class ReportConfig {
/* USER_ID (Length : 20 / Position : 0) */
public static final int USER_ID_LENGTH = 20;
public static final int USER_ID_POSITION = 0;
/* WRITE_COUNT (Length : 10 / Position : 20) */
public static final int WRITE_COUNT_LENGTH = 10;
public static final int WRITE_COUNT_POSITION = USER_ID_POSITION + USER_ID_LENGTH;
/* READ_COUNT (Length : 10 / Position : 30) */
public static final int READ_COUNT_LENGTH = 10;
public static final int READ_COUNT_POSITION = WRITE_COUNT_POSITION + WRITE_COUNT_LENGTH;
/* Head 길이 */
public static final int HEAD_LENGTH = READ_COUNT_POSITION + READ_COUNT_LENGTH;
/* MSG_ID (Length : 20 / Position : 0) */
public static final int MSG_ID_LENGTH = 20;
public static final int MSG_ID_POSITION = 0;
/* AGENT_CODE (Length : 2 / Position : 20) */
public static final int AGENT_CODE_LENGTH = 2;
public static final int AGENT_CODE_POSITION = MSG_ID_POSITION + MSG_ID_LENGTH;
/* SEND_TIME (Length : 14 / Position : 22) */
public static final int SEND_TIME_LENGTH = 14;
public static final int SEND_TIME_POSITION = AGENT_CODE_POSITION + AGENT_CODE_LENGTH;
/* TELECOM (Length : 3 / Position : 36) */
public static final int TELECOM_LENGTH = 3;
public static final int TELECOM_POSITION = SEND_TIME_POSITION + SEND_TIME_LENGTH;
/* RESULT (Length : 5 / Position : 39) */
public static final int RESULT_LENGTH = 5;
public static final int RESULT_POSITION = TELECOM_POSITION + TELECOM_LENGTH;
/* Report 길이 */
public static final int BODY_LENGTH = RESULT_POSITION + RESULT_LENGTH;
// 큐에 저장하기전에 바이트를 채울 문자
public static final byte SET_DEFAULT_BYTE = (byte) 0x20;
}

View File

@ -1,10 +0,0 @@
package com.munjaon.server.queue.config;
public final class SmsBodyConfig {
/* SMS Message (Length : 160 / Position : 161) */
public static final int SMS_MSG_BYTE_LENGTH = 160;
public static final int SMS_MSG_BYTE_POSITION = BodyCommonConfig.AGENT_CODE_BYTE_POSITION + BodyCommonConfig.AGENT_CODE_BYTE_LENGTH;
/* SMS Body 길이 */
public static final int SMS_SUM_BYTE_LENGTH = BodyCommonConfig.COMMON_SUM_BYTE_LENGTH + SMS_MSG_BYTE_LENGTH;
}

View File

@ -8,35 +8,11 @@ import lombok.ToString;
@Setter
@ToString
public class BasicMessageDto {
/* 임시로 사용하는 변수 */
protected String id;
protected String userId = ""; // 사용자 아이디
protected final String feeType = "A"; // 요금제(선불 : P / 후불 : A)
protected String unitCost = ""; // 단가
protected String msgGroupID = "0";
protected String userMsgID = "";
protected String serviceType = "";
protected String sendStatus = "0";
protected String userSender = "";
protected String userReceiver = "";
protected String reserveDt = "";
protected String requestDt;
protected String remoteIP = "127.0.0.1";
protected String routerSeq = "0";
protected String userMessage = "";
protected String userSubject = "";
protected int userFileCnt = 0;
protected String userFileName01;
protected String userFileName02;
protected String userFileName03;
protected int userFileSize01 = 0;
protected int userFileSize02 = 0;
protected int userFileSize03 = 0;
private String kakaoSenderKey;
private String kakaoTemplateCode;
private String kakaoJsonFile;
protected String userMsgType = "";
protected String userRequestDate = "";
protected String sendStatus = "0";
}

View File

@ -1,12 +0,0 @@
package com.munjaon.server.queue.dto;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class LmsMessageDto extends BasicMessageDto {
private String userSubject = "";
}

View File

@ -1,19 +0,0 @@
package com.munjaon.server.queue.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@Builder
@ToString
public class QueueInfo {
private String queuePath;
private String queueName;
private String queueFileName;
// private int queueDataLength = 0;
private String serviceType;
private String readXMLFileName;
}

View File

@ -4,11 +4,10 @@ import lombok.Getter;
@Getter
public enum QueueService {
SMS_QUEUE_SERVICE,
LMS_QUEUE_SERVICE,
MMS_QUEUE_SERVICE,
KAT_QUEUE_SERVICE,
KFT_QUEUE_SERVICE;
SMS_QUEUE,
LMS_QUEUE,
MMS_QUEUE,
KAKAO_QUEUE;
private Object service;

View File

@ -1,377 +0,0 @@
package com.munjaon.server.queue.enums;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.pool.WriteQueue;
import com.munjaon.server.queue.service.*;
import lombok.Getter;
import java.util.EnumSet;
import java.util.List;
@Getter
public enum QueueTypeWorker {
MSG_TYPE_SMS("SMS") {
@Override
public int getQueueSize() {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
return smsQueueService.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
return smsQueueService.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
smsQueueService.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
smsQueueService.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
smsQueueService.pushQueue(data);
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
return smsQueueService.saveMessageToTable(data);
}
@Override
public int saveMessageForList(List<BasicMessageDto> list) {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
return smsQueueService.saveMessageForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
smsQueueService.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
return smsQueueService.memoryDeQueue();
}
@Override
public int getMemorySize() {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
return smsQueueService.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
SmsQueueService smsQueueService = (SmsQueueService) QueueService.SMS_QUEUE_SERVICE.getService();
return smsQueueService.isMemoryEmpty();
}
},
MSG_TYPE_LMS("LMS") {
@Override
public int getQueueSize() {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
return lmsQueueService.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
return lmsQueueService.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
lmsQueueService.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
lmsQueueService.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
lmsQueueService.pushQueue(data);
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
return lmsQueueService.saveMessageToTable(data);
}
@Override
public int saveMessageForList(List<BasicMessageDto> list) {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
return lmsQueueService.saveMessageForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
lmsQueueService.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
return lmsQueueService.memoryDeQueue();
}
@Override
public int getMemorySize() {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
return lmsQueueService.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
LmsQueueService lmsQueueService = (LmsQueueService) QueueService.LMS_QUEUE_SERVICE.getService();
return lmsQueueService.isMemoryEmpty();
}
},
MSG_TYPE_MMS("MMS") {
@Override
public int getQueueSize() {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
return mmsQueueService.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
return mmsQueueService.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
mmsQueueService.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
mmsQueueService.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
mmsQueueService.pushQueue(data);
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
return mmsQueueService.saveMessageToTable(data);
}
@Override
public int saveMessageForList(List<BasicMessageDto> list) {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
return mmsQueueService.saveMessageForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
mmsQueueService.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
return mmsQueueService.memoryDeQueue();
}
@Override
public int getMemorySize() {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
return mmsQueueService.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
MmsQueueService mmsQueueService = (MmsQueueService) QueueService.MMS_QUEUE_SERVICE.getService();
return mmsQueueService.isMemoryEmpty();
}
},
MSG_TYPE_KAT("KAT") {
@Override
public int getQueueSize() {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
return kakaoAlarmQueueService.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
return kakaoAlarmQueueService.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
kakaoAlarmQueueService.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
kakaoAlarmQueueService.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
kakaoAlarmQueueService.pushQueue(data);
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
return kakaoAlarmQueueService.saveMessageToTable(data);
}
@Override
public int saveMessageForList(List<BasicMessageDto> list) {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
return kakaoAlarmQueueService.saveMessageForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
kakaoAlarmQueueService.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
return kakaoAlarmQueueService.memoryDeQueue();
}
@Override
public int getMemorySize() {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
return kakaoAlarmQueueService.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
KakaoAlarmQueueService kakaoAlarmQueueService = (KakaoAlarmQueueService) QueueService.KAT_QUEUE_SERVICE.getService();
return kakaoAlarmQueueService.isMemoryEmpty();
}
},
MSG_TYPE_KFT("KFT") {
@Override
public int getQueueSize() {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
return kakaoFriendQueueService.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
return kakaoFriendQueueService.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
kakaoFriendQueueService.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
kakaoFriendQueueService.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
kakaoFriendQueueService.pushQueue(data);
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
return kakaoFriendQueueService.saveMessageToTable(data);
}
@Override
public int saveMessageForList(List<BasicMessageDto> list) {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
return kakaoFriendQueueService.saveMessageForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
kakaoFriendQueueService.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
return kakaoFriendQueueService.memoryDeQueue();
}
@Override
public int getMemorySize() {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
return kakaoFriendQueueService.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
KakaoFriendQueueService kakaoFriendQueueService = (KakaoFriendQueueService) QueueService.KFT_QUEUE_SERVICE.getService();
return kakaoFriendQueueService.isMemoryEmpty();
}
};
QueueTypeWorker(final String name) {
this.type = name;
}
private final String type;
public static QueueTypeWorker find(String type) {
for (QueueTypeWorker queueTypeWorker : EnumSet.allOf(QueueTypeWorker.class)) {
if (type.equals(queueTypeWorker.getType())) {
return queueTypeWorker;
}
}
return null;
}
public abstract int getQueueSize();
public abstract boolean isExistQueue(String name);
public abstract void removeQueue(String name);
public abstract void addQueue(WriteQueue queue);
public abstract void pushQueue(BasicMessageDto data) throws Exception;
public abstract int saveMessageToTable(BasicMessageDto data);
public abstract int saveMessageForList(List<BasicMessageDto> list);
public abstract void memoryEnQueue(BasicMessageDto data);
public abstract BasicMessageDto memoryDeQueue();
public abstract int getMemorySize();
public abstract boolean isMemoryEmpty();
}

View File

@ -1,13 +0,0 @@
package com.munjaon.server.queue.mapper;
import com.munjaon.server.queue.dto.BasicMessageDto;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface KatMapper {
int insert(BasicMessageDto messageDto);
int insertForList(List<BasicMessageDto> list);
int insertGroupForList(List<BasicMessageDto> list);
}

View File

@ -1,13 +0,0 @@
package com.munjaon.server.queue.mapper;
import com.munjaon.server.queue.dto.BasicMessageDto;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface KftMapper {
int insert(BasicMessageDto messageDto);
int insertForList(List<BasicMessageDto> list);
int insertGroupForList(List<BasicMessageDto> list);
}

View File

@ -1,13 +0,0 @@
package com.munjaon.server.queue.mapper;
import com.munjaon.server.queue.dto.BasicMessageDto;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface LmsMapper {
int insert(BasicMessageDto messageDto);
int insertForList(List<BasicMessageDto> list);
int insertGroupForList(List<BasicMessageDto> list);
}

View File

@ -1,13 +0,0 @@
package com.munjaon.server.queue.mapper;
import com.munjaon.server.queue.dto.BasicMessageDto;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface MmsMapper {
int insert(BasicMessageDto messageDto);
int insertForList(List<BasicMessageDto> list);
int insertGroupForList(List<BasicMessageDto> list);
}

View File

@ -1,13 +0,0 @@
package com.munjaon.server.queue.mapper;
import com.munjaon.server.queue.dto.BasicMessageDto;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface SmsMapper {
int insert(BasicMessageDto messageDto);
int insertForList(List<BasicMessageDto> list);
int insertGroupForList(List<BasicMessageDto> list);
}

View File

@ -1,47 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.dto.BasicMessageDto;
import java.util.LinkedList;
public class KakaoAlarmMemoryQueue {
/** Lock Object */
private final Object msgMonitor = new Object();
/** Message Queue */
private final LinkedList<BasicMessageDto> msgQueue = new LinkedList<>();
/** Singleton Instance */
private static KakaoAlarmMemoryQueue memoryQueue;
public synchronized static KakaoAlarmMemoryQueue getInstance() {
if(memoryQueue == null){
memoryQueue = new KakaoAlarmMemoryQueue();
}
return memoryQueue;
}
/** MESSAGE QUEUE ************************************************************************ */
/** MESSAGE enQueue */
public void memoryEnQueue(BasicMessageDto data){
synchronized(msgMonitor){
msgQueue.addLast(data);
}
}
/** SMS deQueue */
public BasicMessageDto memoryDeQueue() {
synchronized(msgMonitor){
if (msgQueue.isEmpty()) return null;
else return msgQueue.removeFirst();
}
}
/** SMS size */
public int getMemorySize() {
synchronized(msgMonitor) {
return msgQueue.size();
}
}
/** SMS isEmpty */
public boolean isMemoryEmpty() {
synchronized(msgMonitor) {
return msgQueue.isEmpty();
}
}
}

View File

@ -1,15 +0,0 @@
package com.munjaon.server.queue.pool;
public class KakaoAlarmQueuePool extends QueuePool {
/** Singleton Instance */
private static KakaoAlarmQueuePool queueInstance;
private KakaoAlarmQueuePool() {}
public synchronized static KakaoAlarmQueuePool getInstance() {
if(queueInstance == null){
queueInstance = new KakaoAlarmQueuePool();
}
return queueInstance;
}
}

View File

@ -1,40 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.KakaoBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class KakaoAlarmReadQueue extends ReadQueue {
public KakaoAlarmReadQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
// initQueue();
}
@Override
void popBuffer() throws Exception {
this.channel.position(MessageUtil.calcReadPosition(this.popCounter, KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH));
this.channel.read(this.dataBuffer);
}
@Override
void getBytesForExtendMessage(BasicMessageDto messageDto) throws UnsupportedEncodingException {
MessageUtil.getBytesForKakaoMessage(this.dataBuffer, messageDto);
}
@Override
void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,76 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.config.ServiceCode;
import com.munjaon.server.queue.config.KakaoBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class KakaoAlarmWriteQueue extends WriteQueue {
public KakaoAlarmWriteQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
/* 큐초기화 */
// initQueue();
}
@Override
public int isValidateMessageForExtend(BasicMessageDto messageDto) throws UnsupportedEncodingException {
/* 13. 제목 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserSubject(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserSubject(), KakaoBodyConfig.SUBJECT_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_SUBJECT.getCode();
}
/* 14. 메시지 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserMessage(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserMessage(), KakaoBodyConfig.MEDIA_MSG_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
/* 15. KAKAO_SENDER_KEY */
if (MessageUtil.isEmptyForMessage(messageDto.getKakaoSenderKey(), true) || MessageUtil.isOverByteForMessage(messageDto.getKakaoSenderKey(), KakaoBodyConfig.KAKAO_SENDER_KEY_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
/* 16. KAKAO_TEMPLATE_CODE */
if (MessageUtil.isEmptyForMessage(messageDto.getKakaoTemplateCode(), true) || MessageUtil.isOverByteForMessage(messageDto.getKakaoTemplateCode(), KakaoBodyConfig.KAKAO_TEMPLATE_CODE_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
return ServiceCode.OK.getCode();
}
@Override
public void pushMessageToBuffer(BasicMessageDto messageDto) throws Exception {
if (isValidateMessage(messageDto) == ServiceCode.OK.getCode()) {
/* 1. dataBuffer 초기화 */
initDataBuffer();
/* 2. messageDto >> dataBuffer */
MessageUtil.setBytesForCommonMessage(this.dataBuffer, messageDto);
MessageUtil.setBytesForKakaoMessage(this.dataBuffer, messageDto);
/* 3. 파일큐에 적재 */
/* 3.1 Header 정보 다시 일기 */
readHeader();
if (this.dataBuffer != null){
this.channel.position(MessageUtil.calcWritePosition(this.pushCounter, KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH));
this.dataBuffer.flip();
this.channel.write(this.dataBuffer);
/* 3.2 Push 카운터 증가 */
this.pushCounter = this.pushCounter + 1;
/* 3.3 Header 정보 변경 */
writeHeader();
}
}
}
@Override
public void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,47 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.dto.BasicMessageDto;
import java.util.LinkedList;
public class KakaoFriendMemoryQueue {
/** SMS Lock Object */
private final Object msgMonitor = new Object();
/** SMS Message Queue */
private final LinkedList<BasicMessageDto> msgQueue = new LinkedList<>();
/** Singleton Instance */
private static KakaoFriendMemoryQueue memoryQueue;
public synchronized static KakaoFriendMemoryQueue getInstance() {
if(memoryQueue == null){
memoryQueue = new KakaoFriendMemoryQueue();
}
return memoryQueue;
}
/** MESSAGE QUEUE ************************************************************************ */
/** MESSAGE enQueue */
public void memoryEnQueue(BasicMessageDto data){
synchronized(msgMonitor){
msgQueue.addLast(data);
}
}
/** SMS deQueue */
public BasicMessageDto memoryDeQueue() {
synchronized(msgMonitor){
if (msgQueue.isEmpty()) return null;
else return msgQueue.removeFirst();
}
}
/** SMS size */
public int getMemorySize() {
synchronized(msgMonitor) {
return msgQueue.size();
}
}
/** SMS isEmpty */
public boolean isMemoryEmpty() {
synchronized(msgMonitor) {
return msgQueue.isEmpty();
}
}
}

View File

@ -1,15 +0,0 @@
package com.munjaon.server.queue.pool;
public class KakaoFriendQueuePool extends QueuePool {
/** Singleton Instance */
private static KakaoFriendQueuePool queueInstance;
private KakaoFriendQueuePool() {}
public synchronized static KakaoFriendQueuePool getInstance(){
if(queueInstance == null){
queueInstance = new KakaoFriendQueuePool();
}
return queueInstance;
}
}

View File

@ -1,40 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.KakaoBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class KakaoFriendReadQueue extends ReadQueue {
public KakaoFriendReadQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
// initQueue();
}
@Override
void popBuffer() throws Exception {
this.channel.position(MessageUtil.calcReadPosition(this.popCounter, KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH));
this.channel.read(this.dataBuffer);
}
@Override
void getBytesForExtendMessage(BasicMessageDto messageDto) throws UnsupportedEncodingException {
MessageUtil.getBytesForKakaoMessage(this.dataBuffer, messageDto);
}
@Override
void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,76 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.config.ServiceCode;
import com.munjaon.server.queue.config.KakaoBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class KakaoFriendWriteQueue extends WriteQueue {
public KakaoFriendWriteQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
/* 큐초기화 */
// initQueue();
}
@Override
public int isValidateMessageForExtend(BasicMessageDto messageDto) throws UnsupportedEncodingException {
/* 13. 제목 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserSubject(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserSubject(), KakaoBodyConfig.SUBJECT_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_SUBJECT.getCode();
}
/* 14. 메시지 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserMessage(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserMessage(), KakaoBodyConfig.MEDIA_MSG_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
/* 15. KAKAO_SENDER_KEY */
if (MessageUtil.isEmptyForMessage(messageDto.getKakaoSenderKey(), true) || MessageUtil.isOverByteForMessage(messageDto.getKakaoSenderKey(), KakaoBodyConfig.KAKAO_SENDER_KEY_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
/* 16. KAKAO_TEMPLATE_CODE */
if (MessageUtil.isEmptyForMessage(messageDto.getKakaoTemplateCode(), true) || MessageUtil.isOverByteForMessage(messageDto.getKakaoTemplateCode(), KakaoBodyConfig.KAKAO_TEMPLATE_CODE_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
return ServiceCode.OK.getCode();
}
@Override
public void pushMessageToBuffer(BasicMessageDto messageDto) throws Exception {
if (isValidateMessage(messageDto) == ServiceCode.OK.getCode()) {
/* 1. dataBuffer 초기화 */
initDataBuffer();
/* 2. messageDto >> dataBuffer */
MessageUtil.setBytesForCommonMessage(this.dataBuffer, messageDto);
MessageUtil.setBytesForKakaoMessage(this.dataBuffer, messageDto);
/* 3. 파일큐에 적재 */
/* 3.1 Header 정보 다시 일기 */
readHeader();
if (this.dataBuffer != null){
this.channel.position(MessageUtil.calcWritePosition(this.pushCounter, KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH));
this.dataBuffer.flip();
this.channel.write(this.dataBuffer);
/* 3.2 Push 카운터 증가 */
this.pushCounter = this.pushCounter + 1;
/* 3.3 Header 정보 변경 */
writeHeader();
}
}
}
@Override
public void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < KakaoBodyConfig.KAKAO_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,216 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.server.packet.common.Packet;
import com.munjaon.server.util.FileUtil;
import lombok.Getter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
@Getter
public class KeyWriteQueue {
private final static int HEAD_SIZE = 40;
private final static int HEAD_TOTAL_COUNT_LOCATION = 0;
private final static int HEAD_TOTAL_COUNT_SIZE = 20;
private final static int HEAD_WRITE_POSITION_LOCATION = 20;
private final static int HEAD_WRITE_POSITION_SIZE = 20;
private final static int BODY_WRITE_KEY_SIZE = 20;
/* Queue 변수 */
private final String queuePath;
private final String queueName;
private final int MAX_QUEUE_SIZE;
private int writePosition = -1;
private int totalCount = -1;
/** Queue Header Buffer */
protected ByteBuffer headerBuffer = null;
/** Header 에서 사용하는 변수 */
protected byte[] headerArray = null;
/** Queue File Channel */
protected FileChannel channel = null;
/** pushBuffer() 함수에서 사용하는 변수 */
protected ByteBuffer dataBuffer = null;
/** isExist() 함수에서 사용하는 변수 */
protected ByteBuffer searchBuffer = null;
public KeyWriteQueue(String queuePath, String queueName, int maxQueueSize) {
this.queuePath = System.getProperty("ROOTPATH") + File.separator + queuePath;
this.queueName = queueName;
MAX_QUEUE_SIZE = maxQueueSize;
/* 큐초기화 */
try {
initQueue();
} catch (Exception e) {}
}
public boolean isExist(String key) throws Exception {
if (this.totalCount == 0) {
return false;
}
boolean exists = false;
for (int i = 0; i < this.totalCount; i++) {
int position = this.HEAD_SIZE + (i * BODY_WRITE_KEY_SIZE);
this.channel.position(position);
/* 읽기용 데이터 버퍼 초기화 */
initSearchBuffer();
this.channel.read(searchBuffer);
byte[] byteArray = new byte[BODY_WRITE_KEY_SIZE];
searchBuffer.position(0);
searchBuffer.get(byteArray);
String queueKey = QueueConstants.getString(byteArray);
if (queueKey.equals(key)) {
exists = true;
break;
}
}
return exists;
}
public void pushKeyToBuffer(String key) throws Exception {
if (key == null || key.isEmpty()) {
return;
}
/* 1. dataBuffer 초기화 */
initDataBuffer();
/* 2. messageDto >> dataBuffer */
this.dataBuffer.position(0);
this.dataBuffer.put(key.getBytes(Packet.AGENT_CHARACTER_SET));
/* 3.1 Header 정보 다시 일기 */
readHeader();
if (this.dataBuffer != null) {
int position = HEAD_SIZE + (BODY_WRITE_KEY_SIZE * this.writePosition);
this.channel.position(position);
this.dataBuffer.flip();
this.channel.write(this.dataBuffer);
/* 3.2 Push 카운터 증가 */
this.writePosition = this.writePosition + 1;
if (this.writePosition > this.MAX_QUEUE_SIZE) {
this.writePosition = 0;
}
this.totalCount = this.totalCount + 1;
if (this.totalCount > this.MAX_QUEUE_SIZE) {
this.totalCount = this.MAX_QUEUE_SIZE;
}
/* 3.3 Header 정보 변경 */
writeHeader();
}
}
public void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(BODY_WRITE_KEY_SIZE);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < BODY_WRITE_KEY_SIZE; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
public void initSearchBuffer() {
if (this.searchBuffer == null) {
this.searchBuffer = ByteBuffer.allocateDirect(BODY_WRITE_KEY_SIZE);
}
this.searchBuffer.clear();
for(int loopCnt = 0; loopCnt < BODY_WRITE_KEY_SIZE; loopCnt++){
this.searchBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.searchBuffer.position(0);
}
private void initQueue() throws Exception {
this.headerBuffer = ByteBuffer.allocateDirect(HEAD_SIZE);
try{
/* 1. 경로 체크 및 생성 */
FileUtil.mkdirs(this.queuePath);
/* 2. 파일생성 및 읽기 */
File file = new File(this.queuePath + File.separator + queueName + ".queue");
this.channel = new RandomAccessFile(file, "rw").getChannel();
if (file.length() == 0) {
// Push Pop 카운트 초기화
this.writePosition = 0;
this.totalCount = 0;
// 헤더 초기화
writeHeader();
} else {
readHeader();
}
// backupQueue();
} catch(Exception e) {
throw e;
} finally {
//lock.release();
}
}
protected void readHeader() throws Exception {
try {
initHeaderBuffer();
this.channel.position(0);
this.channel.read(this.headerBuffer);
this.headerArray = new byte[HEAD_TOTAL_COUNT_SIZE];
// 생성날짜 가져오기 - 생성날짜(10) / 읽은카운트(10) / 쓴카운트(10)
this.headerBuffer.position(HEAD_TOTAL_COUNT_LOCATION);
this.headerBuffer.get(this.headerArray);
this.totalCount = Integer.parseInt(QueueConstants.getString(this.headerArray));
// 카운트 가져오기
this.headerArray = new byte[HEAD_WRITE_POSITION_SIZE];
this.headerBuffer.position(HEAD_WRITE_POSITION_LOCATION);
this.headerBuffer.get(this.headerArray);
this.writePosition = Integer.parseInt(QueueConstants.getString(this.headerArray));
} catch(Exception e) {
throw e;
}
}
protected void writeHeader() throws Exception {
try {
initHeaderBuffer();
this.channel.position(0);
this.headerBuffer.put(Integer.toString(this.totalCount).getBytes(Packet.AGENT_CHARACTER_SET));
this.headerBuffer.position(HEAD_WRITE_POSITION_LOCATION);
this.headerBuffer.put(Integer.toString(this.writePosition).getBytes(Packet.AGENT_CHARACTER_SET));
this.headerBuffer.flip();
this.channel.write(this.headerBuffer);
} catch(Exception e) {
throw e;
}
}
protected void initHeaderBuffer(){
this.headerBuffer.clear();
for(int loopCnt = 0; loopCnt < HEAD_SIZE; loopCnt++){
this.headerBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.headerBuffer.position(0);
}
public void close() throws IOException {
try {
if (isOpen()) {
channel.close();
}
} catch(IOException e) {
throw e;
}
}
protected boolean isOpen() {
if (this.channel == null) {
return false;
}
return this.channel.isOpen();
}
}

View File

@ -1,47 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.dto.BasicMessageDto;
import java.util.LinkedList;
public class LmsMemoryQueue {
/** Lock Object */
private final Object msgMonitor = new Object();
/** Message Queue */
private final LinkedList<BasicMessageDto> msgQueue = new LinkedList<>();
/** Singleton Instance */
private static LmsMemoryQueue memoryQueue;
public synchronized static LmsMemoryQueue getInstance() {
if(memoryQueue == null){
memoryQueue = new LmsMemoryQueue();
}
return memoryQueue;
}
/** MESSAGE QUEUE ************************************************************************ */
/** MESSAGE enQueue */
public void memoryEnQueue(BasicMessageDto data){
synchronized(msgMonitor){
msgQueue.addLast(data);
}
}
/** SMS deQueue */
public BasicMessageDto memoryDeQueue() {
synchronized(msgMonitor){
if (msgQueue.isEmpty()) return null;
else return msgQueue.removeFirst();
}
}
/** SMS size */
public int getMemorySize() {
synchronized(msgMonitor) {
return msgQueue.size();
}
}
/** SMS isEmpty */
public boolean isMemoryEmpty() {
synchronized(msgMonitor) {
return msgQueue.isEmpty();
}
}
}

View File

@ -1,15 +0,0 @@
package com.munjaon.server.queue.pool;
public class LmsQueuePool extends QueuePool {
/** Singleton Instance */
private static LmsQueuePool queueInstance;
private LmsQueuePool() {}
public synchronized static LmsQueuePool getInstance(){
if(queueInstance == null){
queueInstance = new LmsQueuePool();
}
return queueInstance;
}
}

View File

@ -1,40 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.MediaBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class LmsReadQueue extends ReadQueue {
public LmsReadQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
// initQueue();
}
@Override
void popBuffer() throws Exception {
this.channel.position(MessageUtil.calcReadPosition(this.popCounter, MediaBodyConfig.LMS_SUM_BYTE_LENGTH));
this.channel.read(this.dataBuffer);
}
@Override
void getBytesForExtendMessage(BasicMessageDto messageDto) throws UnsupportedEncodingException {
MessageUtil.getBytesForMediaMessage(this.dataBuffer, messageDto);
}
@Override
void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(MediaBodyConfig.LMS_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < MediaBodyConfig.LMS_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,68 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.config.ServiceCode;
import com.munjaon.server.queue.config.MediaBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class LmsWriteQueue extends WriteQueue {
public LmsWriteQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
/* 큐초기화 */
// initQueue();
}
@Override
public int isValidateMessageForExtend(BasicMessageDto messageDto) throws UnsupportedEncodingException {
/* 13. 제목 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserSubject(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserSubject(), MediaBodyConfig.SUBJECT_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_SUBJECT.getCode();
}
/* 14. 메시지 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserMessage(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserMessage(), MediaBodyConfig.MEDIA_MSG_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
return ServiceCode.OK.getCode();
}
@Override
public void pushMessageToBuffer(BasicMessageDto messageDto) throws Exception {
if (isValidateMessage(messageDto) == ServiceCode.OK.getCode()) {
/* 1. dataBuffer 초기화 */
initDataBuffer();
/* 2. messageDto >> dataBuffer */
MessageUtil.setBytesForCommonMessage(this.dataBuffer, messageDto);
MessageUtil.setBytesForMediaMessage(this.dataBuffer, messageDto);
/* 3. 파일큐에 적재 */
/* 3.1 Header 정보 다시 일기 */
readHeader();
if (this.dataBuffer != null){
this.channel.position(MessageUtil.calcWritePosition(this.pushCounter, MediaBodyConfig.LMS_SUM_BYTE_LENGTH));
this.dataBuffer.flip();
this.channel.write(this.dataBuffer);
/* 3.2 Push 카운터 증가 */
this.pushCounter = this.pushCounter + 1;
/* 3.3 Header 정보 변경 */
writeHeader();
}
}
}
@Override
public void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(MediaBodyConfig.LMS_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < MediaBodyConfig.LMS_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,47 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.dto.BasicMessageDto;
import java.util.LinkedList;
public class MmsMemoryQueue {
/** Lock Object */
private final Object msgMonitor = new Object();
/** Message Queue */
private final LinkedList<BasicMessageDto> msgQueue = new LinkedList<>();
/** Singleton Instance */
private static MmsMemoryQueue memoryQueue;
public synchronized static MmsMemoryQueue getInstance() {
if(memoryQueue == null){
memoryQueue = new MmsMemoryQueue();
}
return memoryQueue;
}
/** MESSAGE QUEUE ************************************************************************ */
/** MESSAGE enQueue */
public void memoryEnQueue(BasicMessageDto data){
synchronized(msgMonitor){
msgQueue.addLast(data);
}
}
/** SMS deQueue */
public BasicMessageDto memoryDeQueue() {
synchronized(msgMonitor){
if (msgQueue.isEmpty()) return null;
else return msgQueue.removeFirst();
}
}
/** SMS size */
public int getMemorySize() {
synchronized(msgMonitor) {
return msgQueue.size();
}
}
/** SMS isEmpty */
public boolean isMemoryEmpty() {
synchronized(msgMonitor) {
return msgQueue.isEmpty();
}
}
}

View File

@ -1,15 +0,0 @@
package com.munjaon.server.queue.pool;
public class MmsQueuePool extends QueuePool {
/** Singleton Instance */
private static MmsQueuePool queueInstance;
private MmsQueuePool() {}
public synchronized static MmsQueuePool getInstance(){
if(queueInstance == null){
queueInstance = new MmsQueuePool();
}
return queueInstance;
}
}

View File

@ -1,41 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.MediaBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class MmsReadQueue extends ReadQueue {
public MmsReadQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
// initQueue();
}
@Override
void popBuffer() throws Exception {
this.channel.position(MessageUtil.calcReadPosition(this.popCounter, MediaBodyConfig.MMS_SUM_BYTE_LENGTH));
this.channel.read(this.dataBuffer);
}
@Override
void getBytesForExtendMessage(BasicMessageDto messageDto) throws UnsupportedEncodingException {
MessageUtil.getBytesForMediaMessage(this.dataBuffer, messageDto);
MessageUtil.getBytesForMmsMessage(this.dataBuffer, messageDto);
}
@Override
void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(MediaBodyConfig.MMS_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < MediaBodyConfig.MMS_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,69 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.config.ServiceCode;
import com.munjaon.server.queue.config.MediaBodyConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class MmsWriteQueue extends WriteQueue {
public MmsWriteQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
/* 큐초기화 */
// initQueue();
}
@Override
public int isValidateMessageForExtend(BasicMessageDto messageDto) throws UnsupportedEncodingException {
/* 13. 제목 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserSubject(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserSubject(), MediaBodyConfig.SUBJECT_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_SUBJECT.getCode();
}
/* 14. 메시지 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserMessage(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserMessage(), MediaBodyConfig.MEDIA_MSG_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_MEDIA_MESSAGE.getCode();
}
return ServiceCode.OK.getCode();
}
@Override
public void pushMessageToBuffer(BasicMessageDto messageDto) throws Exception {
if (isValidateMessage(messageDto) == ServiceCode.OK.getCode()) {
/* 1. dataBuffer 초기화 */
initDataBuffer();
/* 2. messageDto >> dataBuffer */
MessageUtil.setBytesForCommonMessage(this.dataBuffer, messageDto);
MessageUtil.setBytesForMediaMessage(this.dataBuffer, messageDto);
MessageUtil.setBytesForMmsMessage(this.dataBuffer, messageDto);
/* 3. 파일큐에 적재 */
/* 3.1 Header 정보 다시 일기 */
readHeader();
if (this.dataBuffer != null){
this.channel.position(MessageUtil.calcWritePosition(this.pushCounter, MediaBodyConfig.MMS_SUM_BYTE_LENGTH));
this.dataBuffer.flip();
this.channel.write(this.dataBuffer);
/* 3.2 Push 카운터 증가 */
this.pushCounter = this.pushCounter + 1;
/* 3.3 Header 정보 변경 */
writeHeader();
}
}
}
@Override
public void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(MediaBodyConfig.MMS_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < MediaBodyConfig.MMS_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,86 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.dto.BasicMessageDto;
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedList;
@Slf4j
public abstract class QueuePool {
/** Lock Object */
protected final Object lockMonitor = new Object();
/** File Queue Pool */
protected final LinkedList<WriteQueue> queuePool = new LinkedList<>();
/** File Queue */
protected WriteQueue queue = null;
/** File Queue 분배를 위한 인덱서 */
protected int queueIndex = 0;
public int getQueueSize() {
synchronized (lockMonitor) {
return queuePool.size();
}
}
/** Queue 존재하는지 조회 */
public boolean isExistQueue(String name){
synchronized (lockMonitor) {
boolean isExist = false;
for (WriteQueue writeQueue : queuePool) {
if (name.equals(writeQueue.getQueueName())) {
isExist = true;
break;
}
}
return isExist;
}
}
/** Queue 제거 */
public void removeQueue(String name) {
synchronized (lockMonitor) {
for (int loopCnt = 0; loopCnt < queuePool.size(); loopCnt++) {
queue = queuePool.get(loopCnt);
if(name.equals(queue.getQueueName())){
queuePool.remove(loopCnt);
log.info("[" + queue.getQueueInfo().getServiceType() + " Queue] [" + queue.getQueueName() + " is Removed]");
break;
}
}
}
}
/** Queue 등록 */
public void addQueue(WriteQueue queue) {
synchronized(lockMonitor){
if (queue != null){
queuePool.addLast(queue);
log.info("[" + queue.getQueueInfo().getServiceType() + " Queue] [" + queue.getQueueName() + " is Added]");
lockMonitor.notifyAll();
}
}
}
/** Queue 데이터 저장 */
public void pushQueue(BasicMessageDto data) throws Exception {
synchronized(lockMonitor) {
if (queuePool.isEmpty()) {
try {
lockMonitor.wait();
} catch (InterruptedException e) {
// 아무 처리도 하지 않는다.
}
}
//큐리스트의 끝까지 이동한 경우 처음으로 되돌린다.
if (queueIndex >= queuePool.size()) {
queueIndex = 0;
}
// 파일큐에 Push 한다.
queue = queuePool.get(queueIndex);
log.info("Adding queue : {}, Data : {}", queue.getQueueName(), data);
queue.pushMessageToBuffer(data);
// 큐인덱서를 증가시킨다.
queueIndex++;
}
}
}

View File

@ -1,211 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.config.QueueHeaderConfig;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.FileUtil;
import com.munjaon.server.util.MessageUtil;
import lombok.Getter;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
public abstract class ReadQueue {
/** Queue Header Buffer */
protected ByteBuffer headerBuffer = null;
/** Header 에서 사용하는 변수 */
protected byte[] headerArray = null;
/** Queue Create Date - [Format:YYYYMMDD] */
@Getter
protected String createDate;
/** XML 읽은 날짜 */
@Getter
protected String readXMLDate;
/** Queue Pop Counter */
@Getter
protected int popCounter = -1;
/** Queue Push Counter */
@Getter
protected int pushCounter = 0;
/* 큐경로 */
@Getter
protected String queuePath;
/** Queue File Channel */
protected FileChannel channel = null;
protected FileOutputStream fileOutputStream = null;
/** Queue Information */
@Getter
protected QueueInfo queueInfo = null;
/** pushBuffer() 함수에서 사용하는 변수 */
protected ByteBuffer dataBuffer = null;
protected void initQueuePath() {
/* 1. 큐경로 */
this.queuePath = System.getProperty("ROOTPATH") + File.separator + queueInfo.getQueuePath();
/* 2. 경로 체크 및 생성 */
FileUtil.mkdirs(this.queuePath);
}
public void initReadQueue() throws IOException, JDOMException {
this.queueInfo.setReadXMLFileName(this.queuePath + File.separator + this.queueInfo.getQueueName() + "_Read.xml");
File file = new File(this.queueInfo.getReadXMLFileName());
if (file.exists()) {
readPopCounter(file);
} else {
this.readXMLDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
this.popCounter = 0;
writePopCounter();
}
}
public void initPopCounter() throws IOException {
initHeaderBuffer();
// 데이터 초기화
this.readXMLDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
this.popCounter = 0;
writePopCounter();
}
protected void readPopCounter(File file) throws IOException, JDOMException {
SAXBuilder sax = new SAXBuilder();
// String that contains XML
Document doc = (Document) sax.build(file);
Element rootNode = doc.getRootElement();
List<Element> childElements = rootNode.getChildren();
for (Element child : childElements) {
if ("createDate".equals(child.getName())) {
this.readXMLDate = child.getValue();
}
if ("popCounter".equals(child.getName())) {
this.popCounter = Integer.parseInt(child.getValue());
}
}
}
protected void readPopCounter() throws IOException, JDOMException {
// String that contains XML
File file = new File(this.queueInfo.getReadXMLFileName());
readPopCounter(file);
}
public void writePopCounter() throws IOException {
SAXBuilder sb = new SAXBuilder();
Document docFile = new Document();
Element rootElement = new Element("ReadQueue");
rootElement.addContent(new Element("createDate").setText(this.readXMLDate));
rootElement.addContent(new Element("popCounter").setText(Integer.toString(this.popCounter)));
docFile.setRootElement(rootElement);
// pretty print format
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
// output to console
this.fileOutputStream = new FileOutputStream(this.queueInfo.getReadXMLFileName());
xmlOutputter.output(docFile, fileOutputStream);
}
public void initQueue() throws Exception {
this.headerBuffer = ByteBuffer.allocateDirect(QueueHeaderConfig.QUEUE_HEADER_LENGTH);
try {
/* 1. 큐경로 초기화 */
initQueuePath();
this.queueInfo.setQueueFileName(this.queuePath + File.separator + this.queueInfo.getQueueName() + ".queue");
File file = new File(this.queueInfo.getQueueFileName());
if (file.exists()) {
this.channel = new RandomAccessFile(file, "r").getChannel();
// 파일큐의 헤더 정보를 읽어온다.
readHeader();
/* 읽기 큐 XML Load Or Create */
initReadQueue();
} else {
throw new Exception(this.queueInfo.getQueueName() + "'s Queue is Not Exists!!");
}
} catch(Exception e) {
throw e;
} finally {
//lock.release();
}
}
protected void readHeader() throws Exception {
try {
initHeaderBuffer();
this.channel.position(0);
this.channel.read(this.headerBuffer);
this.headerArray = new byte[QueueHeaderConfig.CREATE_DATE_LENGTH];
// 생성날짜 가져오기 - 생성날짜(10) / 읽은카운트(10) / 쓴카운트(10)
this.headerBuffer.position(QueueHeaderConfig.CREATE_DATE_POSITION);
this.headerBuffer.get(this.headerArray);
this.createDate = QueueConstants.getString(this.headerArray);
// 카운트 가져오기
this.headerArray = new byte[QueueHeaderConfig.PUSH_COUNT_LENGTH];
this.headerBuffer.position(QueueHeaderConfig.PUSH_COUNT_POSITION);
this.headerBuffer.get(this.headerArray);
this.pushCounter = Integer.parseInt(QueueConstants.getString(this.headerArray));
} catch(Exception e) {
throw e;
}
}
protected void initHeaderBuffer(){
this.headerBuffer.clear();
for(int loopCnt = 0; loopCnt < QueueHeaderConfig.QUEUE_HEADER_LENGTH; loopCnt++){
this.headerBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.headerBuffer.position(0);
}
public void close() throws IOException {
try {
if (this.channel != null && this.channel.isOpen()) {
channel.close();
}
if (this.fileOutputStream != null) {
this.fileOutputStream.close();
}
} catch(IOException e) {
throw e;
}
}
public BasicMessageDto popMessageFromBuffer() throws IOException, JDOMException, Exception {
readHeader();
readPopCounter();
BasicMessageDto messageDto = null;
if (this.popCounter < this.pushCounter) {
/* Read buffer 초기화 */
initDataBuffer();
/* Read Queue 읽기 */
popBuffer();
/* 메시지 추출 */
messageDto = new BasicMessageDto();
MessageUtil.getBytesForCommonMessage(this.dataBuffer, messageDto);
getBytesForExtendMessage(messageDto);
/* Pop Counter 증가 및 저장 */
this.popCounter = this.popCounter + 1;
writePopCounter();
}
return messageDto;
}
public void resetPopCounter(int resetCounter) throws IOException {
this.popCounter = this.popCounter - resetCounter;
writePopCounter();
}
abstract void popBuffer() throws Exception;
abstract void getBytesForExtendMessage(BasicMessageDto messageDto) throws UnsupportedEncodingException;
abstract void initDataBuffer();
}

View File

@ -1,197 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.config.ServiceCode;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.config.ReportConfig;
import com.munjaon.server.server.dto.ReportDto;
import com.munjaon.server.server.packet.common.Packet;
import com.munjaon.server.util.FileUtil;
import com.munjaon.server.util.MessageUtil;
import lombok.Getter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReportQueue {
private final Object lockObject = new Object(); // Lock Object
@Getter
private String queuePathFile; // 사용자 파일
@Getter
private String userId; // 사용자 아이디
@Getter
private int writeCounter = 0; // 쓰기 카운트
@Getter
private int readCounter = 0; // 읽기 카운트
private FileChannel channel = null; // Queue File Channel
private ByteBuffer headBuffer = ByteBuffer.allocateDirect(ReportConfig.HEAD_LENGTH); // Queue Head Buffer
private ByteBuffer bodyBuffer = ByteBuffer.allocateDirect(ReportConfig.BODY_LENGTH); // Queue Body Buffer
private byte[] byteArray = null;
public ReportQueue(String queuePathFile, String userId) throws Exception {
this.queuePathFile = queuePathFile;
this.userId = userId;
initQueue();
}
private void initQueue() throws Exception {
/* 2. 경로 체크 및 생성 */
FileUtil.mkdirs(this.queuePathFile);
File file = new File(this.queuePathFile + File.separator + this.userId + ".queue");
this.channel = new RandomAccessFile(file, "rw").getChannel();
if (file.length() == 0) {
this.writeCounter = 0;
this.readCounter = 0;
writeHeader();
} else {
readHeader();
}
}
public void pushReportToQueue(ReportDto reportDto) throws Exception {
synchronized (lockObject) {
if (ServiceCode.OK.getCode() != MessageUtil.isValidateMessageForReport(reportDto)) {
return;
}
/* 1. buffer 초기화 및 데이터 Set */
initBodyBuffer();
MessageUtil.setBytesForReport(this.bodyBuffer, reportDto);
/* 2. Header 정보 다시 읽기 */
readHeader();
/* 3. 파일채널에 쓰기 */
this.channel.position(MessageUtil.calcWritePositionForReport(this.writeCounter, ReportConfig.BODY_LENGTH));
this.bodyBuffer.flip();
this.channel.write(this.bodyBuffer);
/* 4 Push 카운터 증가 및 head 저장 */
this.writeCounter = this.writeCounter + 1;
writeHeader();
}
}
public ReportDto popReportFromQueue() throws Exception {
synchronized (lockObject) {
/* 1. Header 정보 다시 읽기 */
readHeader();
/* 2. 읽을 데이터가 없는지 체크 */
if (this.writeCounter <= this.readCounter) {
return null;
}
/* 3. 채널에서 읽기 */
this.bodyBuffer.clear();
this.channel.position(MessageUtil.calcWritePositionForReport(this.readCounter, ReportConfig.BODY_LENGTH));
this.channel.read(this.bodyBuffer);
return MessageUtil.getReportFromBuffer(this.bodyBuffer);
}
}
public boolean isTruncateQueue(int maxQueueCount) {
synchronized (lockObject) {
if (this.writeCounter > 0 && this.writeCounter >= maxQueueCount) {
return this.writeCounter == this.readCounter;
}
return false;
}
}
public boolean isWriteLimit(int maxQueueCount) {
synchronized (lockObject) {
return this.writeCounter > 0 && this.writeCounter >= maxQueueCount;
}
}
public boolean isRemainReport() {
return this.writeCounter > this.readCounter;
}
public void truncateQueue() throws Exception {
synchronized (lockObject) {
if (isOpen()) {
this.channel.truncate(0);
this.writeCounter = 0;
this.readCounter = 0;
writeHeader();
}
}
}
private void readHeader() throws Exception {
initHeadBuffer();
this.channel.position(0);
this.channel.read(this.headBuffer);
this.byteArray = new byte[ReportConfig.USER_ID_LENGTH];
// USER_ID
this.headBuffer.position(ReportConfig.USER_ID_POSITION);
this.headBuffer.get(this.byteArray);
this.userId = (new String(this.byteArray)).trim();
// 쓰기 카운트 가져오기
this.byteArray = new byte[ReportConfig.WRITE_COUNT_LENGTH];
this.headBuffer.position(ReportConfig.WRITE_COUNT_POSITION);
this.headBuffer.get(this.byteArray);
this.writeCounter = Integer.parseInt((new String(this.byteArray)).trim());
// 읽기 카운트 가져오기
this.byteArray = new byte[ReportConfig.READ_COUNT_LENGTH];
this.headBuffer.position(ReportConfig.READ_COUNT_POSITION);
this.headBuffer.get(this.byteArray);
this.readCounter = Integer.parseInt((new String(this.byteArray)).trim());
}
public void addReadCounter() throws Exception {
synchronized (lockObject) {
/* 읽기 카운트 증가 */
this.readCounter = this.readCounter + 1;
writeHeader();
}
}
private void writeHeader() throws Exception {
initHeadBuffer();
this.channel.position(ReportConfig.USER_ID_POSITION);
this.headBuffer.put(this.userId.getBytes(Packet.AGENT_CHARACTER_SET));
this.headBuffer.position(ReportConfig.WRITE_COUNT_POSITION);
this.headBuffer.put(Integer.toString(this.writeCounter).getBytes(Packet.AGENT_CHARACTER_SET));
this.headBuffer.position(ReportConfig.READ_COUNT_POSITION);
this.headBuffer.put(Integer.toString(this.readCounter).getBytes(Packet.AGENT_CHARACTER_SET));
this.headBuffer.flip();
this.channel.write(this.headBuffer);
}
private void initHeadBuffer() {
this.headBuffer.clear();
for(int loopCnt = 0; loopCnt < ReportConfig.HEAD_LENGTH; loopCnt++){
this.headBuffer.put(ReportConfig.SET_DEFAULT_BYTE);
}
this.headBuffer.position(0);
}
public void initBodyBuffer() {
this.bodyBuffer.clear();
for(int loopCnt = 0; loopCnt < ReportConfig.BODY_LENGTH; loopCnt++){
this.bodyBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.bodyBuffer.position(0);
}
public void close() throws IOException {
try {
if (isOpen()) {
channel.close();
}
} catch(IOException e) {
throw e;
}
}
public boolean isOpen() {
if (this.channel == null) {
return false;
}
return this.channel.isOpen();
}
}

View File

@ -1,131 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.server.packet.common.Packet;
import com.munjaon.server.server.service.PropertyLoader;
import com.munjaon.server.util.FileUtil;
import lombok.Getter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SerialQueue {
/** Queue Header Buffer */
private ByteBuffer dataBuffer = null;
/** Header 에서 사용하는 변수 */
private byte[] dataArray = null;
/* 채번 큐 크기 */
private final int SERIAL_QUEUE_SIZE = 14;
/* 큐경로 */
@Getter
private String queuePath;
@Getter
private final String queueName = "SERIAL_QUEUE.queue";
@Getter
private Long serialNo = 0L;
/** Queue File Channel */
private FileChannel channel = null;
public SerialQueue() throws Exception {
initQueue();
}
private void initQueuePath() {
/* 1. 큐경로 */
this.queuePath = System.getProperty("ROOTPATH") + File.separator + "queue" + File.separator + "SERIAL_QUEUE";
/* 2. 경로 체크 및 생성 */
FileUtil.mkdirs(this.queuePath);
}
private void initQueue() throws Exception {
this.dataBuffer = ByteBuffer.allocateDirect(SERIAL_QUEUE_SIZE);
try{
/* 1. 큐경로 초기화 */
initQueuePath();
File file = new File(this.queuePath + File.separator + queueName);
this.channel = new RandomAccessFile(file, "rw").getChannel();
if (file.length() == 0) {
String msgid = PropertyLoader.getProp("SERIAL_QUEUE", "MSGID");
if (msgid == null) {
msgid = "0";
}
serialNo = Long.parseLong(msgid);
// 헤더 초기화
writeData();
} else {
readData();
}
// backupQueue();
} catch(Exception e) {
throw e;
} finally {
//lock.release();
}
}
private void readData() throws Exception {
try {
initDataBuffer();
this.channel.position(0);
this.channel.read(this.dataBuffer);
this.dataArray = new byte[SERIAL_QUEUE_SIZE];
this.dataBuffer.position(0);
this.dataBuffer.get(this.dataArray);
String no = QueueConstants.getString(this.dataArray);
serialNo = Long.parseLong(no);
System.out.println("SERIAL QUEUE NO: " + serialNo);
} catch(Exception e) {
throw e;
}
}
public String getSerialNumber() throws Exception {
this.serialNo = this.serialNo + 1;
writeData();
return String.valueOf(this.serialNo);
}
private void writeData() throws Exception {
try {
initDataBuffer();
this.channel.position(0);
this.dataBuffer.put(String.valueOf(serialNo).getBytes(Packet.AGENT_CHARACTER_SET));
this.dataBuffer.flip();
this.channel.write(this.dataBuffer);
} catch(Exception e) {
throw e;
}
}
private void initDataBuffer(){
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < SERIAL_QUEUE_SIZE; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
public void close() throws IOException {
try {
if (isOpen()) {
channel.close();
}
} catch(IOException e) {
throw e;
}
}
public boolean isOpen() {
if (this.channel == null) {
return false;
}
return this.channel.isOpen();
}
}

View File

@ -1,54 +0,0 @@
package com.munjaon.server.queue.pool;
public class SerialQueuePool {
/** Lock Object */
protected final Object lockMonitor = new Object();
/* Serial Queue */
private SerialQueue serialQueue;
private static SerialQueuePool queueInstance;
private SerialQueuePool() {}
public synchronized static SerialQueuePool getInstance() {
if (queueInstance == null) {
queueInstance = new SerialQueuePool();
}
return queueInstance;
}
public String getSerialNumber() throws Exception {
synchronized (lockMonitor) {
if (serialQueue == null || serialQueue.isOpen() == false) {
try {
lockMonitor.wait();
} catch(InterruptedException e) {
// 아무 처리도 하지 않는다.
}
}
return serialQueue.getSerialNumber();
}
}
public void setSerialQueue(SerialQueue serialQueue) {
synchronized(lockMonitor){
if (serialQueue != null){
this.serialQueue = serialQueue;
lockMonitor.notifyAll();
}
}
}
public boolean isReady() {
synchronized (lockMonitor) {
if (serialQueue != null && serialQueue.isOpen()) {
return true;
} else {
return false;
}
}
}
}

View File

@ -1,47 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.dto.BasicMessageDto;
import java.util.LinkedList;
public class SmsMemoryQueue {
/** Lock Object */
private final Object msgMonitor = new Object();
/** Message Queue */
private final LinkedList<BasicMessageDto> msgQueue = new LinkedList<>();
/** Singleton Instance */
private static SmsMemoryQueue memoryQueue;
public synchronized static SmsMemoryQueue getInstance() {
if(memoryQueue == null){
memoryQueue = new SmsMemoryQueue();
}
return memoryQueue;
}
/** MESSAGE QUEUE ************************************************************************ */
/** MESSAGE enQueue */
public void memoryEnQueue(BasicMessageDto data) {
synchronized(msgMonitor) {
msgQueue.addLast(data);
}
}
/** SMS deQueue */
public BasicMessageDto memoryDeQueue() {
synchronized(msgMonitor) {
if(msgQueue.isEmpty()) return null;
else return msgQueue.removeFirst();
}
}
/** SMS size */
public int getMemorySize(){
synchronized(msgMonitor) {
return msgQueue.size();
}
}
/** SMS isEmpty */
public boolean isMemoryEmpty() {
synchronized(msgMonitor) {
return msgQueue.isEmpty();
}
}
}

View File

@ -1,15 +0,0 @@
package com.munjaon.server.queue.pool;
public class SmsQueuePool extends QueuePool {
/** Singleton Instance */
private static SmsQueuePool queueInstance = null;
private SmsQueuePool() {}
public synchronized static SmsQueuePool getInstance(){
if(queueInstance == null){
queueInstance = new SmsQueuePool();
}
return queueInstance;
}
}

View File

@ -1,40 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.config.SmsBodyConfig;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class SmsReadQueue extends ReadQueue {
public SmsReadQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
// initQueue();
}
@Override
void popBuffer() throws Exception {
this.channel.position(MessageUtil.calcReadPosition(this.popCounter, SmsBodyConfig.SMS_SUM_BYTE_LENGTH));
this.channel.read(this.dataBuffer);
}
@Override
void getBytesForExtendMessage(BasicMessageDto messageDto) throws UnsupportedEncodingException {
MessageUtil.getBytesForSmsMessage(this.dataBuffer, messageDto);
}
@Override
void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(SmsBodyConfig.SMS_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < SmsBodyConfig.SMS_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,64 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.config.ServiceCode;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.config.SmsBodyConfig;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.util.MessageUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class SmsWriteQueue extends WriteQueue {
public SmsWriteQueue(QueueInfo queueInfo) throws Exception {
this.queueInfo = queueInfo;
/* 큐초기화 */
// initQueue();
}
@Override
public int isValidateMessageForExtend(BasicMessageDto messageDto) throws UnsupportedEncodingException {
/* 13. 메시지 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserMessage(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserMessage(), SmsBodyConfig.SMS_MSG_BYTE_LENGTH, false)) {
return ServiceCode.MSG_ERROR_SMS_MESSAGE.getCode();
}
return ServiceCode.OK.getCode();
}
@Override
public void pushMessageToBuffer(BasicMessageDto messageDto) throws Exception {
if (isValidateMessage(messageDto) == ServiceCode.OK.getCode()) {
/* 1. dataBuffer 초기화 */
initDataBuffer();
/* 2. messageDto >> dataBuffer */
MessageUtil.setBytesForCommonMessage(this.dataBuffer, messageDto);
MessageUtil.setBytesForSmsMessage(this.dataBuffer, messageDto);
/* 3. 파일큐에 적재 */
/* 3.1 Header 정보 다시 일기 */
readHeader();
if (this.dataBuffer != null){
this.channel.position(MessageUtil.calcWritePosition(this.pushCounter, SmsBodyConfig.SMS_SUM_BYTE_LENGTH));
this.dataBuffer.flip();
this.channel.write(this.dataBuffer);
/* 3.2 Push 카운터 증가 */
this.pushCounter = this.pushCounter + 1;
/* 3.3 Header 정보 변경 */
writeHeader();
}
}
}
@Override
public void initDataBuffer() {
if (this.dataBuffer == null) {
this.dataBuffer = ByteBuffer.allocateDirect(SmsBodyConfig.SMS_SUM_BYTE_LENGTH);
}
this.dataBuffer.clear();
for(int loopCnt = 0; loopCnt < SmsBodyConfig.SMS_SUM_BYTE_LENGTH; loopCnt++){
this.dataBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.dataBuffer.position(0);
}
}

View File

@ -1,245 +0,0 @@
package com.munjaon.server.queue.pool;
import com.munjaon.server.config.ServiceCode;
import com.munjaon.server.queue.config.BodyCommonConfig;
import com.munjaon.server.queue.config.QueueConstants;
import com.munjaon.server.queue.config.QueueHeaderConfig;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.dto.QueueInfo;
import com.munjaon.server.server.packet.common.Packet;
import com.munjaon.server.util.FileUtil;
import com.munjaon.server.util.JobFileFactory;
import com.munjaon.server.util.MessageUtil;
import lombok.Getter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public abstract class WriteQueue {
/** Queue Header Buffer */
protected ByteBuffer headerBuffer = null;
/** Header 에서 사용하는 변수 */
protected byte[] headerArray = null;
/** Queue Create Date - [Format:YYYYMMDD] */
@Getter
protected String createDate = "";
/** Queue Push Counter */
@Getter
protected int pushCounter = 0;
/* 큐경로 */
@Getter
protected String queuePath;
/** Queue File Channel */
protected FileChannel channel = null;
/** Queue Information */
@Getter
protected QueueInfo queueInfo = null;
/** pushBuffer() 함수에서 사용하는 변수 */
protected ByteBuffer dataBuffer = null;
protected void initQueuePath() {
/* 1. 큐경로 */
this.queuePath = System.getProperty("ROOTPATH") + File.separator + queueInfo.getQueuePath();
/* 2. 경로 체크 및 생성 */
FileUtil.mkdirs(this.queuePath);
}
public void initQueue() throws Exception {
this.headerBuffer = ByteBuffer.allocateDirect(QueueHeaderConfig.QUEUE_HEADER_LENGTH);
try{
/* 1. 큐경로 초기화 */
initQueuePath();
this.queueInfo.setQueueFileName(this.queuePath + File.separator + this.queueInfo.getQueueName() + ".queue");
File file = new File(this.queueInfo.getQueueFileName());
this.channel = new RandomAccessFile(file, "rw").getChannel();
if (file.length() == 0) {
// Push Pop 카운트 초기화
this.createDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
this.pushCounter = 0;
// 헤더 초기화
writeHeader();
} else {
readHeader();
}
// backupQueue();
} catch(Exception e) {
throw e;
} finally {
//lock.release();
}
}
public void backupQueue() throws IOException {
/* 1. 백업경로 */
String backupDir = this.queuePath + File.separator + "backup" + File.separator + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
/* 2. 파일 백업 */
JobFileFactory.transferFile(this.queuePath, this.queueInfo.getQueueName() + ".queue", backupDir, this.queueInfo.getQueueName() + ".queue");
}
protected void readHeader() throws Exception {
try {
initHeaderBuffer();
this.channel.position(0);
this.channel.read(this.headerBuffer);
this.headerArray = new byte[QueueHeaderConfig.CREATE_DATE_LENGTH];
// 생성날짜 가져오기 - 생성날짜(10) / 읽은카운트(10) / 쓴카운트(10)
this.headerBuffer.position(QueueHeaderConfig.CREATE_DATE_POSITION);
this.headerBuffer.get(this.headerArray);
this.createDate = QueueConstants.getString(this.headerArray);
// 카운트 가져오기
this.headerArray = new byte[QueueHeaderConfig.PUSH_COUNT_LENGTH];
this.headerBuffer.position(QueueHeaderConfig.PUSH_COUNT_POSITION);
this.headerBuffer.get(this.headerArray);
this.pushCounter = Integer.parseInt(QueueConstants.getString(this.headerArray));
} catch(Exception e) {
throw e;
}
}
protected void writeHeader() throws Exception {
try {
initHeaderBuffer();
this.channel.position(QueueHeaderConfig.CREATE_DATE_POSITION);
this.headerBuffer.put(this.createDate.getBytes(Packet.AGENT_CHARACTER_SET));
this.headerBuffer.position(QueueHeaderConfig.PUSH_COUNT_POSITION);
this.headerBuffer.put(Integer.toString(this.pushCounter).getBytes(Packet.AGENT_CHARACTER_SET));
this.headerBuffer.flip();
this.channel.write(this.headerBuffer);
} catch(Exception e) {
throw e;
}
}
protected void initHeaderBuffer(){
this.headerBuffer.clear();
for(int loopCnt = 0; loopCnt < QueueHeaderConfig.QUEUE_HEADER_LENGTH; loopCnt++){
this.headerBuffer.put(QueueConstants.SET_DEFAULT_BYTE);
}
this.headerBuffer.position(0);
}
public void close() throws IOException {
try {
if (isOpen()) {
channel.close();
}
} catch(IOException e) {
throw e;
}
}
protected boolean isOpen() {
if (this.channel == null) {
return false;
}
return this.channel.isOpen();
}
public void truncateQueue() throws Exception{
try {
/* 1. 날짜가 지난경우와 더이상 읽을 데이터가 없을 경우 큐를 초기화 */
String thisDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
if (this.createDate.equals(thisDate)) {
return;
}
if (isOpen()) {
/* 2. 헤더정보 읽기 */
readHeader();
/* 3. 파일 내용을 모두 지운다. */
channel.truncate(0);
/* 4. 헤더 정보를 초기화한다. */
this.createDate = thisDate;
this.pushCounter = 0;
/* 5. 헤더에 초기데이터를 저장 */
writeHeader();
}
} catch(Exception e) {
throw e;
}
}
public String getQueueName(){
if(this.queueInfo == null)
return null;
else
return this.queueInfo.getQueueName();
}
protected int isValidateMessage(BasicMessageDto messageDto) throws UnsupportedEncodingException {
int result = isValidateMessageForCommon(messageDto);
if (result != ServiceCode.OK.getCode()) {
return result;
}
return isValidateMessageForExtend(messageDto);
}
protected int isValidateMessageForCommon(BasicMessageDto messageDto) throws UnsupportedEncodingException {
/* 1. 사용자 아이디 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserId(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserId(), BodyCommonConfig.USERID_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_USERID.getCode();
}
/* 2. 요금제(선불 : P / 후불 : A) */
if (MessageUtil.isEmptyForMessage(messageDto.getFeeType(), true) || MessageUtil.isOverByteForMessage(messageDto.getFeeType(), BodyCommonConfig.FEETYPE_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_FEETYPE.getCode();
}
/* 3. 단가 */
if (MessageUtil.isEmptyForMessage(messageDto.getUnitCost(), true) || MessageUtil.isOverByteForMessage(messageDto.getUnitCost(), BodyCommonConfig.UNITCOST_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_UNITCOST.getCode();
}
/* 4. MSG Group ID */
if (MessageUtil.isEmptyForMessage(messageDto.getMsgGroupID(), true) || MessageUtil.isOverByteForMessage(messageDto.getMsgGroupID(), BodyCommonConfig.MSGGROUPID_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_MSGGROUPID.getCode();
}
/* 5. MSG ID */
if (MessageUtil.isEmptyForMessage(messageDto.getUserMsgID(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserMsgID(), BodyCommonConfig.MSGID_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_USERMSGID.getCode();
}
/* 6. Service Type */
if (MessageUtil.isEmptyForMessage(messageDto.getServiceType(), true) || MessageUtil.isOverByteForMessage(messageDto.getServiceType(), BodyCommonConfig.SERVICETYPE_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_SERVICETYPE.getCode();
}
/* 7. 메시지 전송 결과 >> 성공 : 0 / 필터링 : 기타값 */
if (MessageUtil.isEmptyForMessage(messageDto.getSendStatus(), true) || MessageUtil.isOverByteForMessage(messageDto.getSendStatus(), BodyCommonConfig.SENDSTATUS_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_SENDSTATUS.getCode();
}
/* 8. 회신번호 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserSender(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserSender(), BodyCommonConfig.SENDER_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_USERSENDER.getCode();
}
/* 9. 수신번호 */
if (MessageUtil.isEmptyForMessage(messageDto.getUserReceiver(), true) || MessageUtil.isOverByteForMessage(messageDto.getUserReceiver(), BodyCommonConfig.RECEIVER_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_USERRECEIVER.getCode();
}
/* 10. 요청시간 */
if (MessageUtil.isEmptyForMessage(messageDto.getRequestDt(), true) || MessageUtil.isOverByteForMessage(messageDto.getRequestDt(), BodyCommonConfig.REQUESTDT_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_REQUESTDT.getCode();
}
/* 11. 원격 주소 */
if (MessageUtil.isEmptyForMessage(messageDto.getRemoteIP(), true) || MessageUtil.isOverByteForMessage(messageDto.getRemoteIP(), BodyCommonConfig.REMOTEIP_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_REMOTEIP.getCode();
}
/* 12. 발송망 */
if (MessageUtil.isEmptyForMessage(messageDto.getRouterSeq(), true) || MessageUtil.isOverByteForMessage(messageDto.getRouterSeq(), BodyCommonConfig.AGENT_CODE_BYTE_LENGTH, true)) {
return ServiceCode.MSG_ERROR_ROUTERSEQ.getCode();
}
return ServiceCode.OK.getCode();
}
public abstract int isValidateMessageForExtend(BasicMessageDto messageDto) throws UnsupportedEncodingException;
public abstract void pushMessageToBuffer(BasicMessageDto messageDto) throws Exception;
public abstract void initDataBuffer();
}

View File

@ -1,99 +0,0 @@
package com.munjaon.server.queue.service;
import com.munjaon.server.cache.service.SerialNoService;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.mapper.KatMapper;
import com.munjaon.server.queue.pool.KakaoAlarmMemoryQueue;
import com.munjaon.server.queue.pool.KakaoAlarmQueuePool;
import com.munjaon.server.queue.pool.WriteQueue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class KakaoAlarmQueueService implements QueueAction {
private final KatMapper katMapper;
private final KakaoAlarmQueuePool queueInstance = KakaoAlarmQueuePool.getInstance();
private final KakaoAlarmMemoryQueue memoryQueue = KakaoAlarmMemoryQueue.getInstance();
private final SerialNoService serialNoService;
@Override
public int getQueueSize() {
return queueInstance.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
return queueInstance.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
queueInstance.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
queueInstance.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
queueInstance.pushQueue(data);
}
public void pushQueue_bak(BasicMessageDto data) {
boolean isError = false;
try {
queueInstance.pushQueue(data);
} catch (Exception e) {
isError = true;
// throw new RuntimeException(e);
}
if (isError) {
log.error("Push queue failed");
}
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
String serialNo = serialNoService.getSerialNo();
String groupSerialNo = serialNo.replace("MSGID", "MGRP");
data.setId(serialNo);
data.setMsgGroupID(groupSerialNo);
log.debug("Save message to table : {}", data);
return katMapper.insert(data);
}
@Override
@Transactional
public int saveMessageForList(List<BasicMessageDto> list) {
katMapper.insertGroupForList(list);
return katMapper.insertForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
memoryQueue.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
return memoryQueue.memoryDeQueue();
}
@Override
public int getMemorySize() {
return memoryQueue.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
return memoryQueue.isMemoryEmpty();
}
}

View File

@ -1,99 +0,0 @@
package com.munjaon.server.queue.service;
import com.munjaon.server.cache.service.SerialNoService;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.mapper.KftMapper;
import com.munjaon.server.queue.pool.KakaoAlarmMemoryQueue;
import com.munjaon.server.queue.pool.KakaoFriendQueuePool;
import com.munjaon.server.queue.pool.WriteQueue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class KakaoFriendQueueService implements QueueAction {
private final KftMapper kftMapper;
private final KakaoFriendQueuePool queueInstance = KakaoFriendQueuePool.getInstance();
private final KakaoAlarmMemoryQueue memoryQueue = KakaoAlarmMemoryQueue.getInstance();
private final SerialNoService serialNoService;
@Override
public int getQueueSize() {
return queueInstance.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
return queueInstance.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
queueInstance.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
queueInstance.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
queueInstance.pushQueue(data);
}
public void pushQueue_bak(BasicMessageDto data) {
boolean isError = false;
try {
queueInstance.pushQueue(data);
} catch (Exception e) {
isError = true;
// throw new RuntimeException(e);
}
if (isError) {
log.error("Push queue failed");
}
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
String serialNo = serialNoService.getSerialNo();
String groupSerialNo = serialNo.replace("MSGID", "MGRP");
data.setId(serialNo);
data.setMsgGroupID(groupSerialNo);
log.debug("Save message to table : {}", data);
return kftMapper.insert(data);
}
@Override
@Transactional
public int saveMessageForList(List<BasicMessageDto> list) {
kftMapper.insertGroupForList(list);
return kftMapper.insertForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
memoryQueue.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
return memoryQueue.memoryDeQueue();
}
@Override
public int getMemorySize() {
return memoryQueue.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
return memoryQueue.isMemoryEmpty();
}
}

View File

@ -0,0 +1,11 @@
package com.munjaon.server.queue.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class KakaoQueueService {
}

View File

@ -1,99 +1,11 @@
package com.munjaon.server.queue.service;
import com.munjaon.server.cache.service.SerialNoService;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.mapper.LmsMapper;
import com.munjaon.server.queue.pool.LmsMemoryQueue;
import com.munjaon.server.queue.pool.LmsQueuePool;
import com.munjaon.server.queue.pool.WriteQueue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class LmsQueueService implements QueueAction {
private final LmsMapper lmsMapper;
private final LmsQueuePool queueInstance = LmsQueuePool.getInstance();
private final LmsMemoryQueue memoryQueue = LmsMemoryQueue.getInstance();
private final SerialNoService serialNoService;
@Override
public int getQueueSize() {
return queueInstance.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
return queueInstance.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
queueInstance.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
queueInstance.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
queueInstance.pushQueue(data);
}
public void pushQueue_bak(BasicMessageDto data) {
boolean isError = false;
try {
queueInstance.pushQueue(data);
} catch (Exception e) {
isError = true;
// throw new RuntimeException(e);
}
if (isError) {
log.error("Push queue failed");
}
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
String serialNo = serialNoService.getSerialNo();
String groupSerialNo = serialNo.replace("MSGID", "MGRP");
data.setId(serialNo);
data.setMsgGroupID(groupSerialNo);
log.debug("Save message to table : {}", data);
return lmsMapper.insert(data);
}
@Override
@Transactional
public int saveMessageForList(List<BasicMessageDto> list) {
lmsMapper.insertGroupForList(list);
return lmsMapper.insertForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
memoryQueue.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
return memoryQueue.memoryDeQueue();
}
@Override
public int getMemorySize() {
return memoryQueue.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
return memoryQueue.isMemoryEmpty();
}
public class LmsQueueService {
}

View File

@ -1,99 +1,11 @@
package com.munjaon.server.queue.service;
import com.munjaon.server.cache.service.SerialNoService;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.mapper.MmsMapper;
import com.munjaon.server.queue.pool.MmsMemoryQueue;
import com.munjaon.server.queue.pool.MmsQueuePool;
import com.munjaon.server.queue.pool.WriteQueue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class MmsQueueService implements QueueAction {
private final MmsMapper mmsMapper;
private final MmsQueuePool queueInstance = MmsQueuePool.getInstance();
private final MmsMemoryQueue memoryQueue = MmsMemoryQueue.getInstance();
private final SerialNoService serialNoService;
@Override
public int getQueueSize() {
return queueInstance.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
return queueInstance.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
queueInstance.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
queueInstance.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
queueInstance.pushQueue(data);
}
public void pushQueue_bak(BasicMessageDto data) {
boolean isError = false;
try {
queueInstance.pushQueue(data);
} catch (Exception e) {
isError = true;
// throw new RuntimeException(e);
}
if (isError) {
log.error("Push queue failed");
}
}
@Override
public int saveMessageToTable(BasicMessageDto data) {
String serialNo = serialNoService.getSerialNo();
String groupSerialNo = serialNo.replace("MSGID", "MGRP");
data.setId(serialNo);
data.setMsgGroupID(groupSerialNo);
log.debug("Save message to table : {}", data);
return mmsMapper.insert(data);
}
@Override
@Transactional
public int saveMessageForList(List<BasicMessageDto> list) {
mmsMapper.insertGroupForList(list);
return mmsMapper.insertForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
memoryQueue.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
return memoryQueue.memoryDeQueue();
}
@Override
public int getMemorySize() {
return memoryQueue.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
return memoryQueue.isMemoryEmpty();
}
public class MmsQueueService {
}

View File

@ -1,21 +0,0 @@
package com.munjaon.server.queue.service;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.pool.WriteQueue;
import java.util.List;
public interface QueueAction {
int getQueueSize();
boolean isExistQueue(String name);
void removeQueue(String name);
void addQueue(WriteQueue queue);
void pushQueue(BasicMessageDto data) throws Exception;
int saveMessageToTable(BasicMessageDto data);
int saveMessageForList(List<BasicMessageDto> list);
void memoryEnQueue(BasicMessageDto data);
BasicMessageDto memoryDeQueue();
int getMemorySize();
boolean isMemoryEmpty();
}

View File

@ -16,24 +16,20 @@ public class QueueServiceInjector {
@Autowired
private MmsQueueService mmsQueueService;
@Autowired
private KakaoAlarmQueueService kakaoAlarmQueueService;
@Autowired
private KakaoFriendQueueService kakaoFriendQueueService;
private KakaoQueueService kakaoQueueService;
@PostConstruct
public void postConstruct() {
for (QueueService svc : EnumSet.allOf(QueueService.class)) {
switch (svc) {
case SMS_QUEUE_SERVICE: svc.setService(smsQueueService);
case SMS_QUEUE: svc.setService(smsQueueService);
break;
case LMS_QUEUE_SERVICE: svc.setService(lmsQueueService);
case LMS_QUEUE: svc.setService(lmsQueueService);
break;
case MMS_QUEUE_SERVICE: svc.setService(mmsQueueService);
case MMS_QUEUE: svc.setService(mmsQueueService);
break;
case KAT_QUEUE_SERVICE: svc.setService(kakaoAlarmQueueService);
case KAKAO_QUEUE: svc.setService(kakaoQueueService);
break;
case KFT_QUEUE_SERVICE: svc.setService(kakaoFriendQueueService);
break;
default: break;
}
}

View File

@ -1,100 +1,11 @@
package com.munjaon.server.queue.service;
import com.munjaon.server.cache.service.SerialNoService;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.mapper.SmsMapper;
import com.munjaon.server.queue.pool.SmsMemoryQueue;
import com.munjaon.server.queue.pool.SmsQueuePool;
import com.munjaon.server.queue.pool.WriteQueue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsQueueService implements QueueAction {
private final SmsMapper smsMapper;
private final SmsQueuePool queueInstance = SmsQueuePool.getInstance();
private final SmsMemoryQueue memoryQueue = SmsMemoryQueue.getInstance();
private final SerialNoService serialNoService;
@Override
public int getQueueSize() {
return queueInstance.getQueueSize();
}
@Override
public boolean isExistQueue(String name) {
return queueInstance.isExistQueue(name);
}
@Override
public void removeQueue(String name) {
queueInstance.removeQueue(name);
}
@Override
public void addQueue(WriteQueue queue) {
queueInstance.addQueue(queue);
}
@Override
public void pushQueue(BasicMessageDto data) throws Exception {
queueInstance.pushQueue(data);
}
public void pushQueue_bak(BasicMessageDto data) {
boolean isError = false;
try {
queueInstance.pushQueue(data);
} catch (Exception e) {
isError = true;
// throw new RuntimeException(e);
}
if (isError) {
log.error("Push queue failed");
}
}
@Override
@Transactional
public int saveMessageToTable(BasicMessageDto data) {
String serialNo = serialNoService.getSerialNo();
String groupSerialNo = serialNo.replace("MSGID", "MGRP");
data.setId(serialNo);
data.setMsgGroupID(groupSerialNo);
log.debug("Save message to table : {}", data);
return smsMapper.insert(data);
}
@Override
@Transactional
public int saveMessageForList(List<BasicMessageDto> list) {
smsMapper.insertGroupForList(list);
return smsMapper.insertForList(list);
}
@Override
public void memoryEnQueue(BasicMessageDto data) {
memoryQueue.memoryEnQueue(data);
}
@Override
public BasicMessageDto memoryDeQueue() {
return memoryQueue.memoryDeQueue();
}
@Override
public int getMemorySize() {
return memoryQueue.getMemorySize();
}
@Override
public boolean isMemoryEmpty() {
return memoryQueue.isMemoryEmpty();
}
public class SmsQueueService {
}

View File

@ -17,8 +17,6 @@ public class CacheScheduleService {
private String tableSchema;
/* 사용자 테이블 마지막 업데이트 시간 */
private String member_last_modified_time = null;
/* 사용자 설정 테이블 마지막 업데이트 시간 */
private String config_last_modified_time = null;
@Scheduled(cron="0/5 * * * * *")
public void doService() throws Exception {
@ -26,19 +24,18 @@ public class CacheScheduleService {
}
private void doMemberService() {
if (member_last_modified_time == null || config_last_modified_time == null) {
if (member_last_modified_time == null) {
log.info("Member List Info is First Caching~~~");
memberService.deleteAllMember();
// memberService.list();
/* 회원 정보 마지막 변경시간 저장 */
member_last_modified_time = memberService.getMemberLastModifiedTime(tableSchema);
config_last_modified_time = memberService.getConfigLastModifiedTime(tableSchema);
member_last_modified_time = memberService.getLastModifiedTime(tableSchema);
return;
}
/* 변경이 없는 경우 */
if (member_last_modified_time.equals(memberService.getMemberLastModifiedTime(tableSchema)) && config_last_modified_time.equals(memberService.getConfigLastModifiedTime(tableSchema))) {
if (member_last_modified_time.equals(memberService.getLastModifiedTime(tableSchema))) {
return;
}
@ -47,7 +44,6 @@ public class CacheScheduleService {
memberService.deleteAllMember();
// memberService.list();
/* 회원 정보 마지막 변경시간 저장 */
member_last_modified_time = memberService.getMemberLastModifiedTime(tableSchema);
config_last_modified_time = memberService.getConfigLastModifiedTime(tableSchema);
member_last_modified_time = memberService.getLastModifiedTime(tableSchema);
}
}

View File

@ -1,19 +0,0 @@
package com.munjaon.server.server.config;
public final class ServerConfig {
/* 서버 타임아웃 체크 시간 */
public static final int CYCLE_SOCKET_TIMEOUT = 3000;
/* 서버 연결후 로그인 만료 시간 */
public static final int LIMIT_BIND_TIMEOUT = 3000;
/* Session Check 만료 시간 */
public static final int LIMIT_LINK_CHECK_TIMEOUT = 10000;
/* 서버 프로퍼티 reload interval 시간 */
public static final Long INTERVAL_PROPERTY_RELOAD_TIME = 3000L;
/* 사용자 정보 조회 체크 시간 */
public static final long USER_STATUS_CYCLE_TIME = 60000;
/* Deliver Thread 실행 시간 */
public static final long DELIVER_EXEC_CYCLE_TIME = 3000;
/* Report Thread 실행 시간 */
public static final long REPORT_EXEC_CYCLE_TIME = 3000;
}

View File

@ -1,59 +0,0 @@
package com.munjaon.server.server.dto;
import com.munjaon.server.cache.dto.MemberDto;
import com.munjaon.server.queue.pool.KeyWriteQueue;
import com.munjaon.server.server.config.ServerConfig;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@Builder
@ToString
public class ConnectUserDto {
/* 로그인여부 */
private boolean isLogin;
/* 마지막 통신 시간 */
private Long lastTrafficTime;
/* 서비스 유형 */
private String serviceType;
/* 사용자 ID */
private String userId;
/* 사용자 접속 IP */
private String remoteIP;
/* 요금제(선불 : P / 후불 : A) */
private final String feeType = "A";
/* 요청 command */
private int command;
/* 요청을 처리중인지 여부 */
private boolean isRunningMode;
/* MSGID 중복큐 경로 */
private String msgKeyPath;
/* MSGID 중복큐 사이즈 */
private int msgIdQueueSize;
/* MSG ID 중복체크 큐 */
private KeyWriteQueue keyWriteQueue;
private MemberDto memberDto;
public int isAlive() {
if (isLogin) {
if (System.currentTimeMillis() - lastTrafficTime > ServerConfig.LIMIT_LINK_CHECK_TIMEOUT) {
return 2;
}
} else {
if (System.currentTimeMillis() - lastTrafficTime > ServerConfig.LIMIT_BIND_TIMEOUT) {
return 1;
}
}
return 0;
}
public void updateLastTrafficTime() {
this.lastTrafficTime = System.currentTimeMillis();
}
}

View File

@ -1,17 +0,0 @@
package com.munjaon.server.server.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@Builder
@ToString
public class HeaderDto {
private boolean isError;
private String version;
private int command;
private int bodyLength;
}

View File

@ -1,19 +0,0 @@
package com.munjaon.server.server.dto;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class ReportDto {
private String msgId;
private String userId;
private String agentMsgId;
private String agentCode;
private String msgType;
private String rsltDate;
private String rsltCode;
private String rsltNet;
}

View File

@ -1,48 +0,0 @@
package com.munjaon.server.server.dto;
import com.munjaon.server.cache.dto.MemberDto;
import com.munjaon.server.queue.pool.ReportQueue;
import com.munjaon.server.server.config.ServerConfig;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@Builder
@ToString
public class ReportUserDto {
private boolean isLogin; //로그인여부
private Long lastTrafficTime; //마지막 통신 시간
private String userId; //사용자 ID
private String remoteIP; //사용자 접속 IP
private String queuePath; //저장큐경로
private ReportQueue reportQueue; //ReportQueue
private MemberDto memberDto; //사용자 정보
private int command; //요청 command
private int maxWriteCount; //건당 Report 개수
private int maxQueueCount; //Report Queue에 유지할 건수
/* 요청을 처리중인지 여부 */
private boolean isRunningMode;
/* Report Queue 처리중인지 여부 */
private boolean isQueueMode;
public int isAlive() {
if (isLogin) {
if (System.currentTimeMillis() - lastTrafficTime > ServerConfig.LIMIT_LINK_CHECK_TIMEOUT) {
return 2;
}
} else {
if (System.currentTimeMillis() - lastTrafficTime > ServerConfig.LIMIT_BIND_TIMEOUT) {
return 1;
}
}
return 0;
}
public void updateLastTrafficTime() {
this.lastTrafficTime = System.currentTimeMillis();
}
}

View File

@ -1,100 +0,0 @@
package com.munjaon.server.server.packet.common;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
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.HEADER_LENGTH;
public static final String ENCRYPTION = "0";
public static ByteBuffer makeBindBuffer(String id, String pwd) throws UnsupportedEncodingException {
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(Packet.AGENT_CHARACTER_SET));
}
/* PWD */
if (pwd != null) {
buffer.put(BIND_PWD_POSITION, pwd.getBytes(Packet.AGENT_CHARACTER_SET));
}
/* ENCRYPTION */
buffer.put(BIND_ENCRYPTION_POSITION, ENCRYPTION.getBytes(Packet.AGENT_CHARACTER_SET));
return buffer;
}
public static ByteBuffer makeBindAckBuffer(String resultCode) throws UnsupportedEncodingException {
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(Packet.AGENT_CHARACTER_SET));
}
return buffer;
}
public static String getBindId(final ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
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 new String(destArray);
return Packet.getString(destArray);
}
}

View File

@ -1,183 +0,0 @@
package com.munjaon.server.server.packet.common;
import com.munjaon.server.util.CommonUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
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) throws UnsupportedEncodingException {
if (buffer == null || messageId == null) {
return;
}
buffer.put(DELIVER_MESSAGE_ID_POSITION, messageId.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMessageIdForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
if (buffer == null || sender == null) {
return;
}
sender = CommonUtil.cutString(CommonUtil.doNumber(sender), DELIVER_SENDER_LENGTH);
buffer.put(DELIVER_SENDER_POSITION, sender.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getSenderForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
if (buffer == null || receiver == null) {
return;
}
receiver = CommonUtil.cutString(CommonUtil.doNumber(receiver), DELIVER_RECEIVER_LENGTH);
buffer.put(DELIVER_RECEIVER_POSITION, receiver.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getReceiverForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
if (buffer == null || reserveTime == null) {
return;
}
buffer.put(DELIVER_RESERVE_TIME_POSITION, reserveTime.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getReserveTimeForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
if (buffer == null || requestTime == null) {
return;
}
buffer.put(DELIVER_REQUEST_TIME_POSITION, requestTime.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getRequestTimeForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
if (buffer == null || msgType == null) {
return;
}
buffer.put(DELIVER_MSG_TYPE_POSITION, msgType.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMsgTypeForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
if (buffer == null || messageId == null) {
return;
}
buffer.put(DELIVER_ACK_MESSAGE_ID_POSITION, messageId.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMessageIdForDeliverAck(ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
if (buffer == null || result == null) {
return;
}
buffer.put(DELIVER_ACK_RESULT_POSITION, result.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getResultForDeliverAck(ByteBuffer buffer) throws UnsupportedEncodingException {
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);
}
}

View File

@ -1,110 +0,0 @@
package com.munjaon.server.server.packet.common;
import com.munjaon.server.util.ByteUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
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) throws UnsupportedEncodingException {
if (buffer == null) {
return;
}
buffer.put(VERSION_POSITION, VERSION.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getVersion(final ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(VERSION_POSITION);
byte[] destArray = new byte[VERSION_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
// return new String(destArray);
}
public static void putCommand(final ByteBuffer buffer, String command) throws UnsupportedEncodingException {
if (buffer == null) {
return;
}
buffer.put(COMMAND_POSITION, command.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getCommand(final ByteBuffer buffer) throws UnsupportedEncodingException {
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) throws UnsupportedEncodingException {
putBodyLength(buffer, Integer.toString(bodyLength));
}
public static String getBodyLength(final ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(BODY_POSITION);
byte[] destArray = new byte[BODY_LENGTH];
buffer.get(destArray);
System.out.println(ByteUtil.byteToHex(destArray));
return Packet.getString(destArray);
}
public static void putBodyLength(final ByteBuffer buffer, String bodyLength) throws UnsupportedEncodingException {
if (buffer == null) {
return;
}
buffer.put(BODY_POSITION, bodyLength.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static void putHeader(final ByteBuffer buffer, String command, int bodyLength) throws UnsupportedEncodingException {
putHeader(buffer, command, Integer.toString(bodyLength));
}
public static void putHeader(final ByteBuffer buffer, String command, String bodyLength) throws UnsupportedEncodingException {
putVersion(buffer);
putCommand(buffer, command);
putBodyLength(buffer, bodyLength);
}
}

View File

@ -1,144 +0,0 @@
package com.munjaon.server.server.packet.common;
import com.munjaon.server.util.CommonUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public final class KakaoMessage {
/* 카카오 파일 수신 분배 바이트 수 */
public static final int KAKAO_FILE_UNIT_BYTES = 1024;
public static final int LIMIT_FILE_CAPACITY = 1024 * 50;
public static final int DELIVER_JSON_FILENAME_LENGTH = 40;
public static final int DELIVER_JSON_FILENAME_POSITION = 0;
public static final int DELIVER_JSON_FILESIZE_LENGTH = 8;
public static final int DELIVER_JSON_FILESIZE_POSITION = DELIVER_JSON_FILENAME_POSITION + DELIVER_JSON_FILENAME_LENGTH;
public static final int DELIVER_KAKAO_BODY_LENGTH = 2233;
public static final int DELIVER_KAKAO_ACK_BODY_LENGTH = 21;
/* DELIVER */
/* SUBJECT */
public static final int DELIVER_SUBJECT_LENGTH = 40;
public static final int DELIVER_SUBJECT_POSITION = CommonMessage.DELIVER_MSG_TYPE_POSITION + CommonMessage.DELIVER_MSG_TYPE_LENGTH;
/* MESSAGE */
public static final int DELIVER_MESSAGE_LENGTH = 2000;
public static final int DELIVER_MESSAGE_POSITION = DELIVER_SUBJECT_POSITION + DELIVER_SUBJECT_LENGTH;
/* KAKAO_SENDER_KEY */
public static final int DELIVER_KAKAO_SENDER_KEY_LENGTH = 40;
public static final int DELIVER_KAKAO_SENDER_KEY_POSITION = DELIVER_MESSAGE_POSITION + DELIVER_MESSAGE_LENGTH;
/* KAKAO_TEMPLATE_CODE */
public static final int DELIVER_KAKAO_TEMPLATE_CODE_LENGTH = 64;
public static final int DELIVER_KAKAO_TEMPLATE_CODE_POSITION = DELIVER_KAKAO_SENDER_KEY_POSITION + DELIVER_KAKAO_SENDER_KEY_LENGTH;
public static void putSubjectForDeliver(ByteBuffer buffer, String subject) throws UnsupportedEncodingException {
if (buffer == null || subject == null) {
return;
}
subject = CommonUtil.cutString(subject, DELIVER_SUBJECT_LENGTH);
buffer.put(DELIVER_SUBJECT_POSITION, subject.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getSubjectForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_SUBJECT_POSITION);
byte[] destArray = new byte[DELIVER_SUBJECT_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static void putMessageForDeliver(ByteBuffer buffer, String message) throws UnsupportedEncodingException {
if (buffer == null || message == null) {
return;
}
message = CommonUtil.cutString(message, DELIVER_MESSAGE_LENGTH);
buffer.put(DELIVER_MESSAGE_POSITION, message.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMessageForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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 putKakaoSenderKeyForDeliver(ByteBuffer buffer, String kakaoSenderKey) throws UnsupportedEncodingException {
if (buffer == null || kakaoSenderKey == null) {
return;
}
kakaoSenderKey = CommonUtil.cutString(kakaoSenderKey, DELIVER_KAKAO_SENDER_KEY_LENGTH);
buffer.put(DELIVER_KAKAO_SENDER_KEY_POSITION, kakaoSenderKey.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getKakaoSenderKeyForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_KAKAO_SENDER_KEY_POSITION);
byte[] destArray = new byte[DELIVER_KAKAO_SENDER_KEY_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static void putKakaoTemplateCodeForDeliver(ByteBuffer buffer, String kakaoTemplateCode) throws UnsupportedEncodingException {
if (buffer == null || kakaoTemplateCode == null) {
return;
}
kakaoTemplateCode = CommonUtil.cutString(kakaoTemplateCode, DELIVER_KAKAO_TEMPLATE_CODE_LENGTH);
buffer.put(DELIVER_KAKAO_TEMPLATE_CODE_POSITION, kakaoTemplateCode.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getKakaoTemplateCodeForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_KAKAO_TEMPLATE_CODE_POSITION);
byte[] destArray = new byte[DELIVER_KAKAO_TEMPLATE_CODE_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static String getFileNameForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_JSON_FILENAME_POSITION);
byte[] destArray = new byte[DELIVER_JSON_FILENAME_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static String getFileSizeForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_JSON_FILESIZE_POSITION);
byte[] destArray = new byte[DELIVER_JSON_FILESIZE_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static ByteBuffer makeDeliverAckBuffer(String msgId, String status) throws UnsupportedEncodingException {
ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + DELIVER_KAKAO_ACK_BODY_LENGTH);
Packet.setDefaultByte(buffer);
Header.putHeader(buffer, Header.COMMAND_DELIVER_ACK, DELIVER_KAKAO_ACK_BODY_LENGTH);
buffer.put(CommonMessage.DELIVER_ACK_MESSAGE_ID_POSITION, msgId.getBytes(Packet.AGENT_CHARACTER_SET));
buffer.put(CommonMessage.DELIVER_ACK_RESULT_POSITION, status.getBytes(Packet.AGENT_CHARACTER_SET));
return buffer;
}
}

View File

@ -1,44 +0,0 @@
package com.munjaon.server.server.packet.common;
import java.io.UnsupportedEncodingException;
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.HEADER_LENGTH;
public static final int LINK_CHECK_ACK_BODY_LENGTH = 3;
public static final int LINK_CHECK_ACK_BODY_POSITION = Header.HEADER_LENGTH;
public static String LINK_CHECK_VALUE = "100";
public static String LINK_CHECK_ACK_VALUE = "100";
public static ByteBuffer makeLinkCheckBuffer() throws UnsupportedEncodingException {
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(Packet.AGENT_CHARACTER_SET));
return buffer;
}
public static ByteBuffer makeLinkCheckAckBuffer() throws UnsupportedEncodingException {
ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + LINK_CHECK_ACK_BODY_LENGTH);
Packet.setDefaultByte(buffer);
Header.putHeader(buffer, Header.COMMAND_LINK_CHECK_ACK, LINK_CHECK_ACK_BODY_LENGTH);
buffer.put(LINK_CHECK_ACK_BODY_POSITION, LINK_CHECK_ACK_VALUE.getBytes(Packet.AGENT_CHARACTER_SET));
return buffer;
}
// public static ByteBuffer bufferForSend;
// public static ByteBuffer bufferForAck;
//
// static {
// bufferForSend = ByteBuffer.allocateDirect(Header.HEADER_LENGTH + LINK_CHECK_BODY_LENGTH);
// Header.putHeader(bufferForSend, Header.COMMAND_LINK_CHECK, LINK_CHECK_BODY_LENGTH);
// bufferForSend.put(LINK_CHECK_BODY_POSITION, LINK_CHECK_VALUE.getBytes());
//
// bufferForAck = ByteBuffer.allocateDirect(Header.HEADER_LENGTH + LINK_CHECK_ACK_BODY_LENGTH);
// Header.putHeader(bufferForAck, Header.COMMAND_LINK_CHECK_ACK, LINK_CHECK_ACK_BODY_LENGTH);
// bufferForSend.put(LINK_CHECK_ACK_BODY_POSITION, LINK_CHECK_ACK_VALUE.getBytes());
// }
}

View File

@ -1,88 +0,0 @@
package com.munjaon.server.server.packet.common;
import com.munjaon.server.util.CommonUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public final class LmsMessage {
public static final int DELIVER_LMS_BODY_LENGTH = 2129;
public static final int DELIVER_LMS_ACK_BODY_LENGTH = 21;
/* DELIVER */
/* SUBJECT */
public static final int DELIVER_SUBJECT_LENGTH = 40;
public static final int DELIVER_SUBJECT_POSITION = CommonMessage.DELIVER_MSG_TYPE_POSITION + CommonMessage.DELIVER_MSG_TYPE_LENGTH;
/* MESSAGE */
public static final int DELIVER_MESSAGE_LENGTH = 2000;
public static final int DELIVER_MESSAGE_POSITION = DELIVER_SUBJECT_POSITION + DELIVER_SUBJECT_LENGTH;
public static void putSubjectForDeliver(ByteBuffer buffer, String subject) throws UnsupportedEncodingException {
if (buffer == null || subject == null) {
return;
}
subject = CommonUtil.cutString(subject, DELIVER_SUBJECT_LENGTH);
buffer.put(DELIVER_SUBJECT_POSITION, subject.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getSubjectForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_SUBJECT_POSITION);
byte[] destArray = new byte[DELIVER_SUBJECT_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static void putMessageForDeliver(ByteBuffer buffer, String message) throws UnsupportedEncodingException {
if (buffer == null || message == null) {
return;
}
message = CommonUtil.cutString(message, DELIVER_MESSAGE_LENGTH);
buffer.put(DELIVER_MESSAGE_POSITION, message.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMessageForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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 ByteBuffer makeDeliverAckBuffer(String msgId, String status) throws UnsupportedEncodingException {
ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + DELIVER_LMS_ACK_BODY_LENGTH);
Packet.setDefaultByte(buffer);
Header.putHeader(buffer, Header.COMMAND_DELIVER_ACK, DELIVER_LMS_ACK_BODY_LENGTH);
buffer.put(CommonMessage.DELIVER_ACK_MESSAGE_ID_POSITION, msgId.getBytes(Packet.AGENT_CHARACTER_SET));
buffer.put(CommonMessage.DELIVER_ACK_RESULT_POSITION, status.getBytes(Packet.AGENT_CHARACTER_SET));
return buffer;
}
// 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());
// /* Subject */
// putSubjectForDeliver(buffer, data.getSubject());
// /* MSG */
// putMessageForDeliver(buffer, data.getMessage());
// }
}

View File

@ -1,150 +0,0 @@
package com.munjaon.server.server.packet.common;
import com.munjaon.server.util.CommonUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public final class MmsMessage {
/* MMS 파일 수신 분배 바이트 수 */
public static final int MMS_IMAGE_UNIT_BYTES = 1024;
public static final int DELIVER_MMS_BODY_LENGTH = 2130;
public static final int DELIVER_MMS_ACK_BODY_LENGTH = 21;
/* DELIVER */
/* SUBJECT */
public static final int DELIVER_SUBJECT_LENGTH = 40;
public static final int DELIVER_SUBJECT_POSITION = CommonMessage.DELIVER_MSG_TYPE_POSITION + CommonMessage.DELIVER_MSG_TYPE_LENGTH;
/* MESSAGE */
public static final int DELIVER_MESSAGE_LENGTH = 2000;
public static final int DELIVER_MESSAGE_POSITION = DELIVER_SUBJECT_POSITION + DELIVER_SUBJECT_LENGTH;
/* FILECOUNT */
public static final int DELIVER_FILECOUNT_LENGTH = 1;
public static final int DELIVER_FILECOUNT_POSITION = DELIVER_MESSAGE_POSITION + DELIVER_MESSAGE_LENGTH;
public static final int LIMIT_FILE_CAPACITY = 1024 * 300;
public static final int DELIVER_MMS_FILENAME_LENGTH = 40;
public static final int DELIVER_MMS_FILENAME_POSITION = 0;
public static final int DELIVER_MMS_FILESIZE_LENGTH = 8;
public static final int DELIVER_MMS_FILESIZE_POSITION = DELIVER_MMS_FILENAME_POSITION + DELIVER_MMS_FILENAME_LENGTH;
public static void putSubjectForDeliver(ByteBuffer buffer, String subject) throws UnsupportedEncodingException {
if (buffer == null || subject == null) {
return;
}
subject = CommonUtil.cutString(subject, DELIVER_SUBJECT_LENGTH);
buffer.put(DELIVER_SUBJECT_POSITION, subject.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getSubjectForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_SUBJECT_POSITION);
byte[] destArray = new byte[DELIVER_SUBJECT_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static void putMessageForDeliver(ByteBuffer buffer, String message) throws UnsupportedEncodingException {
if (buffer == null || message == null) {
return;
}
message = CommonUtil.cutString(message, DELIVER_MESSAGE_LENGTH);
buffer.put(DELIVER_MESSAGE_POSITION, message.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMessageForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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 putFileCountForDeliver(ByteBuffer buffer, int fileCount) throws UnsupportedEncodingException {
putFileCountForDeliver(buffer, Integer.toString(fileCount));
}
public static void putFileCountForDeliver(ByteBuffer buffer, String fileCount) throws UnsupportedEncodingException {
if (buffer == null || fileCount == null) {
return;
}
buffer.put(DELIVER_FILECOUNT_POSITION, fileCount.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getFileCountForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_FILECOUNT_POSITION);
byte[] destArray = new byte[DELIVER_FILECOUNT_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static String getFileNameForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_MMS_FILENAME_POSITION);
byte[] destArray = new byte[DELIVER_MMS_FILENAME_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static String getFileSizeForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(DELIVER_MMS_FILESIZE_POSITION);
byte[] destArray = new byte[DELIVER_MMS_FILESIZE_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static ByteBuffer makeDeliverAckBuffer(String msgId, String status) throws UnsupportedEncodingException {
ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + DELIVER_MMS_ACK_BODY_LENGTH);
Packet.setDefaultByte(buffer);
Header.putHeader(buffer, Header.COMMAND_DELIVER_ACK, DELIVER_MMS_ACK_BODY_LENGTH);
buffer.put(CommonMessage.DELIVER_ACK_MESSAGE_ID_POSITION, msgId.getBytes(Packet.AGENT_CHARACTER_SET));
buffer.put(CommonMessage.DELIVER_ACK_RESULT_POSITION, status.getBytes(Packet.AGENT_CHARACTER_SET));
return buffer;
}
// 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());
// /* Subject */
// putSubjectForDeliver(buffer, data.getSubject());
// /* MSG */
// putMessageForDeliver(buffer, data.getMessage());
// /* FileCount */
// putFileCountForDeliver(buffer, data.getFileCount());
// }
}

View File

@ -1,83 +0,0 @@
package com.munjaon.server.server.packet.common;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public final class Packet {
public static final String AGENT_CHARACTER_SET = "EUC-KR";
public static final byte SET_DEFAULT_BYTE = (byte) 0x00;
/* LinkCheck 전송 체크 시간 간격 */
public static final long LINK_CHECK_CYCLE = 10000L;
/* 패킷 만료 시간 체크 */
public static final long LIMIT_PACKET_TIMEOUT = 25000L;
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);
}
}
public static String getString(byte[] srcArray) throws UnsupportedEncodingException {
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, Packet.AGENT_CHARACTER_SET);
}
public static void mergeBuffers(ByteBuffer dest, ByteBuffer srcHead, ByteBuffer srcBody) {
if (dest == null || srcHead == null || srcBody == null) {
return;
}
if (dest.capacity() != (srcHead.capacity() + srcBody.capacity())) {
return;
}
for (int i = 0; i < srcHead.capacity(); i++) {
dest.put(i, srcHead.get(i));
}
for (int i = 0; i < srcBody.capacity(); i++) {
dest.put((i + srcHead.capacity()), srcBody.get(i));
}
}
public static void mergeBuffers(ByteBuffer dest, ByteBuffer src, int destOffset) {
if (dest == null || src == null) {
return;
}
for (int i = 0; i < src.capacity(); i++) {
dest.put((destOffset + i), src.get(i));
}
}
public static void printBuffer(ByteBuffer buffer) {
if (buffer == null) {
return;
}
byte[] srcArray = buffer.array();
for (int i = 0; i < srcArray.length; i++) {
System.out.print(srcArray[i] + " ");
}
}
}

View File

@ -1,161 +0,0 @@
package com.munjaon.server.server.packet.common;
import com.munjaon.server.server.dto.ReportDto;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public final class Report {
/* MSG_ID (Length : 20 / Position : 0) */
public static final int REPORT_MSG_ID_LENGTH = 20;
public static final int REPORT_MSG_ID_POSITION = Header.HEADER_LENGTH;
/* AGENT_CODE (Length : 2 / Position : 20) */
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;
/* SEND_TIME (Length : 14 / Position : 22) */
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;
/* TELECOM (Length : 3 / Position : 36) */
public static final int REPORT_TELECOM_LENGTH = 3;
public static final int REPORT_TELECOM_POSITION = REPORT_SEND_TIME_POSITION + REPORT_SEND_TIME_LENGTH;
/* RESULT (Length : 5 / Position : 39) */
public static final int REPORT_RESULT_LENGTH = 5;
public static final int REPORT_RESULT_POSITION = REPORT_TELECOM_POSITION + REPORT_TELECOM_LENGTH;
/* Report 길이 */
public static final int REPORT_BODY_LENGTH = REPORT_RESULT_POSITION + REPORT_RESULT_LENGTH;
/* RESULT (Length : 5 / Position : 39) */
public static final int REPORT_ACK_RESULT_LENGTH = 1;
public static final int REPORT_ACK_RESULT_POSITION = 0;
public static final int REPORT_ACK_BODY_LENGTH = REPORT_ACK_RESULT_POSITION + REPORT_ACK_RESULT_LENGTH;
public static void putReport(final ByteBuffer buffer, final ReportDto reportDto) throws UnsupportedEncodingException {
if (reportDto == null) {
return;
}
putMsgId(buffer, reportDto.getMsgId());
putAgentCode(buffer, reportDto.getAgentCode());
putSendTime(buffer, reportDto.getRsltDate());
putTelecom(buffer, reportDto.getRsltNet());
putResult(buffer, reportDto.getRsltCode());
}
public static void putMsgId(final ByteBuffer buffer, String msgId) throws UnsupportedEncodingException {
if (buffer == null || msgId == null) {
return;
}
buffer.put(REPORT_MSG_ID_POSITION, msgId.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMsgId(final ByteBuffer buffer) throws UnsupportedEncodingException {
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 putAgentCode(final ByteBuffer buffer, String agentCode) throws UnsupportedEncodingException {
if (buffer == null || agentCode == null) {
return;
}
buffer.put(REPORT_AGENT_CODE_POSITION, agentCode.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getAgentCode(final ByteBuffer buffer) throws UnsupportedEncodingException {
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 putSendTime(final ByteBuffer buffer, String sendTime) throws UnsupportedEncodingException {
if (buffer == null || sendTime == null) {
return;
}
buffer.put(REPORT_SEND_TIME_POSITION, sendTime.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getSendTime(final ByteBuffer buffer) throws UnsupportedEncodingException {
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 putTelecom(final ByteBuffer buffer, String telecom) throws UnsupportedEncodingException {
if (buffer == null || telecom == null) {
return;
}
buffer.put(REPORT_TELECOM_POSITION, telecom.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getTelecom(final ByteBuffer buffer) throws UnsupportedEncodingException {
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 putResult(final ByteBuffer buffer, String result) throws UnsupportedEncodingException {
if (buffer == null || result == null) {
return;
}
buffer.put(REPORT_RESULT_POSITION, result.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getResult(final ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(REPORT_RESULT_POSITION);
byte[] destArray = new byte[REPORT_RESULT_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
public static void putResultAck(final ByteBuffer buffer, String result) throws UnsupportedEncodingException {
if (buffer == null || result == null) {
return;
}
buffer.put(REPORT_ACK_RESULT_POSITION, result.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getResultAck(final ByteBuffer buffer) throws UnsupportedEncodingException {
if (buffer == null) {
return null;
}
buffer.position(REPORT_ACK_RESULT_POSITION);
byte[] destArray = new byte[REPORT_ACK_RESULT_LENGTH];
buffer.get(destArray);
return Packet.getString(destArray);
}
}

View File

@ -1,45 +0,0 @@
package com.munjaon.server.server.packet.common;
import com.munjaon.server.util.CommonUtil;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
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) throws UnsupportedEncodingException {
if (buffer == null || message == null) {
return;
}
message = CommonUtil.cutString(message, DELIVER_MESSAGE_LENGTH);
buffer.put(DELIVER_MESSAGE_POSITION, message.getBytes(Packet.AGENT_CHARACTER_SET));
}
public static String getMessageForDeliver(ByteBuffer buffer) throws UnsupportedEncodingException {
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 ByteBuffer makeDeliverAckBuffer(String msgId, String status) throws UnsupportedEncodingException {
ByteBuffer buffer = ByteBuffer.allocate(Header.HEADER_LENGTH + DELIVER_SMS_ACK_BODY_LENGTH);
Packet.setDefaultByte(buffer);
Header.putHeader(buffer, Header.COMMAND_DELIVER_ACK, DELIVER_SMS_ACK_BODY_LENGTH);
buffer.put(CommonMessage.DELIVER_ACK_MESSAGE_ID_POSITION, msgId.getBytes(Packet.AGENT_CHARACTER_SET));
buffer.put(CommonMessage.DELIVER_ACK_RESULT_POSITION, status.getBytes(Packet.AGENT_CHARACTER_SET));
return buffer;
}
}

View File

@ -1,49 +0,0 @@
package com.munjaon.server.server.packet.deliver;
import com.munjaon.server.cache.dto.MemberDto;
import com.munjaon.server.server.queue.CollectUserQueue;
public final class DeliverBind {
public static String checkDuplicate(CollectUserQueue collectUserQueue, String serviceType, String id) {
if (collectUserQueue == null || serviceType == null || id == null) {
return "60";
}
if (collectUserQueue.isExist(serviceType, id)) {
return "60";
}
return "00";
}
public static String checkService(MemberDto memberDto, String serviceType, String id, String pwd) {
if (id == null || pwd == null) {
return "50";
}
if (memberDto == null || !pwd.equals(memberDto.getAccessKey())) {
return "20";
}
/* 회원 사용 상태 */
if (memberDto.getMberSttus() == null || "N".equals(memberDto.getMberSttus())) {
return "30";
}
/* 서비스 이용 상태 */
if ("SMS".equals(serviceType) && "N".equals(memberDto.getSmsUseYn())) {
return "30";
}
if ("LMS".equals(serviceType) && "N".equals(memberDto.getLmsUseYn())) {
return "30";
}
if ("MMS".equals(serviceType) && "N".equals(memberDto.getMmsUseYn())) {
return "30";
}
if ("KAT".equals(serviceType) && "N".equals(memberDto.getKakaoAtUseYn())) {
return "30";
}
if ("KFT".equals(serviceType) && "N".equals(memberDto.getKakaoFtUseYn())) {
return "30";
}
return "00";
}
}

View File

@ -1,118 +0,0 @@
package com.munjaon.server.server.queue;
import com.munjaon.server.server.dto.ConnectUserDto;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CollectUserQueue {
private final Object lockObject = new Object(); // Lock Object
private final Map<String, ConnectUserDto> smstUserQueue = new LinkedHashMap<>();
private final Map<String, ConnectUserDto> lmsUserQueue = new LinkedHashMap<>();
private final Map<String, ConnectUserDto> mmsUserQueue = new LinkedHashMap<>();
private final Map<String, ConnectUserDto> katUserQueue = new LinkedHashMap<>();
private final Map<String, ConnectUserDto> kftUserQueue = new LinkedHashMap<>();
private static CollectUserQueue collectUserQueue;
private CollectUserQueue() {}
public synchronized static CollectUserQueue getInstance() {
if (collectUserQueue == null) {
collectUserQueue = new CollectUserQueue();
}
return collectUserQueue;
}
public void putUser(final String serviceType, final ConnectUserDto user) {
synchronized (lockObject) {
switch (serviceType) {
case "SMS" : smstUserQueue.put(user.getUserId(), user); break;
case "LMS" : lmsUserQueue.put(user.getUserId(), user); break;
case "MMS" : mmsUserQueue.put(user.getUserId(), user); break;
case "KAT" : katUserQueue.put(user.getUserId(), user); break;
case "KFT" : kftUserQueue.put(user.getUserId(), user); break;
default: break;
}
}
}
public ConnectUserDto getUser(final String serviceType, final String userId) {
synchronized (lockObject) {
switch (serviceType) {
case "SMS" : return smstUserQueue.get(userId);
case "LMS" : return lmsUserQueue.get(userId);
case "MMS" : return mmsUserQueue.get(userId);
case "KAT" : return katUserQueue.get(userId);
case "KFT" : return kftUserQueue.get(userId);
default: return null;
}
}
}
public List<ConnectUserDto> getUsers(final String serviceType) {
synchronized (lockObject) {
switch (serviceType) {
case "SMS" : return new ArrayList<>(smstUserQueue.values());
case "LMS" : return new ArrayList<>(lmsUserQueue.values());
case "MMS" : return new ArrayList<>(mmsUserQueue.values());
case "KAT" : return new ArrayList<>(katUserQueue.values());
case "KFT" : return new ArrayList<>(kftUserQueue.values());
default: return null;
}
}
}
public boolean isExist(final String serviceType, final String userId) {
synchronized (lockObject) {
switch (serviceType) {
case "SMS" : return smstUserQueue.containsKey(userId);
case "LMS" : return lmsUserQueue.containsKey(userId);
case "MMS" : return mmsUserQueue.containsKey(userId);
case "KAT" : return katUserQueue.containsKey(userId);
case "KFT" : return kftUserQueue.containsKey(userId);
default: return false;
}
}
}
public void removeUser(final String serviceType, final String userId) {
synchronized (lockObject) {
switch (serviceType) {
case "SMS" : smstUserQueue.remove(userId); break;
case "LMS" : lmsUserQueue.remove(userId); break;
case "MMS" : mmsUserQueue.remove(userId); break;
case "KAT" : katUserQueue.remove(userId); break;
case "KFT" : kftUserQueue.remove(userId); break;
default: break;
}
}
}
public int size(final String serviceType) {
synchronized (lockObject) {
switch (serviceType) {
case "SMS" : return smstUserQueue.size();
case "LMS" : return lmsUserQueue.size();
case "MMS" : return mmsUserQueue.size();
case "KAT" : return katUserQueue.size();
case "KFT" : return kftUserQueue.size();
default: return 0;
}
}
}
public boolean isEmpty(final String serviceType) {
synchronized (lockObject) {
switch (serviceType) {
case "SMS" : return smstUserQueue.isEmpty();
case "LMS" : return lmsUserQueue.isEmpty();
case "MMS" : return mmsUserQueue.isEmpty();
case "KAT" : return katUserQueue.isEmpty();
case "KFT" : return kftUserQueue.isEmpty();
default: return true;
}
}
}
}

View File

@ -1,76 +0,0 @@
package com.munjaon.server.server.queue;
import com.munjaon.server.queue.pool.ReportQueue;
import com.munjaon.server.server.dto.ReportUserDto;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ReportUserQueue {
private final Object lockObject = new Object(); // Lock Object
private final Map<String, ReportUserDto> connectUserQueue = new LinkedHashMap<>();
private static ReportUserQueue reportUserQueue;
private ReportUserQueue() {}
public synchronized static ReportUserQueue getInstance() {
if (reportUserQueue == null) {
reportUserQueue = new ReportUserQueue();
}
return reportUserQueue;
}
public void putUser(final ReportUserDto user) {
synchronized (lockObject) {
connectUserQueue.put(user.getUserId(), user);
}
}
public ReportUserDto getUser(final String userId) {
synchronized (lockObject) {
return connectUserQueue.get(userId);
}
}
public List<ReportUserDto> getUsers() {
synchronized (lockObject) {
return new ArrayList<>(connectUserQueue.values());
}
}
public boolean isExist(final String userId) {
synchronized (lockObject) {
return connectUserQueue.containsKey(userId);
}
}
public void removeUser(final String userId) {
synchronized (lockObject) {
ReportUserDto userDto = connectUserQueue.remove(userId);
if (userDto != null) {
ReportQueue queue = userDto.getReportQueue();
try {
queue.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
public int size() {
synchronized (lockObject) {
return connectUserQueue.size();
}
}
public boolean isEmpty() {
synchronized (lockObject) {
return connectUserQueue.isEmpty();
}
}
}

View File

@ -1,228 +0,0 @@
package com.munjaon.server.server.service;
import com.munjaon.server.queue.enums.QueueTypeWorker;
import com.munjaon.server.queue.pool.KeyWriteQueue;
import com.munjaon.server.server.config.ServerConfig;
import com.munjaon.server.server.dto.ConnectUserDto;
import com.munjaon.server.server.queue.CollectUserQueue;
import com.munjaon.server.server.task.CollectServerTask;
import com.munjaon.server.server.task.StatusCheckTask;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class CollectServer extends Service {
private final InetSocketAddress listenAddress;
private final CollectUserQueue collectUserQueue = CollectUserQueue.getInstance();
private Selector selector;
private final String serviceType;
private final String msgKeyPath;
private final int msgIdQueueSize;
private long USER_STATUS_LAST_CHECK_TIME = System.currentTimeMillis();
public CollectServer(String serviceName, String serviceType, int port, String msgKeyPath, int msgIdQueueSize) {
super(serviceName);
this.listenAddress = new InetSocketAddress(port);
this.serviceType = serviceType;
this.msgKeyPath = msgKeyPath;
this.msgIdQueueSize = msgIdQueueSize;
}
@Override
public void checkReady() {
QueueTypeWorker worker = QueueTypeWorker.find(this.serviceType);
if (worker != null && worker.getQueueSize() > 0) {
this.IS_READY_YN = true;
saveSystemLog("COLLECT_SERVER_SERVICE : QUEUE IS READY ... ...");
} else {
this.IS_READY_YN = false;
saveSystemLog("COLLECT_SERVER_SERVICE : QUEUE IS NOT READY ... ...");
}
}
@Override
public void initResources() {
try {
saveSystemLog("COLLECT_SERVER_SERVICE : RESOURCES INITIALIZING ... ...");
initCollectChannel();
saveSystemLog("COLLECT_SERVER_SERVICE : RESOURCES INITIALIZED ... ...");
} catch (IOException e) {
saveSystemLog(e);
throw new RuntimeException(e);
}
}
private void initCollectChannel() throws IOException {
saveSystemLog("COLLECT_SERVER_SERVICE INITIALIZING : SERVER PORT [" + listenAddress.getPort() + "]");
selector = Selector.open();
/* 채널 생성 */
ServerSocketChannel serverChannel = ServerSocketChannel.open();
/* non-Blocking 설정 */
serverChannel.configureBlocking(false);
/* 서버 ip, port 설정 */
serverChannel.socket().bind(listenAddress);
/* 채널에 accept 대기 설정 */
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
saveSystemLog("COLLECT_SERVER_SERVICE : SERVER SOCKET INITIALIZED ... ...");
}
private void closeCollectChannel() throws IOException {
if (selector != null) {
selector.close();
selector = null;
}
}
@Override
public void releaseResources() {
saveSystemLog("COLLECT_SERVER_SERVICE : SERVER RESOURCE RELEASING ... ...");
try {
closeCollectChannel();
} catch (IOException e) {
saveSystemLog(e);
throw new RuntimeException(e);
}
saveSystemLog("COLLECT_SERVER_SERVICE : SERVER RESOURCE RELEASED ... ...");
}
@Override
public void doService() {
saveSystemLog("COLLECT_SERVER_SERVICE : SERVER SERVICE STARTED ... ...");
while (isRun()) {
try {
execInterest();
checkInterest();
execUserStatus();
} catch (Exception e) {
saveSystemLog(e);
// throw new RuntimeException(e);
}
}
saveSystemLog("COLLECT_SERVER_SERVICE : SERVER SERVICE STOPPED ... ...");
}
private void execInterest() throws IOException {
if (selector.select(1000) == 0) {
return ;
}
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
/* 키 셋에서 제거. */
keys.remove();
if (key.isValid()) {
if (key.isAcceptable()) { // 접속일 경우..
saveLog("CONNECTION IS ACCEPTABLE ... ...");
accept(selector, key);
} else if (key.isReadable()) { // 수신일 경우..
ConnectUserDto connectUserDto = (ConnectUserDto) key.attachment();
if (connectUserDto == null || connectUserDto.isRunningMode()) {
continue;
}
/* 사용자별 Collect Thread 실행 */
new CollectServerTask(selector, key, getName(), this.serviceType, logger).start();
}
} else {
expireConnectUser(key);
}
}
}
private void checkInterest() {
for (SelectionKey key : selector.keys()) {
if (key.isValid()) {
ConnectUserDto connectUserDto = (ConnectUserDto) key.attachment();
if (connectUserDto == null) {
continue;
}
if (connectUserDto.isAlive() == 1) { // 로그인이 완료되지 않은 경우
expireConnectUser(key);
} else {
if (connectUserDto.isRunningMode()) {
continue;
}
connectUserDto.setRunningMode(true);
/* 사용자별 Collect Thread 실행 */
new CollectServerTask(selector, key, getName(), this.serviceType, logger).start();
}
} else {
expireConnectUser(key);
}
}
}
private void execUserStatus() throws IOException {
if (System.currentTimeMillis() - USER_STATUS_LAST_CHECK_TIME > ServerConfig.USER_STATUS_CYCLE_TIME) {
new StatusCheckTask(this.serviceType, logger).run();
USER_STATUS_LAST_CHECK_TIME = System.currentTimeMillis();
}
}
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();
InetAddress inetAddress = socket.getInetAddress();
SocketAddress socketAddress = socket.getRemoteSocketAddress();
saveLog("[CLIENT CONNECTION IP : " + inetAddress.getHostAddress() + "]");
saveLog("[CLIENT CONNECTION IP : " + socketAddress.toString() + "]");
// Socket 채널을 channel에 수신 등록한다
channel.register(selector, SelectionKey.OP_READ, ConnectUserDto.builder().serviceType(this.serviceType).msgKeyPath(this.msgKeyPath).msgIdQueueSize(this.msgIdQueueSize).lastTrafficTime(System.currentTimeMillis()).remoteIP(inetAddress.getHostAddress()).build());
} catch (Exception e) {
saveLog(e.toString());
throw new RuntimeException(e);
}
}
private void expireConnectUser(SelectionKey key) {
if (key == null || !key.isValid()) {
return;
}
try {
SocketChannel channel = (SocketChannel) key.channel();
ConnectUserDto userDto = (ConnectUserDto) key.attachment();
if (userDto != null && userDto.getUserId() != null) {
/* MSG ID 중복체크 큐 해제 */
KeyWriteQueue keyWriteQueue = userDto.getKeyWriteQueue();
if (keyWriteQueue != null) {
keyWriteQueue.close();
}
saveLog("[CLIENT USER IS DISCONNECT : " + userDto.toString() + "]");
collectUserQueue.removeUser(this.serviceType, userDto.getUserId());
key.attach(null);
/* 모니터링 로그 */
HealthCheckServer.saveMonitorLog("[COLLECT SERVER][SERVICE TYPE : " + this.serviceType + "][ID : " + userDto.getUserId() + "][EXPIRE CONNECT USER]");
}
// 소켓 채널 닫기
channel.close();
// 닫기
key.cancel();
} catch (IOException e) {
saveLog(e.toString());
e.printStackTrace();
}
}
@Override
public JSONObject monitorService() {
return null;
}
}

View File

@ -1,222 +0,0 @@
package com.munjaon.server.server.service;
import com.slack.api.Slack;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
public class HealthCheckServer extends Service {
private static final List<String> monitorLog = new ArrayList<>();
/** Lock Object */
private static final Object msgMonitor = new Object();
/** 설정 모니터링(10초단위로 체크한다.) */
private long CONFIG_CHECK_TIME = 0;
private String slackYn;
private String slackUrl;
private int serverCycle;
private long LAST_SERVER_CHECK_TIME = 0;
public HealthCheckServer(String serviceName) {
super(serviceName);
}
public static void saveMonitorLog(String log) {
if (log == null) {
return;
}
synchronized(msgMonitor){
monitorLog.add(log);
}
}
public static boolean isEmptyMonitorLog() {
synchronized(msgMonitor){
return monitorLog.isEmpty();
}
}
public static String popMonitorLog() {
synchronized(msgMonitor){
return monitorLog.remove(0);
}
}
@Override
public void checkReady() {
this.IS_READY_YN = true;
}
@Override
public void initResources() {
}
@Override
public void releaseResources() {
}
@Override
public void doService() {
saveSystemLog("HEALTH_CHECK_SERVER : SERVER SERVICE STARTED ... ...");
while (isRun()) {
try {
Thread.sleep(5000);
loadMonitorConfig();
serverMonitor();
sendMonitorLog();
} catch (Exception e) {
saveSystemLog(e.toString());
}
}
saveSystemLog("HEALTH_CHECK_SERVER : SERVER SERVICE STOPPED ... ...");
}
private void loadMonitorConfig() {
if (System.currentTimeMillis() - CONFIG_CHECK_TIME < 10000) {
return;
}
slackYn = getProp("SLACK_FLAG");
slackUrl = getProp("SLACK_URL");
serverCycle = Integer.parseInt(getProp("SERVER_CYCLE")) * 60000;
CONFIG_CHECK_TIME = System.currentTimeMillis();
}
@SuppressWarnings("unchecked")
public void sendMonitorLog() {
Slack slack = Slack.getInstance();
try {
while (true) {
if (isEmptyMonitorLog()) {
break;
}
String msg = popMonitorLog();
if (msg == null) {
break;
}
saveLog(msg);
if ("Y".equals(slackYn)) {
JSONObject payload = new JSONObject();
payload.put("text", msg);
slack.send(slackUrl, String.valueOf(payload));
}
}
Thread.sleep(3000);
} catch (IOException | InterruptedException e) {
saveSystemLog(e);
} finally {
if (slack != null) {
try {
slack.close();
} catch (Exception e) {
}
}
}
}
public void serverMonitor() {
if (System.currentTimeMillis() - LAST_SERVER_CHECK_TIME < serverCycle) {
return;
}
boolean isConnected = false;
int port;
/* 1. SMS */
port = Integer.parseInt(getProp("SMS_COLLECTOR", "SERVICE_PORT"));
isConnected = connectTest(port);
if (isConnected) {
saveMonitorLog("[SMS SERVER is Connectable]");
} else {
saveMonitorLog("[SMS SERVER is Shutdown]");
}
/* 2. LMS */
port = Integer.parseInt(getProp("LMS_COLLECTOR", "SERVICE_PORT"));
isConnected = connectTest(port);
if (isConnected) {
saveMonitorLog("[LMS SERVER is Connectable]");
} else {
saveMonitorLog("[LMS SERVER is Shutdown]");
}
/* 3. MMS */
port = Integer.parseInt(getProp("MMS_COLLECTOR", "SERVICE_PORT"));
isConnected = connectTest(port);
if (isConnected) {
saveMonitorLog("[MMS SERVER is Connectable]");
} else {
saveMonitorLog("[MMS SERVER is Shutdown]");
}
/* 4. 알림톡 */
port = Integer.parseInt(getProp("KAT_COLLECTOR", "SERVICE_PORT"));
isConnected = connectTest(port);
if (isConnected) {
saveMonitorLog("[KAT SERVER is Connectable]");
} else {
saveMonitorLog("[KAT SERVER is Shutdown]");
}
/* 5. 친구톡 */
port = Integer.parseInt(getProp("KFT_COLLECTOR", "SERVICE_PORT"));
isConnected = connectTest(port);
if (isConnected) {
saveMonitorLog("[KFT SERVER is Connectable]");
} else {
saveMonitorLog("[KFT SERVER is Shutdown]");
}
/* 6. 리포트 */
port = Integer.parseInt(getProp("REPORTER", "SERVICE_PORT"));
isConnected = connectTest(port);
if (isConnected) {
saveMonitorLog("[REPORT SERVER is Connectable]");
} else {
saveMonitorLog("[REPORT SERVER is Shutdown]");
}
LAST_SERVER_CHECK_TIME = System.currentTimeMillis();
}
private boolean connectTest(int port) {
boolean isConnected = false;
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open(new InetSocketAddress(port));
socketChannel.configureBlocking(false);
long connectStartTime = System.currentTimeMillis();
while (true) {
if (socketChannel.finishConnect()) {
isConnected = true;
break;
}
if (System.currentTimeMillis() - connectStartTime > 3000) {
break;
}
}
} catch (IOException e) {
saveLog("Connect Fail to [PORT : " + port + "]");
saveLog("ERROR [" + e.getMessage() + "]");
} finally {
if (socketChannel != null) {
try {
socketChannel.close();
} catch (IOException e) {
}
}
}
return isConnected;
}
@Override
public JSONObject monitorService() {
return null;
}
}

View File

@ -1,79 +0,0 @@
package com.munjaon.server.server.service;
import java.io.FileInputStream;
import java.util.Properties;
/**
* PropertyLoader
* @author JDS
*/
public class PropertyLoader extends Thread {
private static Properties props = load();
private static PropertyLoader loader;
public static String getProp(String key, String sub) {
return get(key+"."+sub);
}
public static String get(String key) {
return get(key, null);
}
public static String get(String key, String dflt) {
if( props == null ) return null;
String value = props.getProperty(key, dflt);
if( value == null ) {
value = dflt;
System.err.println("Not Defined : [" + key + "]");
}
else {
value = value.replaceAll("\\$WORK_HOME", System.getProperty("WORK_HOME"));
}
return value == null ? null : value.trim();
}
public synchronized static Properties load() {
String propFile = System.getProperty("PROPS");
try {
Properties properties = new Properties();
properties.load( new FileInputStream (propFile) );
props = properties;
} catch(Exception e) {
Log(e);
}
if( loader == null ) {
loader = new PropertyLoader();
loader.start();
}
return props;
}
private synchronized static void Log(Object oLog) {
if ( oLog instanceof Exception ) {
System.out.println( (new java.util.Date()) );
((Exception)oLog).printStackTrace();
} else {
System.out.println( (new java.util.Date()) + (String) oLog );
}
}
@Override
public void run() {
while( true ) {
try {
Thread.sleep(1000);
load();
} catch(Exception e) {
Log(e);
}
}
}
}

View File

@ -1,302 +0,0 @@
package com.munjaon.server.server.service;
import com.munjaon.server.queue.dto.BasicMessageDto;
import com.munjaon.server.queue.enums.QueueTypeWorker;
import com.munjaon.server.queue.pool.ReadQueue;
import com.munjaon.server.queue.pool.SerialQueuePool;
import com.munjaon.server.queue.pool.WriteQueue;
import com.munjaon.server.util.CommonUtil;
import com.munjaon.server.util.MessageUtil;
import com.munjaon.server.util.ServiceUtil;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class QueueServerService extends Service {
/** 큐모드 설정(WAIT : 파일에 쓰기모드만 / DB : DB에 적재) */
private String QUEUE_MODE = null;
/** 큐모드 설정 모니터링(10초단위로 체크한다.) */
private long QUEUE_MODE_CHECK_TIME = 0;
/** 큐 초기화 모니터링(1분단위로 체크한다.) 및 초기화 여부 */
private long QUEUE_INIT_CHECK_TIME = 0;
/** Commit 누적 카운트 */
private long SUM_COMMIT_COUNT = 0;
/** 큐모니터링 체크 사이클 */
private int QUEUE_MONITOR_CYCLE;
private long QUEUE_MONITOR_CHECK_TIME = 0;
SerialQueuePool queueInstance = SerialQueuePool.getInstance();
/* 쓰기큐 */
private WriteQueue writeQueue;
private ReadQueue readQueue;
private QueueTypeWorker worker;
public QueueServerService(String serviceName, WriteQueue writeQueue, ReadQueue readQueue) {
super(serviceName);
this.writeQueue = writeQueue;
this.readQueue = readQueue;
this.worker = QueueTypeWorker.find(writeQueue.getQueueInfo().getServiceType());
if (this.worker == null) {
throw new RuntimeException("No worker found for " + writeQueue.getQueueInfo().getServiceType());
}
}
/** 큐모드 설정(WAIT : 파일에 쓰기모드만 / DB : DB에 적재) */
public void checkMode(){
if((System.currentTimeMillis() - QUEUE_MODE_CHECK_TIME) > 10000){
QUEUE_MODE = PropertyLoader.get("COMMON.QUEUE_MODE");
// 예외체크
if(QUEUE_MODE == null) QUEUE_MODE = "DB";
QUEUE_MODE = QUEUE_MODE.toUpperCase();
// 읽은 시간 업데이트
QUEUE_MODE_CHECK_TIME = System.currentTimeMillis();
// 큐모니터링 체크 사이클
QUEUE_MONITOR_CYCLE = Integer.parseInt(getProp("HEALTH", "QUEUE_CYCLE")) * 60000;
}
}
@Override
public void checkReady() {
this.IS_READY_YN = queueInstance.isReady();
}
@Override
public void initResources() {
// 큐모드 정보를 읽어온다.
QUEUE_MODE = getProp("COMMON", "QUEUE_MODE");
if (QUEUE_MODE == null) {
QUEUE_MODE = "DB"; // 예외체크
}
try {
if (isRun()) {
/* 쓰기 큐 */
writeQueue.initQueue();
/* 읽기 큐 */
readQueue.initQueue();
/* 최초 큐정보 */
saveSystemLog("[INIT_LOAD_BEFORE][QUEUE_NAME : " + writeQueue.getQueueName() + "][WRITE_POSITION : " + writeQueue.getPushCounter() + "][READ_POSITION : " + readQueue.getPopCounter() + "]");
/* 큐 초기화 */
initQueue();
/* 큐 pool에 등록 */
worker.addQueue(writeQueue);
/* 메모리큐에서 다시 적재하기 */
loadMemoryQueue();
/* 최종 큐정보 */
saveSystemLog("[INIT_LOAD_AFTER][QUEUE_NAME : " + writeQueue.getQueueName() + "][WRITE_POSITION : " + writeQueue.getPushCounter() + "][READ_POSITION : " + readQueue.getPopCounter() + "]");
}
} catch (Exception e) {
saveSystemLog(e.toString());
throw new RuntimeException(e);
}
}
private void initQueue() throws Exception {
boolean isQueueInit = false; // 초기화 여부
String writeQueueCreateDate = writeQueue.getCreateDate();
String readQueueCreateDate = readQueue.getReadXMLDate();
String thisDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
if (readQueueCreateDate.equals(readQueueCreateDate)) {
if (thisDate.equals(writeQueueCreateDate)) {
isQueueInit = false;
} else {
String preDate = CommonUtil.getTargetDay(-24);
// 하루전이면 남은 큐데이터를 DB 처리한다.
if (writeQueueCreateDate.equals(preDate)) {
while (true) {
BasicMessageDto messageDto = readQueue.popMessageFromBuffer();
if (messageDto == null) {
break;
} else {
worker.memoryEnQueue(messageDto);
}
}
isQueueInit = true;
} else {
isQueueInit = true;
}
}
} else {
isQueueInit = true;
}
// 큐초기화 대상이면
if (isQueueInit) {
/* 큐 백업 */
writeQueue.backupQueue();
/* 커밋 카운트 초기화 */
SUM_COMMIT_COUNT = 0;
writeQueue.truncateQueue();
readQueue.initPopCounter();
}
}
private void loadMemoryQueue() throws Exception {
if (worker.getMemorySize() > 0) {
while (true) {
BasicMessageDto messageDto = worker.memoryDeQueue();
if (messageDto == null) {
break;
} else {
writeQueue.pushMessageToBuffer(messageDto);
}
}
}
}
private void checkQueue() throws Exception {
if((System.currentTimeMillis() - QUEUE_INIT_CHECK_TIME) < 60000){
return;
}
// 초기화 체크시간 업데이트
QUEUE_INIT_CHECK_TIME = System.currentTimeMillis();
// 초기화 여부
boolean isQueueInit = false;
// 오늘 날짜 체크 생성날짜 저장
String thisDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String writeQueueCreateDate = writeQueue.getCreateDate();
if (writeQueueCreateDate.equals(thisDate)) {
// 아무 처리도 하지 않는다.
} else {
/* 큐 pool에서 제거 */
if (worker != null) {
worker.removeQueue(writeQueue.getQueueInfo().getQueueName());
}
while(true){
BasicMessageDto messageDto = readQueue.popMessageFromBuffer();
if (messageDto == null) {
break;
} else {
worker.memoryEnQueue(messageDto);
}
}
isQueueInit = true;
}
if (isQueueInit) {
saveSystemLog("[QUEUE_INIT_START][QUEUE_NAME : " + writeQueue.getQueueName() + "][WRITE_POSITION : " + writeQueue.getPushCounter() + "][READ_POSITION : " + readQueue.getPopCounter() + "]");
/* 큐 백업 */
writeQueue.backupQueue();
/* 커밋 카운트 초기화 */
SUM_COMMIT_COUNT = 0;
// 큐를 초기화한다.
writeQueue.truncateQueue();
readQueue.initPopCounter();
/* 큐에 등록 */
worker.addQueue(writeQueue);
/* 메모리큐에서 다시 적재하기 */
loadMemoryQueue();
saveSystemLog("[QUEUE_INIT_END][QUEUE_NAME : " + writeQueue.getQueueName() + "][WRITE_POSITION : " + writeQueue.getPushCounter() + "][READ_POSITION : " + readQueue.getPopCounter() + "]");
}
}
private void messageService() throws Exception {
int DB_PROC_COUNT = 0;
List<BasicMessageDto> list = new ArrayList<>();
/* 큐 메시지 조회 */
try {
for (int loopCnt = 0; loopCnt < ServiceUtil.COMMIT_COUNT; loopCnt++) {
BasicMessageDto messageDto = readQueue.popMessageFromBuffer();
if (messageDto == null) {
break;
}
/* MSG ID 채번 */
String msgId = queueInstance.getSerialNumber();
msgId = MessageUtil.makeMessageKey(msgId);
String msgGroupId = msgId.replace("MSGID", "MGRP");
messageDto.setId(msgId);
messageDto.setMsgGroupID(msgGroupId);
list.add(messageDto);
DB_PROC_COUNT++;
SUM_COMMIT_COUNT++;
}
} catch (Exception e) {
saveLog(e);
}
// DB 처리한 카운트에 대한 처리
if (DB_PROC_COUNT > 0) {
boolean isError = false;
try {
worker.saveMessageForList(list);
Thread.sleep(10);
} catch (Exception e) {
saveLog(e);
isError = true;
}
/* DB 적재 실패시 처리 */
if (isError) {
readQueue.resetPopCounter(DB_PROC_COUNT);
}
} else {
Thread.sleep(100);
}
}
private void messageService_bak() throws Exception {
int DB_PROC_COUNT = 0;
for (int loopCnt = 0; loopCnt < ServiceUtil.COMMIT_COUNT; loopCnt++) {
BasicMessageDto messageDto = readQueue.popMessageFromBuffer();
if (messageDto == null) {
break;
}
worker.saveMessageToTable(messageDto);
DB_PROC_COUNT++;
SUM_COMMIT_COUNT++;
}
// DB 처리한 카운트에 대한 처리
if (DB_PROC_COUNT > 0) {
Thread.sleep(10);
} else {
Thread.sleep(1000);
}
}
@Override
public void releaseResources() {
try {
if (writeQueue != null) {
/* 쓰기 Pool에서 제거 */
worker.removeQueue(writeQueue.getQueueInfo().getQueueName());
/* 자원 해제 */
writeQueue.close();
saveSystemLog("[QUEUE_RELEASE][QUEUE_NAME : " + writeQueue.getQueueName() + "]");
}
if (readQueue != null) {
readQueue.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void doService() {
while (isRun()) {
try {
checkMode();
checkQueue();
messageService();
monitorService();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public JSONObject monitorService() {
if (System.currentTimeMillis() - QUEUE_MONITOR_CHECK_TIME < QUEUE_MONITOR_CYCLE) {
return null;
}
HealthCheckServer.saveMonitorLog("[QUEUE MONITOR][" + getName() + "] [WRITE POSITION : " + writeQueue.getPushCounter() + "][READ POSITION : " + readQueue.getPopCounter() + "]");
QUEUE_MONITOR_CHECK_TIME = System.currentTimeMillis();
return null;
}
}

View File

@ -1,77 +0,0 @@
package com.munjaon.server.server.service;
import com.munjaon.server.server.dto.ReportUserDto;
import com.munjaon.server.server.queue.ReportUserQueue;
import com.munjaon.server.server.task.ReportQueueTask;
import org.json.simple.JSONObject;
import java.util.List;
public class ReportQueueServer extends Service {
private final ReportUserQueue reportUserQueue = ReportUserQueue.getInstance();
private final int maxWriteCount;
private final int maxQueueCount;
public ReportQueueServer(String serviceName) {
super(serviceName);
this.maxWriteCount = Integer.parseInt(getProp("MAX_WRITE_COUNT").trim());
this.maxQueueCount = Integer.parseInt(getProp("MAX_QUEUE_COUNT").trim());
}
@Override
public void checkReady() {
this.IS_READY_YN = true;
}
@Override
public void initResources() {
saveSystemLog("REPORT_QUEUE_SERVICE : RESOURCES INITIALIZING ... ...");
saveSystemLog("REPORT_QUEUE_SERVICE : RESOURCES INITIALIZED ... ...");
}
@Override
public void releaseResources() {
saveSystemLog("REPORT_QUEUE_SERVICE : SERVER RESOURCE RELEASING ... ...");
saveSystemLog("REPORT_QUEUE_SERVICE : SERVER RESOURCE RELEASED ... ...");
}
@Override
public void doService() {
saveSystemLog("REPORT_QUEUE_SERVICE : SERVER SERVICE STARTED ... ...");
while (isRun()) {
try {
doQueueService();
Thread.sleep(10);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
saveSystemLog("REPORT_QUEUE_SERVICE : SERVER SERVICE STOPPED ... ...");
}
private void doQueueService() {
List<ReportUserDto> reportUserList = reportUserQueue.getUsers();
if (reportUserList == null || reportUserList.isEmpty()) {
return;
}
for (ReportUserDto reportUserDto : reportUserList) {
/* Report Queue 작업중인지 체크 */
if (reportUserDto.isQueueMode()) {
continue;
}
/* Report Queue 작업을 실행한다. */
reportUserDto.setQueueMode(true);
reportUserDto.setMaxWriteCount(this.maxWriteCount);
reportUserDto.setMaxQueueCount(this.maxQueueCount);
new ReportQueueTask(reportUserDto, logger).run();
}
}
@Override
public JSONObject monitorService() {
return null;
}
}

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