diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7a7781a5c..420a8b933 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,7 +9,7 @@ You need for `ezyfox` to your Github - must include unit test and coverage 100% - should have 6 files or less - don't change old code style if it has no problem - + ### 3. resolve review comment if we have any Please don't use force push after push resolved comments code diff --git a/assembly.xml b/assembly.xml index 1a84be639..69e0178eb 100644 --- a/assembly.xml +++ b/assembly.xml @@ -1,16 +1,16 @@ - bin - false - - dir - + bin + false + + dir + - - - true - lib - - + + + true + lib + + - \ No newline at end of file + diff --git a/ezyfox-server-boot/assembly.xml b/ezyfox-server-boot/assembly.xml index 1a84be639..69e0178eb 100644 --- a/ezyfox-server-boot/assembly.xml +++ b/ezyfox-server-boot/assembly.xml @@ -1,16 +1,16 @@ - bin - false - - dir - + bin + false + + dir + - - - true - lib - - + + + true + lib + + - \ No newline at end of file + diff --git a/ezyfox-server-boot/pom.xml b/ezyfox-server-boot/pom.xml index 86a16b1f4..2a0d2e2dc 100644 --- a/ezyfox-server-boot/pom.xml +++ b/ezyfox-server-boot/pom.xml @@ -1,22 +1,22 @@ - 4.0.0 - - com.tvd12 - ezyfox-server - 1.2.3 - - ezyfox-server-boot + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + com.tvd12 + ezyfox-server + 1.2.3 + + ezyfox-server-boot + + ezyfox-server-boot + https://youngmonkeys.org/project/ezyfox-sever/ + + + + com.tvd12 + ezyfox-server-core + ${project.version} + + - ezyfox-server-boot - https://youngmonkeys.org/project/ezyfox-sever/ - - - - com.tvd12 - ezyfox-server-core - ${project.version} - - - diff --git a/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyEmptyHttpBootstrap.java b/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyEmptyHttpBootstrap.java index aa4b82ae6..af9686187 100644 --- a/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyEmptyHttpBootstrap.java +++ b/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyEmptyHttpBootstrap.java @@ -6,13 +6,13 @@ public class EzyEmptyHttpBootstrap implements EzyHttpBootstrap { - @Setter - protected EzyServerContext serverContext; - - @Override - public void start() throws Exception {} + @Setter + protected EzyServerContext serverContext; - @Override - public void destroy() {} + @Override + public void start() throws Exception {} + + @Override + public void destroy() {} } diff --git a/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyHttpServerBootstrap.java b/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyHttpServerBootstrap.java index cecf4f7f7..af9575f91 100644 --- a/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyHttpServerBootstrap.java +++ b/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyHttpServerBootstrap.java @@ -6,29 +6,29 @@ public abstract class EzyHttpServerBootstrap extends EzyServerBootstrap { - private EzyHttpBootstrap httpBootstrap; - - protected void startHttpBootstrap() throws Exception { - EzyHttpSetting setting = getHttpSetting(); - if(!setting.isActive()) return; - logger.debug("starting http server bootstrap ...."); - httpBootstrap = newHttpBottstrap(); - httpBootstrap.start(); - logger.debug("http server bootstrap has started"); - } - - private EzyHttpBootstrap newHttpBottstrap() { - EzyEmptyHttpBootstrap bootstrap = new EzyEmptyHttpBootstrap(); - bootstrap.setServerContext(context); - return bootstrap; - } - - @Override - public void destroy() { - super.destroy(); - if(httpBootstrap != null) - processWithLogException(() -> httpBootstrap.destroy()); - this.httpBootstrap = null; - } - + private EzyHttpBootstrap httpBootstrap; + + protected void startHttpBootstrap() throws Exception { + EzyHttpSetting setting = getHttpSetting(); + if(!setting.isActive()) return; + logger.debug("starting http server bootstrap ...."); + httpBootstrap = newHttpBottstrap(); + httpBootstrap.start(); + logger.debug("http server bootstrap has started"); + } + + private EzyHttpBootstrap newHttpBottstrap() { + EzyEmptyHttpBootstrap bootstrap = new EzyEmptyHttpBootstrap(); + bootstrap.setServerContext(context); + return bootstrap; + } + + @Override + public void destroy() { + super.destroy(); + if(httpBootstrap != null) + processWithLogException(() -> httpBootstrap.destroy()); + this.httpBootstrap = null; + } + } diff --git a/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapBuilderTest.java b/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapBuilderTest.java index 97701eabe..d3d9320b8 100644 --- a/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapBuilderTest.java +++ b/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapBuilderTest.java @@ -8,17 +8,17 @@ public class EzyHttpServerBootstrapBuilderTest extends BaseTest { - @Test - public void test() { - new ExEzyHttpServerBootstrapBuilder(); - } - - public static class ExEzyHttpServerBootstrapBuilder extends EzyHttpServerBootstrapBuilder { + @Test + public void test() { + new ExEzyHttpServerBootstrapBuilder(); + } + + public static class ExEzyHttpServerBootstrapBuilder extends EzyHttpServerBootstrapBuilder { - @Override - protected EzyServerBootstrap newServerBootstrap() { - return null; - } - - } + @Override + protected EzyServerBootstrap newServerBootstrap() { + return null; + } + + } } diff --git a/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapTest.java b/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapTest.java index 1776be848..9d147b2cc 100644 --- a/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapTest.java +++ b/ezyfox-server-boot/src/test/java/com/tvd12/ezyfoxserver/testing/EzyHttpServerBootstrapTest.java @@ -14,37 +14,37 @@ public class EzyHttpServerBootstrapTest extends BaseTest { - @Test - public void test() { - EzyServerContext serverContext = mock(EzyServerContext.class); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - when(serverContext.getServer()).thenReturn(server); - EzyEmptyHttpBootstrap httpBootstrap = new EzyEmptyHttpBootstrap(); - httpBootstrap.setServerContext(serverContext); - ExEzyHttpServerBootstrap bootstrap = new ExEzyHttpServerBootstrap(); - bootstrap.setContext(serverContext); - MethodInvoker.create() - .object(bootstrap) - .method("startHttpBootstrap") - .invoke(); - - settings.getHttp().setActive(true); - MethodInvoker.create() - .object(bootstrap) - .method("startHttpBootstrap") - .invoke(); - bootstrap.destroy(); - bootstrap.destroy(); - } - - public static class ExEzyHttpServerBootstrap extends EzyHttpServerBootstrap { + @Test + public void test() { + EzyServerContext serverContext = mock(EzyServerContext.class); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + when(serverContext.getServer()).thenReturn(server); + EzyEmptyHttpBootstrap httpBootstrap = new EzyEmptyHttpBootstrap(); + httpBootstrap.setServerContext(serverContext); + ExEzyHttpServerBootstrap bootstrap = new ExEzyHttpServerBootstrap(); + bootstrap.setContext(serverContext); + MethodInvoker.create() + .object(bootstrap) + .method("startHttpBootstrap") + .invoke(); + + settings.getHttp().setActive(true); + MethodInvoker.create() + .object(bootstrap) + .method("startHttpBootstrap") + .invoke(); + bootstrap.destroy(); + bootstrap.destroy(); + } + + public static class ExEzyHttpServerBootstrap extends EzyHttpServerBootstrap { - @Override - protected void startOtherBootstraps(Runnable callback) throws Exception { - } - - } - + @Override + protected void startOtherBootstraps(Runnable callback) throws Exception { + } + + } + } diff --git a/ezyfox-server-boot/src/test/resources/AllTests.tng.xml b/ezyfox-server-boot/src/test/resources/AllTests.tng.xml index 3f571ed5b..cc4f77dda 100644 --- a/ezyfox-server-boot/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-boot/src/test/resources/AllTests.tng.xml @@ -1,9 +1,9 @@ - - - - - - \ No newline at end of file + + + + + + diff --git a/ezyfox-server-core/assembly.xml b/ezyfox-server-core/assembly.xml index 1a84be639..69e0178eb 100644 --- a/ezyfox-server-core/assembly.xml +++ b/ezyfox-server-core/assembly.xml @@ -1,16 +1,16 @@ - bin - false - - dir - + bin + false + + dir + - - - true - lib - - + + + true + lib + + - \ No newline at end of file + diff --git a/ezyfox-server-core/pom.xml b/ezyfox-server-core/pom.xml index 6ffd74010..749bfa911 100644 --- a/ezyfox-server-core/pom.xml +++ b/ezyfox-server-core/pom.xml @@ -1,48 +1,48 @@ - 4.0.0 - - com.tvd12 - ezyfox-server - 1.2.3 - - ezyfox-server-core - ezyfox-server-core - https://youngmonkeys.org/project/ezyfox-sever/ - - - - com.tvd12 - ezyfox-codec - ${project.version} - - - com.tvd12 - ezyfox-mapping - ${project.version} - - - com.tvd12 - ezyfox-tools - ${project.version} - test - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + 4.0.0 + + com.tvd12 + ezyfox-server + 1.2.3 + + ezyfox-server-core + ezyfox-server-core + https://youngmonkeys.org/project/ezyfox-sever/ - - - - src/main/resources - - ezy-settings-1.0.0.xsd - ezy-settings.xml - ezy-zone-settings-1.0.0.xsd - ezy-zone-settings.xml - - - - + + + com.tvd12 + ezyfox-codec + ${project.version} + + + com.tvd12 + ezyfox-mapping + ${project.version} + + + com.tvd12 + ezyfox-tools + ${project.version} + test + + + + + + + src/main/resources + + ezy-settings-1.0.0.xsd + ezy-settings.xml + ezy-zone-settings-1.0.0.xsd + ezy-zone-settings.xml + + + + diff --git a/ezyfox-server-core/settings/logback.xml b/ezyfox-server-core/settings/logback.xml index 9ac216fee..a1a5e2c5f 100644 --- a/ezyfox-server-core/settings/logback.xml +++ b/ezyfox-server-core/settings/logback.xml @@ -28,4 +28,4 @@ - \ No newline at end of file + diff --git a/ezyfox-server-core/settings/ssl-config.properties b/ezyfox-server-core/settings/ssl-config.properties index 914e17bfe..bb2fc449b 100644 --- a/ezyfox-server-core/settings/ssl-config.properties +++ b/ezyfox-server-core/settings/ssl-config.properties @@ -1,3 +1,3 @@ ssl.key_store="ssl/ssl-key-store.txt" ssl.keystore_password=ssl/ssl-keystore-password.txt -ssl.certificate_password=ssl/ssl-certificate-password.txt \ No newline at end of file +ssl.certificate_password=ssl/ssl-certificate-password.txt diff --git a/ezyfox-server-core/settings/ssl/ssl-certificate-password.txt b/ezyfox-server-core/settings/ssl/ssl-certificate-password.txt index 536aca34d..d97c5eada 100644 --- a/ezyfox-server-core/settings/ssl/ssl-certificate-password.txt +++ b/ezyfox-server-core/settings/ssl/ssl-certificate-password.txt @@ -1 +1 @@ -secret \ No newline at end of file +secret diff --git a/ezyfox-server-core/settings/ssl/ssl-key-store.txt b/ezyfox-server-core/settings/ssl/ssl-key-store.txt index 439ef0da4..27c1b25b2 100644 Binary files a/ezyfox-server-core/settings/ssl/ssl-key-store.txt and b/ezyfox-server-core/settings/ssl/ssl-key-store.txt differ diff --git a/ezyfox-server-core/settings/ssl/ssl-keystore-password.txt b/ezyfox-server-core/settings/ssl/ssl-keystore-password.txt index 536aca34d..d97c5eada 100644 --- a/ezyfox-server-core/settings/ssl/ssl-keystore-password.txt +++ b/ezyfox-server-core/settings/ssl/ssl-keystore-password.txt @@ -1 +1 @@ -secret \ No newline at end of file +secret diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyBootstrap.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyBootstrap.java index 5c98a0586..293913d04 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyBootstrap.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyBootstrap.java @@ -14,29 +14,29 @@ public class EzyBootstrap extends EzyLoggable implements EzyStartable, EzyDestroyable { - protected final EzyServerContext context; + protected final EzyServerContext context; - protected EzyBootstrap(Builder builder) { - this.context = builder.context; + protected EzyBootstrap(Builder builder) { + this.context = builder.context; } - - @Override - public void start() throws Exception { - notifyServerInitializing(); - startAllZones(); - startSessionManager(); - } - - protected void notifyServerInitializing() { - EzyServerInitializingEvent event = new EzySimpleServerInitializingEvent(); - context.handleEvent(EzyEventType.SERVER_INITIALIZING, event); - } - + + @Override + public void start() throws Exception { + notifyServerInitializing(); + startAllZones(); + startSessionManager(); + } + + protected void notifyServerInitializing() { + EzyServerInitializingEvent event = new EzySimpleServerInitializingEvent(); + context.handleEvent(EzyEventType.SERVER_INITIALIZING, event); + } + @Override - public void destroy() { - // do nothing - } - + public void destroy() { + // do nothing + } + private void startAllZones() { EzyZonesStarter.Builder builder = newZonesStarterBuilder() .serverContext(context); @@ -47,29 +47,29 @@ private void startAllZones() { protected EzyZonesStarter.Builder newZonesStarterBuilder() { return new EzyZonesStarter.Builder(); } - - @SuppressWarnings("rawtypes") + + @SuppressWarnings("rawtypes") protected void startSessionManager() throws Exception { - EzySessionManager sessionManager - = context.getServer().getSessionManager(); - ((EzyStartable)sessionManager).start(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - protected EzyServerContext context; - - public Builder context(EzyServerContext context) { - this.context = context; - return this; - } - - @Override - public EzyBootstrap build() { - return new EzyBootstrap(this); - } - } + EzySessionManager sessionManager + = context.getServer().getSessionManager(); + ((EzyStartable)sessionManager).start(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected EzyServerContext context; + + public Builder context(EzyServerContext context) { + this.context = context; + return this; + } + + @Override + public EzyBootstrap build() { + return new EzyBootstrap(this); + } + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyComponent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyComponent.java index 5caba1271..7b3e094fa 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyComponent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyComponent.java @@ -22,7 +22,7 @@ public class EzyComponent implements EzyExceptionHandlersFetcher, EzyDestroyable @Override public void destroy() { - if(eventControllers != null) + if(eventControllers != null) processWithLogException(() -> eventControllers.destroy()); this.eventControllers = null; } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java index d0b9b7290..75887fb29 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java @@ -4,6 +4,6 @@ public class EzyEnvironment extends EzyEntity { - public static final String SERVER_PORT = "ezyfox.server.port"; - public static final String DATE_FORMAT_PATTERN = "DATE_FORMAT_PATTERN"; + public static final String SERVER_PORT = "ezyfox.server.port"; + public static final String DATE_FORMAT_PATTERN = "DATE_FORMAT_PATTERN"; } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyLoader.java index 6647d040a..32ee464a8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyLoader.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyLoader.java @@ -42,16 +42,16 @@ public abstract class EzyLoader extends EzyLoggable { public EzyServer load() { EzySettings settings = readSettings(); - EzySimpleServer answer = new EzySimpleServer(); - answer.setConfig(config); - answer.setSettings(settings); - answer.setClassLoader(classLoader); - answer.setAppClassLoaders(newAppClassLoaders()); - answer.setStatistics(newStatistics()); - answer.setControllers(newControllers()); - answer.setSessionManager(newSessionManagers(settings)); - answer.setEventControllers(newEventControllers(settings.getEventControllers())); - return answer; + EzySimpleServer answer = new EzySimpleServer(); + answer.setConfig(config); + answer.setSettings(settings); + answer.setClassLoader(classLoader); + answer.setAppClassLoaders(newAppClassLoaders()); + answer.setStatistics(newStatistics()); + answer.setControllers(newControllers()); + answer.setSessionManager(newSessionManagers(settings)); + answer.setEventControllers(newEventControllers(settings.getEventControllers())); + return answer; } protected EzySettings readSettings() { @@ -129,7 +129,7 @@ protected String getEntriesPath() { } protected String getAppsPath() { - return getPath(getHomePath(), EzyFolderNamesSetting.APPS); + return getPath(getHomePath(), EzyFolderNamesSetting.APPS); } protected String getPath(String first, String... more) { @@ -146,8 +146,8 @@ public EzyLoader classLoader(ClassLoader classLoader) { } public EzyLoader config(EzyConfig config) { - this.config = config; - return this; + this.config = config; + return this; } public EzyLoader settingsDecorator(EzySettingsDecorator settingsDecorator) { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyRunner.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyRunner.java index 723601747..0483c2a70 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyRunner.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyRunner.java @@ -23,8 +23,8 @@ public void run(String[] args) throws Exception { } protected void validateArguments(String[] args) { - if(args.length == 0) - throw new IllegalStateException("must specific config.properties file"); + if(args.length == 0) + throw new IllegalStateException("must specific config.properties file"); } protected void startSystem(String[] args) throws Exception { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServerBootstrap.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServerBootstrap.java index b899202a0..3dff76a78 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServerBootstrap.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServerBootstrap.java @@ -25,88 +25,88 @@ public abstract class EzyServerBootstrap extends EzyLoggable implements EzyStartable, EzyDestroyable { - - @Setter - @Getter - protected EzyServerContext context; - @Setter - protected EzyBootstrap localBootstrap; - - @Override - public void start() throws Exception { - setupServer(); - startLocalBootstrap(); - startHttpBootstrap(); - startOtherBootstraps(() -> this.notifyServerReady()); - } - - protected void setupServer() { - } - - protected void startHttpBootstrap() throws Exception { - } - - protected abstract void startOtherBootstraps(Runnable callback) throws Exception; - - @Override - public void destroy() { - processWithLogException(() -> localBootstrap.destroy()); - } - - protected void startLocalBootstrap() throws Exception { - logger.debug("starting local bootstrap ...."); - localBootstrap.start(); - logger.debug("local bootstrap has started"); - } - - protected final void notifyServerReady() { - printBanner(); - notifyServerReady0(); - } - - protected final void printBanner() { - if(getServerConfig().isPrintBanner()) { - String bannerFile = getServerConfig().getBannerFile(); - logger.info("\n{}\n", new EzyBannerPrinter().getBannerText(bannerFile)); - } - } - - protected void notifyServerReady0() { - EzyEvent event = new EzySimpleServerReadyEvent(); + + @Setter + @Getter + protected EzyServerContext context; + @Setter + protected EzyBootstrap localBootstrap; + + @Override + public void start() throws Exception { + setupServer(); + startLocalBootstrap(); + startHttpBootstrap(); + startOtherBootstraps(() -> this.notifyServerReady()); + } + + protected void setupServer() { + } + + protected void startHttpBootstrap() throws Exception { + } + + protected abstract void startOtherBootstraps(Runnable callback) throws Exception; + + @Override + public void destroy() { + processWithLogException(() -> localBootstrap.destroy()); + } + + protected void startLocalBootstrap() throws Exception { + logger.debug("starting local bootstrap ...."); + localBootstrap.start(); + logger.debug("local bootstrap has started"); + } + + protected final void notifyServerReady() { + printBanner(); + notifyServerReady0(); + } + + protected final void printBanner() { + if(getServerConfig().isPrintBanner()) { + String bannerFile = getServerConfig().getBannerFile(); + logger.info("\n{}\n", new EzyBannerPrinter().getBannerText(bannerFile)); + } + } + + protected void notifyServerReady0() { + EzyEvent event = new EzySimpleServerReadyEvent(); context.handleEvent(EzyEventType.SERVER_READY, event); context.broadcast(EzyEventType.SERVER_READY, event, true); - } - - protected EzyServer getServer() { - return context.getServer(); - } - - protected EzyConfig getServerConfig() { - return getServer().getConfig(); - } - - protected EzySettings getServerSettings() { - return getServer().getSettings(); - } - - protected EzyHttpSetting getHttpSetting() { - return getServerSettings().getHttp(); - } - - protected EzySocketSetting getSocketSetting() { + } + + protected EzyServer getServer() { + return context.getServer(); + } + + protected EzyConfig getServerConfig() { + return getServer().getConfig(); + } + + protected EzySettings getServerSettings() { + return getServer().getSettings(); + } + + protected EzyHttpSetting getHttpSetting() { + return getServerSettings().getHttp(); + } + + protected EzySocketSetting getSocketSetting() { return getServerSettings().getSocket(); } - - protected EzyUdpSetting getUdpSetting() { + + protected EzyUdpSetting getUdpSetting() { return getServerSettings().getUdp(); } - - protected EzyWebSocketSetting getWebSocketSetting() { + + protected EzyWebSocketSetting getWebSocketSetting() { return getServerSettings().getWebsocket(); } - - protected EzyThreadPoolSizeSetting getThreadPoolSizeSetting() { - return getServerSettings().getThreadPoolSize(); - } - + + protected EzyThreadPoolSizeSetting getThreadPoolSizeSetting() { + return getServerSettings().getThreadPoolSize(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleServer.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleServer.java index ab7454c5b..da748a5a1 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleServer.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleServer.java @@ -31,35 +31,35 @@ public class EzySimpleServer extends EzyComponent implements EzyServer, EzyResponseApiAware, EzyStreamingApiAware, EzySessionManagerAware, EzyDestroyable { - protected EzyConfig config; - protected EzySettings settings; - protected ClassLoader classLoader; - protected EzyStatistics statistics; - protected EzyServerControllers controllers; + protected EzyConfig config; + protected EzySettings settings; + protected ClassLoader classLoader; + protected EzyStatistics statistics; + protected EzyServerControllers controllers; protected EzyResponseApi responseApi; - protected EzyStreamingApi streamingApi; - protected EzySessionManager sessionManager; + protected EzyStreamingApi streamingApi; + protected EzySessionManager sessionManager; protected Map appClassLoaders; - - @Override - public String getVersion() { - return "1.0.0"; - } - - @Override - public void destroy() { - super.destroy(); - ((EzyDestroyable)sessionManager).destroy(); - } - - @Override - public String toString() { - EzyJsonWriter writer = new EzySimpleJsonWriter(); - String json = writer.writeAsString(this); - return json; - } - - @Override + + @Override + public String getVersion() { + return "1.0.0"; + } + + @Override + public void destroy() { + super.destroy(); + ((EzyDestroyable)sessionManager).destroy(); + } + + @Override + public String toString() { + EzyJsonWriter writer = new EzySimpleJsonWriter(); + String json = writer.writeAsString(this); + return json; + } + + @Override public Map toMap() { Map map = new HashMap<>(); map.put("version", getVersion()); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java index d9c6a4e72..8d10a0142 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java @@ -2,19 +2,19 @@ public final class EzySystem { - private static final EzyEnvironment ENV = newEnviroment(); - - private EzySystem() { - } - - public static EzyEnvironment getEnv() { - return ENV; - } - - private static EzyEnvironment newEnviroment() { - EzyEnvironment env = new EzyEnvironment(); - env.setProperty(EzyEnvironment.DATE_FORMAT_PATTERN, "yyyy-MM-dd'T'HH:mm:ss:SSS"); - return env; - } - + private static final EzyEnvironment ENV = newEnviroment(); + + private EzySystem() { + } + + public static EzyEnvironment getEnv() { + return ENV; + } + + private static EzyEnvironment newEnviroment() { + EzyEnvironment env = new EzyEnvironment(); + env.setProperty(EzyEnvironment.DATE_FORMAT_PATTERN, "yyyy-MM-dd'T'HH:mm:ss:SSS"); + return env; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractResponseApi.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractResponseApi.java index 1473bc25f..2c962f730 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractResponseApi.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractResponseApi.java @@ -9,56 +9,56 @@ import com.tvd12.ezyfoxserver.socket.EzySimplePacket; public abstract class EzyAbstractResponseApi implements EzyResponseApi { - - @Override - public void response(EzyPackage pack, boolean immediate) throws Exception { - if(pack.isEncrypted()) { - secureResponse(pack, immediate); - } - else { - normalResponse(pack, immediate); - } - } - - protected final void normalResponse(EzyPackage pack, boolean immediate) throws Exception { - EzyConstant connectionType = getConnectionType(); - Collection recipients = pack.getRecipients(connectionType); - if(recipients.isEmpty()) return; - Object bytes = encodeData(pack.getData()); - if(immediate) { - for(EzySession session : recipients) - session.sendNow(createPacket(bytes, pack)); - } - else { - for(EzySession session : recipients) + + @Override + public void response(EzyPackage pack, boolean immediate) throws Exception { + if(pack.isEncrypted()) { + secureResponse(pack, immediate); + } + else { + normalResponse(pack, immediate); + } + } + + protected final void normalResponse(EzyPackage pack, boolean immediate) throws Exception { + EzyConstant connectionType = getConnectionType(); + Collection recipients = pack.getRecipients(connectionType); + if(recipients.isEmpty()) return; + Object bytes = encodeData(pack.getData()); + if(immediate) { + for(EzySession session : recipients) + session.sendNow(createPacket(bytes, pack)); + } + else { + for(EzySession session : recipients) session.send(createPacket(bytes, pack)); - } - } - - protected final void secureResponse(EzyPackage pack, boolean immediate) throws Exception { - EzyConstant connectionType = getConnectionType(); - Collection recipients = pack.getRecipients(connectionType); - if(recipients.isEmpty()) return; - byte[] messageContent = dataToMessageContent(pack.getData()); - if(immediate) { - for(EzySession session : recipients) { - byte[] bytes = encrypteMessageContent(messageContent, session.getSessionKey()); - session.sendNow(createPacket(bytes, pack)); - } - } - else { - for(EzySession session : recipients) { - byte[] bytes = encrypteMessageContent(messageContent, session.getSessionKey()); + } + } + + protected final void secureResponse(EzyPackage pack, boolean immediate) throws Exception { + EzyConstant connectionType = getConnectionType(); + Collection recipients = pack.getRecipients(connectionType); + if(recipients.isEmpty()) return; + byte[] messageContent = dataToMessageContent(pack.getData()); + if(immediate) { + for(EzySession session : recipients) { + byte[] bytes = encrypteMessageContent(messageContent, session.getSessionKey()); + session.sendNow(createPacket(bytes, pack)); + } + } + else { + for(EzySession session : recipients) { + byte[] bytes = encrypteMessageContent(messageContent, session.getSessionKey()); session.send(createPacket(bytes, pack)); - } - } - } - + } + } + } + protected EzySimplePacket createPacket(Object bytes, EzyPackage pack) { - EzySimplePacket packet = new EzySimplePacket(); - packet.setTransportType(pack.getTransportType()); - packet.setData(bytes); - return packet; + EzySimplePacket packet = new EzySimplePacket(); + packet.setTransportType(pack.getTransportType()); + packet.setData(bytes); + return packet; } protected abstract EzyConstant getConnectionType(); @@ -66,11 +66,11 @@ protected EzySimplePacket createPacket(Object bytes, EzyPackage pack) { protected abstract Object encodeData(EzyArray data) throws Exception; protected byte[] dataToMessageContent(EzyArray data) throws Exception { - throw new UnsupportedOperationException("unsupported"); + throw new UnsupportedOperationException("unsupported"); } protected byte[] encrypteMessageContent( - byte[] messageContent, byte[] encryptionKey) throws Exception { - throw new UnsupportedOperationException("unsupported"); + byte[] messageContent, byte[] encryptionKey) throws Exception { + throw new UnsupportedOperationException("unsupported"); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractStreamingApi.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractStreamingApi.java index a6cdd0734..54040005f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractStreamingApi.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyAbstractStreamingApi.java @@ -9,24 +9,24 @@ import com.tvd12.ezyfoxserver.socket.EzySimplePacket; public abstract class EzyAbstractStreamingApi implements EzyStreamingApi { - - @Override - public void response(EzyBytesPackage pack) throws Exception { - EzyConstant connectionType = getConnectionType(); - Collection recipients = pack.getRecipients(connectionType); - if(recipients.isEmpty()) return; - byte[] bytes = pack.getBytes(); - for(EzySession session : recipients) + + @Override + public void response(EzyBytesPackage pack) throws Exception { + EzyConstant connectionType = getConnectionType(); + Collection recipients = pack.getRecipients(connectionType); + if(recipients.isEmpty()) return; + byte[] bytes = pack.getBytes(); + for(EzySession session : recipients) session.send(createPacket(bytes, pack)); - } - + } + private EzyPacket createPacket(byte[] bytes, EzyBytesPackage pack) { - EzySimplePacket packet = new EzySimplePacket(); - packet.setTransportType(pack.getTransportType()); - packet.setData(bytes); - return packet; + EzySimplePacket packet = new EzySimplePacket(); + packet.setTransportType(pack.getTransportType()); + packet.setData(bytes); + return packet; } protected abstract EzyConstant getConnectionType(); - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyResponseApi.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyResponseApi.java index e8c995aa7..21eb38b3f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyResponseApi.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyResponseApi.java @@ -6,32 +6,32 @@ public class EzyProxyResponseApi implements EzyResponseApi { - private final EzyResponseApi websocketResponseApi; - private final EzyResponseApi socketResponseApi; - - public EzyProxyResponseApi(EzyCodecFactory codecFactory) { - Object socketEncoder = codecFactory.newEncoder(EzyConnectionType.SOCKET); - Object wsEncoder = codecFactory.newEncoder(EzyConnectionType.WEBSOCKET); - this.socketResponseApi = newSocketResponseApi(socketEncoder); - this.websocketResponseApi = newWebsocketResponseApi(wsEncoder); - } - - private EzyResponseApi newSocketResponseApi(Object socketEncoder) { + private final EzyResponseApi websocketResponseApi; + private final EzyResponseApi socketResponseApi; + + public EzyProxyResponseApi(EzyCodecFactory codecFactory) { + Object socketEncoder = codecFactory.newEncoder(EzyConnectionType.SOCKET); + Object wsEncoder = codecFactory.newEncoder(EzyConnectionType.WEBSOCKET); + this.socketResponseApi = newSocketResponseApi(socketEncoder); + this.websocketResponseApi = newWebsocketResponseApi(wsEncoder); + } + + private EzyResponseApi newSocketResponseApi(Object socketEncoder) { return socketEncoder != null ? new EzySocketResponseApi(socketEncoder) : EzyEmptyResponseApi.getInstance(); } - - private EzyResponseApi newWebsocketResponseApi(Object wsEncoder) { - return wsEncoder != null - ? new EzyWsResponseApi(wsEncoder) - : EzyEmptyResponseApi.getInstance(); - } - - @Override - public void response(EzyPackage pack, boolean immediate) throws Exception { - socketResponseApi.response(pack, immediate); - websocketResponseApi.response(pack, immediate); - } - + + private EzyResponseApi newWebsocketResponseApi(Object wsEncoder) { + return wsEncoder != null + ? new EzyWsResponseApi(wsEncoder) + : EzyEmptyResponseApi.getInstance(); + } + + @Override + public void response(EzyPackage pack, boolean immediate) throws Exception { + socketResponseApi.response(pack, immediate); + websocketResponseApi.response(pack, immediate); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyStreamingApi.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyStreamingApi.java index 9916d7d9b..14b7eaae2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyStreamingApi.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyProxyStreamingApi.java @@ -4,18 +4,18 @@ public class EzyProxyStreamingApi implements EzyStreamingApi { - private final EzyStreamingApi websocketResponseApi; - private final EzyStreamingApi socketResponseApi; - - public EzyProxyStreamingApi() { - this.socketResponseApi = new EzySocketStreamingApi(); - this.websocketResponseApi = new EzyWsStreamingApi(); - } - - @Override - public void response(EzyBytesPackage pack) throws Exception { - socketResponseApi.response(pack); - websocketResponseApi.response(pack); - } - + private final EzyStreamingApi websocketResponseApi; + private final EzyStreamingApi socketResponseApi; + + public EzyProxyStreamingApi() { + this.socketResponseApi = new EzySocketStreamingApi(); + this.websocketResponseApi = new EzyWsStreamingApi(); + } + + @Override + public void response(EzyBytesPackage pack) throws Exception { + socketResponseApi.response(pack); + websocketResponseApi.response(pack); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzySocketResponseApi.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzySocketResponseApi.java index 6934c3e60..1c9b3734b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzySocketResponseApi.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzySocketResponseApi.java @@ -9,31 +9,31 @@ public class EzySocketResponseApi extends EzyAbstractResponseApi { - protected final EzyMessageDataEncoder encoder; - - public EzySocketResponseApi(Object encoder) { - this.encoder = new EzySimpleMessageDataEncoder((EzyObjectToByteEncoder)encoder); - } - - @Override - protected Object encodeData(EzyArray data) throws Exception { - return encoder.encode(data); - } - - @Override - protected byte[] dataToMessageContent(EzyArray data) throws Exception { - return encoder.toMessageContent(data); - } - - @Override - protected byte[] encrypteMessageContent( - byte[] messageContent, byte[] encryptionKey) throws Exception { - return encoder.encryptMessageContent(messageContent, encryptionKey); - } - - @Override - protected EzyConstant getConnectionType() { - return EzyConnectionType.SOCKET; - } - + protected final EzyMessageDataEncoder encoder; + + public EzySocketResponseApi(Object encoder) { + this.encoder = new EzySimpleMessageDataEncoder((EzyObjectToByteEncoder)encoder); + } + + @Override + protected Object encodeData(EzyArray data) throws Exception { + return encoder.encode(data); + } + + @Override + protected byte[] dataToMessageContent(EzyArray data) throws Exception { + return encoder.toMessageContent(data); + } + + @Override + protected byte[] encrypteMessageContent( + byte[] messageContent, byte[] encryptionKey) throws Exception { + return encoder.encryptMessageContent(messageContent, encryptionKey); + } + + @Override + protected EzyConstant getConnectionType() { + return EzyConnectionType.SOCKET; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyWsResponseApi.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyWsResponseApi.java index cc02aaa0f..04e36df8f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyWsResponseApi.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/api/EzyWsResponseApi.java @@ -11,33 +11,33 @@ public class EzyWsResponseApi extends EzyAbstractResponseApi { - protected final EzyStringDataEncoder encoder; - - public EzyWsResponseApi(Object encoder) { - this.encoder = new EzySimpleStringDataEncoder((EzyObjectToStringEncoder)encoder); - } - - @Override - public void response(EzyPackage pack, boolean immediate) throws Exception { - normalResponse(pack, immediate); - } - - @Override - protected EzySimplePacket createPacket(Object bytes, EzyPackage pack) { - EzySimplePacket packet = super.createPacket(bytes, pack); - packet.setBinary(false); - return packet; - } - - @Override - protected Object encodeData(EzyArray data) throws Exception { - Object answer = encoder.encode(data, String.class); - return answer; - } - - @Override - protected EzyConstant getConnectionType() { - return EzyConnectionType.WEBSOCKET; - } - + protected final EzyStringDataEncoder encoder; + + public EzyWsResponseApi(Object encoder) { + this.encoder = new EzySimpleStringDataEncoder((EzyObjectToStringEncoder)encoder); + } + + @Override + public void response(EzyPackage pack, boolean immediate) throws Exception { + normalResponse(pack, immediate); + } + + @Override + protected EzySimplePacket createPacket(Object bytes, EzyPackage pack) { + EzySimplePacket packet = super.createPacket(bytes, pack); + packet.setBinary(false); + return packet; + } + + @Override + protected Object encodeData(EzyArray data) throws Exception { + Object answer = encoder.encode(data, String.class); + return answer; + } + + @Override + protected EzyConstant getConnectionType() { + return EzyConnectionType.WEBSOCKET; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyAbtractServerBootstrapBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyAbtractServerBootstrapBuilder.java index c315e2210..952d36777 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyAbtractServerBootstrapBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyAbtractServerBootstrapBuilder.java @@ -16,68 +16,68 @@ import com.tvd12.ezyfoxserver.ssl.EzySslContextInitializer; public abstract class EzyAbtractServerBootstrapBuilder - implements EzyServerBootstrapBuilder { - - protected EzyServer server; - protected EzyServerContext serverContext; - - @Override - public EzyAbtractServerBootstrapBuilder server(EzyServer server) { - this.server = server; - this.serverContext = newServerContext(server); - return this; - } - - @Override - public final EzyServerBootstrap build() { - prebuild(); + implements EzyServerBootstrapBuilder { + + protected EzyServer server; + protected EzyServerContext serverContext; + + @Override + public EzyAbtractServerBootstrapBuilder server(EzyServer server) { + this.server = server; + this.serverContext = newServerContext(server); + return this; + } + + @Override + public final EzyServerBootstrap build() { + prebuild(); return buildServerBootstrap(); - } - - protected void prebuild() { - } - - protected EzyServerBootstrap buildServerBootstrap() { - EzyServerBootstrap answer = newServerBootstrap(); + } + + protected void prebuild() { + } + + protected EzyServerBootstrap buildServerBootstrap() { + EzyServerBootstrap answer = newServerBootstrap(); answer.setContext(serverContext); answer.setLocalBootstrap(newLocalBoostrap()); return answer; - } - - protected EzyServerContext newServerContext(EzyServer server) { - return newServerContextBuilder() - .server(server) - .build(); - } - - protected SSLContext newSslContext(EzySslConfigSetting sslConfig) { - if(getWebsocketSetting().isSslActive()) - return newSslContextInitializer(sslConfig).init(); - return null; - } - - protected EzySslContextInitializer newSslContextInitializer(EzySslConfigSetting sslConfig) { + } + + protected EzyServerContext newServerContext(EzyServer server) { + return newServerContextBuilder() + .server(server) + .build(); + } + + protected SSLContext newSslContext(EzySslConfigSetting sslConfig) { + if(getWebsocketSetting().isSslActive()) + return newSslContextInitializer(sslConfig).init(); + return null; + } + + protected EzySslContextInitializer newSslContextInitializer(EzySslConfigSetting sslConfig) { return newSslContextInitializerBuilder() .sslConfig(sslConfig) .homeFolderPath(getConfig().getEzyfoxHome()) .build(); } - - protected EzySslContextInitializer.Builder newSslContextInitializerBuilder() { - return EzySslContextInitializer.builder(); - } - + + protected EzySslContextInitializer.Builder newSslContextInitializerBuilder() { + return EzySslContextInitializer.builder(); + } + protected EzyBootstrap newLocalBoostrap() { return EzyBootstrap.builder().context(serverContext).build(); } - - protected EzyServerContextBuilder newServerContextBuilder() { - return new EzySimpleServerContextBuilder<>(); - } - - protected abstract EzyServerBootstrap newServerBootstrap(); - - protected EzyConfig getConfig() { + + protected EzyServerContextBuilder newServerContextBuilder() { + return new EzySimpleServerContextBuilder<>(); + } + + protected abstract EzyServerBootstrap newServerBootstrap(); + + protected EzyConfig getConfig() { return server.getConfig(); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerBootstrapBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerBootstrapBuilder.java index d9aaa4c3d..180e4412d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerBootstrapBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerBootstrapBuilder.java @@ -6,12 +6,12 @@ public interface EzyServerBootstrapBuilder extends EzyBuilder { - /** - * set server - * - * @param server the server - * @return this pointer - */ - EzyServerBootstrapBuilder server(EzyServer server); - + /** + * set server + * + * @param server the server + * @return this pointer + */ + EzyServerBootstrapBuilder server(EzyServer server); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerContextBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerContextBuilder.java index 863aad992..1810dd155 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerContextBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerContextBuilder.java @@ -6,7 +6,7 @@ public interface EzyServerContextBuilder> extends EzyBuilder { - - B server(EzyServer server); - + + B server(EzyServer server); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecFactory.java index 050e80654..1b2ec04f6 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecFactory.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecFactory.java @@ -6,6 +6,6 @@ public interface EzyCodecFactory { Object newEncoder(EzyConstant type); - Object newDecoder(EzyConstant type); - + Object newDecoder(EzyConstant type); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleCodecFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleCodecFactory.java index 4bfd7a82e..d9f1c7ea6 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleCodecFactory.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleCodecFactory.java @@ -10,20 +10,20 @@ public class EzySimpleCodecFactory implements EzyCodecFactory { - protected final EzySocketSetting socketSetting; - protected final EzyWebSocketSetting websocketSetting; + protected final EzySocketSetting socketSetting; + protected final EzyWebSocketSetting websocketSetting; - protected final EzyCodecCreator socketCodecCreator; - protected final EzyCodecCreator websocketCodecCreator; - - public EzySimpleCodecFactory(Builder builder) { - this.socketSetting = builder.socketSetting; - this.websocketSetting = builder.websocketSetting; - this.socketCodecCreator = newSocketCodecCreator(); - this.websocketCodecCreator = newWebsocketCodecCreator(); - } - - @Override + protected final EzyCodecCreator socketCodecCreator; + protected final EzyCodecCreator websocketCodecCreator; + + public EzySimpleCodecFactory(Builder builder) { + this.socketSetting = builder.socketSetting; + this.websocketSetting = builder.websocketSetting; + this.socketCodecCreator = newSocketCodecCreator(); + this.websocketCodecCreator = newWebsocketCodecCreator(); + } + + @Override public Object newEncoder(EzyConstant type) { if(type == EzyConnectionType.SOCKET) { if(socketCodecCreator != null) @@ -35,62 +35,62 @@ public Object newEncoder(EzyConstant type) { } return null; } - - @Override - public Object newDecoder(EzyConstant type) { - if(type == EzyConnectionType.SOCKET) { - if(socketCodecCreator != null) { + + @Override + public Object newDecoder(EzyConstant type) { + if(type == EzyConnectionType.SOCKET) { + if(socketCodecCreator != null) { int maxRequestSize = socketSetting.getMaxRequestSize(); return socketCodecCreator.newDecoder(maxRequestSize); } - } - else { - if(websocketCodecCreator != null) { + } + else { + if(websocketCodecCreator != null) { int maxFrameSize = websocketSetting.getMaxFrameSize(); return websocketCodecCreator.newDecoder(maxFrameSize); } - } - return null; - } - - private EzyCodecCreator newSocketCodecCreator() { - if(socketSetting.isActive()) { - return EzyClasses.newInstance( - socketSetting.getCodecCreator(), - new Class[] {boolean.class}, - new Object[] {socketSetting.isSslActive()}); - } - return null; - } - - private EzyCodecCreator newWebsocketCodecCreator() { - if(websocketSetting.isActive()) - return EzyClasses.newInstance(websocketSetting.getCodecCreator()); - return null; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - protected EzySocketSetting socketSetting; - protected EzyWebSocketSetting websocketSetting; - - public Builder socketSetting(EzySocketSetting settings) { - this.socketSetting = settings; - return this; - } - - public Builder websocketSetting(EzyWebSocketSetting settings) { - this.websocketSetting = settings; - return this; - } - - @Override - public EzyCodecFactory build() { - return new EzySimpleCodecFactory(this); - } - } - + } + return null; + } + + private EzyCodecCreator newSocketCodecCreator() { + if(socketSetting.isActive()) { + return EzyClasses.newInstance( + socketSetting.getCodecCreator(), + new Class[] {boolean.class}, + new Object[] {socketSetting.isSslActive()}); + } + return null; + } + + private EzyCodecCreator newWebsocketCodecCreator() { + if(websocketSetting.isActive()) + return EzyClasses.newInstance(websocketSetting.getCodecCreator()); + return null; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected EzySocketSetting socketSetting; + protected EzyWebSocketSetting websocketSetting; + + public Builder socketSetting(EzySocketSetting settings) { + this.socketSetting = settings; + return this; + } + + public Builder websocketSetting(EzyWebSocketSetting settings) { + this.websocketSetting = settings; + return this; + } + + @Override + public EzyCodecFactory build() { + return new EzySimpleCodecFactory(this); + } + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractResponse.java index eb02d4c2b..fbca694fc 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractResponse.java @@ -36,14 +36,14 @@ public EzyAbstractResponse(C context) { @Override public EzyResponse encrypted() { - this.encrypted = true; - return this; + this.encrypted = true; + return this; } @Override public EzyResponse encrypted(boolean value) { - this.encrypted = value; - return this; + this.encrypted = value; + return this; } @Override diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractSetup.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractSetup.java index 15797eee0..86b8a09fe 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractSetup.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAbstractSetup.java @@ -9,11 +9,11 @@ @AllArgsConstructor public abstract class EzyAbstractSetup extends EzyAbstractCommand { - private final EzyServerChild serverChild; - - @SuppressWarnings("rawtypes") - public void addEventController0(EzyConstant eventType, EzyEventController controller) { - serverChild.addEventController(eventType, controller); - } - + private final EzyServerChild serverChild; + + @SuppressWarnings("rawtypes") + public void addEventController0(EzyConstant eventType, EzyEventController controller) { + serverChild.addEventController(eventType, controller); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyBroadcastEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyBroadcastEvent.java index ae0f23d50..5cd4e467a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyBroadcastEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyBroadcastEvent.java @@ -5,6 +5,6 @@ public interface EzyBroadcastEvent { - void fire(EzyConstant type, EzyEvent event, boolean catchException); - + void fire(EzyConstant type, EzyEvent event, boolean catchException); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCloseSession.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCloseSession.java index ed8441f34..96e3593e8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCloseSession.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCloseSession.java @@ -6,5 +6,5 @@ public interface EzyCloseSession { void close(EzySession session, EzyConstant reason); - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCommand.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCommand.java index 31a2ae54a..b2c742409 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCommand.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyCommand.java @@ -2,6 +2,6 @@ public interface EzyCommand { - R execute(); - + R execute(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyResponse.java index 958168860..95cccf231 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyResponse.java @@ -7,10 +7,10 @@ import com.tvd12.ezyfoxserver.entity.EzyUser; public interface EzyResponse extends EzyVoidCommand { - - EzyResponse encrypted(); - - EzyResponse encrypted(boolean value); + + EzyResponse encrypted(); + + EzyResponse encrypted(boolean value); EzyResponse command(String command); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySetup.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySetup.java index 43157d58f..b9428c68f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySetup.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySetup.java @@ -5,7 +5,7 @@ public interface EzySetup { - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes") EzySetup addEventController(EzyConstant eventType, EzyEventController controller); - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyVoidCommand.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyVoidCommand.java index 557d25403..f3eceef69 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyVoidCommand.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyVoidCommand.java @@ -2,6 +2,6 @@ public interface EzyVoidCommand { - void execute(); - + void execute(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastAppsEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastAppsEventImpl.java index d4369bbff..9b1e69879 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastAppsEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastAppsEventImpl.java @@ -15,53 +15,53 @@ public class EzyBroadcastAppsEventImpl extends EzyAbstractCommand implements EzyBroadcastAppsEvent { private final EzyZoneContext context; - - public EzyBroadcastAppsEventImpl(EzyZoneContext context) { - this.context = context; - } - - @Override - public void fire(EzyConstant type, EzyEvent event, boolean catchException) { - logger.debug("zone {} broadcast to apps event: {}", getZoneName(), type); - for(EzyAppContext appContext : context.getAppContexts()) + + public EzyBroadcastAppsEventImpl(EzyZoneContext context) { + this.context = context; + } + + @Override + public void fire(EzyConstant type, EzyEvent event, boolean catchException) { + logger.debug("zone {} broadcast to apps event: {}", getZoneName(), type); + for(EzyAppContext appContext : context.getAppContexts()) fireAppEvent(appContext, type, event, catchException); - } - - @Override - public void fire(EzyConstant type, EzyEvent event, String username, boolean catchException) { - fire(type, event, appCtx -> containsUser(appCtx, username), catchException); - } - - @Override - public void fire(EzyConstant type, EzyEvent event, EzyUser user, boolean catchException) { - fire(type, event, appCtx -> containsUser(appCtx, user), catchException); - } - - @Override - public void fire(EzyConstant type, EzyEvent event, Predicate filter, boolean catchException) { - logger.debug("zone {} broadcast to apps event: {}", getZoneName(), type); - for(EzyAppContext appContext : context.getAppContexts()) { + } + + @Override + public void fire(EzyConstant type, EzyEvent event, String username, boolean catchException) { + fire(type, event, appCtx -> containsUser(appCtx, username), catchException); + } + + @Override + public void fire(EzyConstant type, EzyEvent event, EzyUser user, boolean catchException) { + fire(type, event, appCtx -> containsUser(appCtx, user), catchException); + } + + @Override + public void fire(EzyConstant type, EzyEvent event, Predicate filter, boolean catchException) { + logger.debug("zone {} broadcast to apps event: {}", getZoneName(), type); + for(EzyAppContext appContext : context.getAppContexts()) { if(filter.test(appContext)) fireAppEvent(appContext, type, event, catchException); } - } - - protected void fireAppEvent(EzyAppContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { - if(catchException) { - try { - ctx.handleEvent(type, event); - } - catch(Exception e) { - ctx.handleException(Thread.currentThread(), e); - } - } - else { - ctx.handleEvent(type, event); - } - } - - protected String getZoneName() { - return context.getZone().getSetting().getName(); - } - + } + + protected void fireAppEvent(EzyAppContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { + if(catchException) { + try { + ctx.handleEvent(type, event); + } + catch(Exception e) { + ctx.handleException(Thread.currentThread(), e); + } + } + else { + ctx.handleEvent(type, event); + } + } + + protected String getZoneName() { + return context.getZone().getSetting().getName(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastEventImpl.java index 8eba86f93..057673f36 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastEventImpl.java @@ -40,4 +40,4 @@ protected void fireZoneEvent(EzyZoneContext ctx, EzyConstant type, EzyEvent even } } -} \ No newline at end of file +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastPluginsEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastPluginsEventImpl.java index ee42713c6..1b5599bd6 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastPluginsEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyBroadcastPluginsEventImpl.java @@ -15,44 +15,44 @@ public class EzyBroadcastPluginsEventImpl extends EzyAbstractCommand implements EzyBroadcastPluginsEvent { - private final EzyZoneContext context; - private final EzyMapSet pluginContextss; - - public EzyBroadcastPluginsEventImpl(EzyZoneContext context) { - this.context = context; - this.pluginContextss = getPluginContextss(); - - } - - @Override - public void fire(EzyConstant type, EzyEvent event, boolean catchException) { - logger.debug("zone: {} broadcast to plugins event: {}", getZoneName(), type); - Set pluginContexts = pluginContextss.get(type); - if(pluginContexts != null) { - for(EzyPluginContext pluginContext : pluginContexts) - firePluginEvent(pluginContext, type, event, catchException); - } - } - - protected void firePluginEvent(EzyPluginContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { - if(catchException) { - try { - ctx.handleEvent(type, event); - } - catch(Exception e) { - ctx.handleException(Thread.currentThread(), e); - } - } - else { - ctx.handleEvent(type, event); - } - } - - protected String getZoneName() { - return context.getZone().getSetting().getName(); - } - - private EzyMapSet getPluginContextss() { + private final EzyZoneContext context; + private final EzyMapSet pluginContextss; + + public EzyBroadcastPluginsEventImpl(EzyZoneContext context) { + this.context = context; + this.pluginContextss = getPluginContextss(); + + } + + @Override + public void fire(EzyConstant type, EzyEvent event, boolean catchException) { + logger.debug("zone: {} broadcast to plugins event: {}", getZoneName(), type); + Set pluginContexts = pluginContextss.get(type); + if(pluginContexts != null) { + for(EzyPluginContext pluginContext : pluginContexts) + firePluginEvent(pluginContext, type, event, catchException); + } + } + + protected void firePluginEvent(EzyPluginContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { + if(catchException) { + try { + ctx.handleEvent(type, event); + } + catch(Exception e) { + ctx.handleException(Thread.currentThread(), e); + } + } + else { + ctx.handleEvent(type, event); + } + } + + protected String getZoneName() { + return context.getZone().getSetting().getName(); + } + + private EzyMapSet getPluginContextss() { Collection pluginContexts = context.getPluginContexts(); EzyMapSet pluginContextss = new EzyHashMapSet<>(); for(EzyPluginContext pluginContext : pluginContexts) { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyCloseSessionImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyCloseSessionImpl.java index 2945edfb5..030dc1693 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyCloseSessionImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyCloseSessionImpl.java @@ -11,43 +11,43 @@ import com.tvd12.ezyfoxserver.response.EzyResponse; public class EzyCloseSessionImpl - extends EzyMessageController - implements EzyCloseSession { - - private final EzyServerContext context; - - public EzyCloseSessionImpl(EzyServerContext ctx) { - this.context = ctx; - } - - @Override - public void close(EzySession session, EzyConstant reason) { - sendToClients(session, reason); + extends EzyMessageController + implements EzyCloseSession { + + private final EzyServerContext context; + + public EzyCloseSessionImpl(EzyServerContext ctx) { + this.context = ctx; + } + + @Override + public void close(EzySession session, EzyConstant reason) { + sendToClients(session, reason); disconnectSession(session, reason); - } - - protected void sendToClients(EzySession session, EzyConstant reason) { - if(shouldSendToClient(reason)) - sendToClients0(session, reason); - } - - protected boolean shouldSendToClient(EzyConstant reason) { - return reason != EzyDisconnectReason.UNKNOWN; - } - - protected void disconnectSession(EzySession session, EzyConstant reason) { + } + + protected void sendToClients(EzySession session, EzyConstant reason) { + if(shouldSendToClient(reason)) + sendToClients0(session, reason); + } + + protected boolean shouldSendToClient(EzyConstant reason) { + return reason != EzyDisconnectReason.UNKNOWN; + } + + protected void disconnectSession(EzySession session, EzyConstant reason) { logger.info("close session: {}, reason: {}", session.getClientAddress(), reason); session.close(); } - - protected void sendToClients0(EzySession session, EzyConstant reason) { - EzyResponse response = newResponse(reason); - context.sendNow(response, session); - } - - protected EzyResponse newResponse(EzyConstant reason) { - EzyDisconnectParams params = new EzyDisconnectParams(); - params.setReason(reason); + + protected void sendToClients0(EzySession session, EzyConstant reason) { + EzyResponse response = newResponse(reason); + context.sendNow(response, session); + } + + protected EzyResponse newResponse(EzyConstant reason) { + EzyDisconnectParams params = new EzyDisconnectParams(); + params.setReason(reason); return new EzyDisconnectResponse(params); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendResponseImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendResponseImpl.java index 35a245896..31b0a1efc 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendResponseImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendResponseImpl.java @@ -79,8 +79,8 @@ public void execute( } protected EzySimplePackage newPackage( - EzyArray data, - boolean encrypted, EzyTransportType transportType) { + EzyArray data, + boolean encrypted, EzyTransportType transportType) { EzySimplePackage pack = new EzySimplePackage(); pack.setData(data); pack.setEncrypted(encrypted); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyZoneBroadcastEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyZoneBroadcastEventImpl.java index 0a02c2d79..7d141c4cc 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyZoneBroadcastEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyZoneBroadcastEventImpl.java @@ -13,55 +13,55 @@ @AllArgsConstructor public class EzyZoneBroadcastEventImpl extends EzyAbstractCommand implements EzyBroadcastEvent { - private final EzyZoneContext context; - - @Override - public void fire(EzyConstant type, EzyEvent event, boolean catchException) { - logger.debug("zone: {} fire event: {}", getZoneName(), type); - firePluginsEvent(type, event, catchException); - fireAppsEvent(type, event, catchException); - } - - protected void fireAppsEvent(EzyConstant type, EzyEvent event, boolean catchException) { - for(EzyAppContext appContext : context.getAppContexts()) - fireAppEvent(appContext, type, event, catchException); - } - - protected void fireAppEvent(EzyAppContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { - if(catchException) { - try { - ctx.handleEvent(type, event); - } - catch(Exception e) { - ctx.handleException(Thread.currentThread(), e); - } - } - else { - ctx.handleEvent(type, event); - } - } - - protected void firePluginsEvent(EzyConstant type, EzyEvent event, boolean catchException) { - for(EzyPluginContext pluginContext : context.getPluginContexts()) - firePluginEvent(pluginContext, type, event, catchException); - } - - protected void firePluginEvent(EzyPluginContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { - if(catchException) { - try { - ctx.handleEvent(type, event); - } - catch(Exception e) { - ctx.handleException(Thread.currentThread(), e); - } - } - else { - ctx.handleEvent(type, event); - } - } - - protected String getZoneName() { - return context.getZone().getSetting().getName(); - } - + private final EzyZoneContext context; + + @Override + public void fire(EzyConstant type, EzyEvent event, boolean catchException) { + logger.debug("zone: {} fire event: {}", getZoneName(), type); + firePluginsEvent(type, event, catchException); + fireAppsEvent(type, event, catchException); + } + + protected void fireAppsEvent(EzyConstant type, EzyEvent event, boolean catchException) { + for(EzyAppContext appContext : context.getAppContexts()) + fireAppEvent(appContext, type, event, catchException); + } + + protected void fireAppEvent(EzyAppContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { + if(catchException) { + try { + ctx.handleEvent(type, event); + } + catch(Exception e) { + ctx.handleException(Thread.currentThread(), e); + } + } + else { + ctx.handleEvent(type, event); + } + } + + protected void firePluginsEvent(EzyConstant type, EzyEvent event, boolean catchException) { + for(EzyPluginContext pluginContext : context.getPluginContexts()) + firePluginEvent(pluginContext, type, event, catchException); + } + + protected void firePluginEvent(EzyPluginContext ctx, EzyConstant type, EzyEvent event, boolean catchException) { + if(catchException) { + try { + ctx.handleEvent(type, event); + } + catch(Exception e) { + ctx.handleException(Thread.currentThread(), e); + } + } + else { + ctx.handleEvent(type, event); + } + } + + protected String getZoneName() { + return context.getZone().getSetting().getName(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfigBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfigBuilder.java index f14ed76fd..b8cd0c41b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfigBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfigBuilder.java @@ -10,15 +10,15 @@ public class EzyConfigBuilder implements EzyBuilder { protected String bannerFile; protected String loggerConfigFile; protected boolean enableAppClassLoader; - - public EzyConfigBuilder() { - this.printSettings = true; - this.printBanner = true; - this.enableAppClassLoader = false; - this.bannerFile = "ezyfox-banner.txt"; - } - - public EzyConfigBuilder ezyfoxHome(String ezyfoxHome) { + + public EzyConfigBuilder() { + this.printSettings = true; + this.printBanner = true; + this.enableAppClassLoader = false; + this.bannerFile = "ezyfox-banner.txt"; + } + + public EzyConfigBuilder ezyfoxHome(String ezyfoxHome) { this.ezyfoxHome = ezyfoxHome; return this; } @@ -59,5 +59,5 @@ public EzyConfig build() { p.setEnableAppClassLoader(enableAppClassLoader); return p; } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfig.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfig.java index 8e42b3781..b60c9486d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfig.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfig.java @@ -14,50 +14,50 @@ @ToString public class EzySimpleConfig implements EzyConfig { - @Property("ezyfox.home") - protected String ezyfoxHome; - - @Property("settings.print") - protected boolean printSettings; - - @Property("banner.print") - protected boolean printBanner; - - @Property("banner.file") + @Property("ezyfox.home") + protected String ezyfoxHome; + + @Property("settings.print") + protected boolean printSettings; + + @Property("banner.print") + protected boolean printBanner; + + @Property("banner.file") protected String bannerFile; - - @Property("logger.config.file") - protected String loggerConfigFile; - - @Property("app.classloader.enable") - protected boolean enableAppClassLoader; - - public EzySimpleConfig() { - this.printSettings = true; - this.printBanner = true; - this.enableAppClassLoader = true; - this.bannerFile = "ezyfox-banner.txt"; - } - - public static EzySimpleConfig defaultConfig() { - EzySimpleConfig config = new EzySimpleConfig(); - config.setEnableAppClassLoader(false); - return config; - } - - public String getEzyfoxHome() { - if(ezyfoxHome == null) - return ""; - return ezyfoxHome; - } - - @Override - public Map toMap() { - Map map = new HashMap<>(); - map.put("ezyfoxHome", getEzyfoxHome()); - map.put("loggerConfigFile", loggerConfigFile != null ? loggerConfigFile : "default"); - map.put("enableAppClassLoader", enableAppClassLoader); - return map; - } - + + @Property("logger.config.file") + protected String loggerConfigFile; + + @Property("app.classloader.enable") + protected boolean enableAppClassLoader; + + public EzySimpleConfig() { + this.printSettings = true; + this.printBanner = true; + this.enableAppClassLoader = true; + this.bannerFile = "ezyfox-banner.txt"; + } + + public static EzySimpleConfig defaultConfig() { + EzySimpleConfig config = new EzySimpleConfig(); + config.setEnableAppClassLoader(false); + return config; + } + + public String getEzyfoxHome() { + if(ezyfoxHome == null) + return ""; + return ezyfoxHome; + } + + @Override + public Map toMap() { + Map map = new HashMap<>(); + map.put("ezyfoxHome", getEzyfoxHome()); + map.put("loggerConfigFile", loggerConfigFile != null ? loggerConfigFile : "default"); + map.put("enableAppClassLoader", enableAppClassLoader); + return map; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyCommand.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyCommand.java index f8ef440e9..14869986f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyCommand.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyCommand.java @@ -11,58 +11,58 @@ public enum EzyCommand implements EzyConstant { - ERROR(10, 10), - HANDSHAKE(11, 0), - PING(12, 10), + ERROR(10, 10), + HANDSHAKE(11, 0), + PING(12, 10), PONG(13, 10), DISCONNECT(14, 10), - LOGIN(20, 1), - LOGIN_ERROR(21, 10), - APP_ACCESS(30, 2), - APP_REQUEST(31, 10), - APP_EXIT(33, 10), - APP_ACCESS_ERROR(34, 10), - APP_REQUEST_ERROR(35, 10), - PLUGIN_INFO(40, 10), + LOGIN(20, 1), + LOGIN_ERROR(21, 10), + APP_ACCESS(30, 2), + APP_REQUEST(31, 10), + APP_EXIT(33, 10), + APP_ACCESS_ERROR(34, 10), + APP_REQUEST_ERROR(35, 10), + PLUGIN_INFO(40, 10), PLUGIN_REQUEST(41, 10), UDP_HANDSHAKE(50, 10); - - @Getter - private final int id; - @Getter - private final int priority; - - private static final Set SYSTEM_COMMANDS = systemCommands(); - private static final Map COMMANDS_BY_ID = commandsById(); - - private EzyCommand(int id, int priority) { - this.id = id; - this.priority = priority; - } - - public boolean isSystemCommand() { - return SYSTEM_COMMANDS.contains(this); - } - - @Override - public String getName() { - return toString(); - } - - public static EzyCommand valueOf(int id) { - EzyCommand cmd = COMMANDS_BY_ID.get(id); - return cmd; - } - - private static final Set systemCommands() { - return Sets.newHashSet(HANDSHAKE, LOGIN, APP_ACCESS, APP_EXIT, PLUGIN_INFO, DISCONNECT); - } - - private static final Map commandsById() { - Map map = new ConcurrentHashMap<>(); - for(EzyCommand cmd : values()) - map.put(cmd.getId(), cmd); - return map; - } - + + @Getter + private final int id; + @Getter + private final int priority; + + private static final Set SYSTEM_COMMANDS = systemCommands(); + private static final Map COMMANDS_BY_ID = commandsById(); + + private EzyCommand(int id, int priority) { + this.id = id; + this.priority = priority; + } + + public boolean isSystemCommand() { + return SYSTEM_COMMANDS.contains(this); + } + + @Override + public String getName() { + return toString(); + } + + public static EzyCommand valueOf(int id) { + EzyCommand cmd = COMMANDS_BY_ID.get(id); + return cmd; + } + + private static final Set systemCommands() { + return Sets.newHashSet(HANDSHAKE, LOGIN, APP_ACCESS, APP_EXIT, PLUGIN_INFO, DISCONNECT); + } + + private static final Map commandsById() { + Map map = new ConcurrentHashMap<>(); + for(EzyCommand cmd : values()) + map.put(cmd.getId(), cmd); + return map; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConnectionType.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConnectionType.java index a5ddbd4f6..56d4d830c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConnectionType.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConnectionType.java @@ -6,19 +6,19 @@ public enum EzyConnectionType implements EzyConstant { - SOCKET(1), - WEBSOCKET(2); - - @Getter - private final int id; - - private EzyConnectionType(int id) { - this.id = id; - } - - @Override - public String getName() { - return toString(); - } - + SOCKET(1), + WEBSOCKET(2); + + @Getter + private final int id; + + private EzyConnectionType(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyDisconnectReason.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyDisconnectReason.java index f6eedf0b7..29e019be9 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyDisconnectReason.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyDisconnectReason.java @@ -9,40 +9,40 @@ public enum EzyDisconnectReason implements EzyConstant { - UNKNOWN(0), - IDLE(1), - NOT_LOGGED_IN(2), - ANOTHER_SESSION_LOGIN(3), - ADMIN_BAN(4), + UNKNOWN(0), + IDLE(1), + NOT_LOGGED_IN(2), + ANOTHER_SESSION_LOGIN(3), + ADMIN_BAN(4), ADMIN_KICK(5), MAX_REQUEST_PER_SECOND(6), MAX_REQUEST_SIZE(7), SERVER_ERROR(8); private static final Map REASONS_BY_ID = reasonsById(); - - @Getter - private final int id; - - private EzyDisconnectReason(int id) { - this.id = id; - } - - @Override - public String getName() { - return toString(); - } - - public static EzyDisconnectReason valueOf(int id) { - EzyDisconnectReason reason = REASONS_BY_ID.get(id); - return reason; - } - - private static final Map reasonsById() { + + @Getter + private final int id; + + private EzyDisconnectReason(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + + public static EzyDisconnectReason valueOf(int id) { + EzyDisconnectReason reason = REASONS_BY_ID.get(id); + return reason; + } + + private static final Map reasonsById() { Map map = new ConcurrentHashMap<>(); for(EzyDisconnectReason reason : values()) map.put(reason.getId(), reason); return map; } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyEventType.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyEventType.java index c765b31bc..dd5725ba1 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyEventType.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyEventType.java @@ -7,8 +7,8 @@ public enum EzyEventType implements EzyConstant { SERVER_INITIALIZING(0), - SERVER_READY(1), - USER_LOGIN(21), + SERVER_READY(1), + USER_LOGIN(21), USER_ACCESS_APP(25), USER_ADDED(26), USER_REMOVED(27), @@ -16,16 +16,16 @@ public enum EzyEventType implements EzyConstant { SESSION_REMOVED(35), STREAMING(36); - @Getter - private final int id; - - private EzyEventType(int id) { - this.id = id; - } - - @Override - public String getName() { - return toString(); - } - + @Getter + private final int id; + + private EzyEventType(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyMaxRequestPerSecondAction.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyMaxRequestPerSecondAction.java index f257195fd..30a980441 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyMaxRequestPerSecondAction.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyMaxRequestPerSecondAction.java @@ -8,7 +8,7 @@ public enum EzyMaxRequestPerSecondAction implements EzyConstant { DROP_REQUEST(1), DISCONNECT_SESSION(2); - + @Getter private final int id; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyTransportType.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyTransportType.java index dac0af3a8..a1ec78992 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyTransportType.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyTransportType.java @@ -6,19 +6,19 @@ public enum EzyTransportType implements EzyConstant { - TCP(1), - UDP(2); - - @Getter - private final int id; - - private EzyTransportType(int id) { - this.id = id; - } - - @Override - public String getName() { - return toString(); - } - + TCP(1), + UDP(2); + + @Getter + private final int id; + + private EzyTransportType(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractContext.java index b99350ea2..5c6eb3b19 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractContext.java @@ -29,66 +29,66 @@ public abstract class EzyAbstractContext implements EzyInitable, EzyDestroyable { protected EzyComponent component; - protected Map commandSuppliers; - protected EzyHandleException handleException; - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - @Override - public final void init() { - this.commandSuppliers = defaultCommandSuppliers(); - this.handleException = new EzyHandleExceptionImpl(component); - this.properties.put(EzyHandleException.class, handleException); - this.properties.put(EzyAddCommand.class, new EzyAddCommandImpl(this)); - this.properties.put(EzyAddExceptionHandler.class, new EzyAddExceptionHandlerImpl(component)); - this.init0(); - } - - protected void init0() {} - - @SuppressWarnings("unchecked") + protected Map commandSuppliers; + protected EzyHandleException handleException; + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + @Override + public final void init() { + this.commandSuppliers = defaultCommandSuppliers(); + this.handleException = new EzyHandleExceptionImpl(component); + this.properties.put(EzyHandleException.class, handleException); + this.properties.put(EzyAddCommand.class, new EzyAddCommandImpl(this)); + this.properties.put(EzyAddExceptionHandler.class, new EzyAddExceptionHandlerImpl(component)); + this.init0(); + } + + protected void init0() {} + + @SuppressWarnings("unchecked") public void handleEvent(EzyConstant eventType, EzyEvent event) { - List controllers = component - .getEventControllers() - .getControllers(eventType); - for (EzyEventController controller : controllers) { - controller.handle(this, event); - } - } - - public void handleException(Thread thread, Throwable throwable) { - this.handleException.handle(thread, throwable); - } - - protected Map defaultCommandSuppliers() { - Map answer = new ConcurrentHashMap<>(); - addCommandSuppliers(answer); - return answer; - } - - protected void addCommandSuppliers(Map suppliers) {} - + List controllers = component + .getEventControllers() + .getControllers(eventType); + for (EzyEventController controller : controllers) { + controller.handle(this, event); + } + } + + public void handleException(Thread thread, Throwable throwable) { + this.handleException.handle(thread, throwable); + } + + protected Map defaultCommandSuppliers() { + Map answer = new ConcurrentHashMap<>(); + addCommandSuppliers(answer); + return answer; + } + + protected void addCommandSuppliers(Map suppliers) {} + public void addCommand(Class commandType, Supplier commandSupplier) { - this.commandSuppliers.put(commandType, commandSupplier); - } - - @Override - public void destroy() { - preDestroy(); - for(Object property : properties.values()) { - if(property instanceof EzyStoppable) - ((EzyStoppable)property).stop(); - if(property instanceof EzyDestroyable) - ((EzyDestroyable)property).destroy(); - } - this.properties.clear(); - this.commandSuppliers.clear(); - this.component = null; - this.commandSuppliers = null; - this.handleException = null; - } - - protected void preDestroy() {} - - protected void postDestroy() {} - + this.commandSuppliers.put(commandType, commandSupplier); + } + + @Override + public void destroy() { + preDestroy(); + for(Object property : properties.values()) { + if(property instanceof EzyStoppable) + ((EzyStoppable)property).stop(); + if(property instanceof EzyDestroyable) + ((EzyDestroyable)property).destroy(); + } + this.properties.clear(); + this.commandSuppliers.clear(); + this.component = null; + this.commandSuppliers = null; + this.handleException = null; + } + + protected void preDestroy() {} + + protected void postDestroy() {} + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractZoneChildContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractZoneChildContext.java index 762d60904..c7017beb5 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractZoneChildContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAbstractZoneChildContext.java @@ -14,26 +14,26 @@ public abstract class EzyAbstractZoneChildContext extends EzyAbstractContext implements EzyExecutorServiceFetcher { - protected EzyZoneContext parent; + protected EzyZoneContext parent; protected ScheduledExecutorService executorService; - - public T get(Class clazz) { - T property = getProperty(clazz); - if(property != null) + + public T get(Class clazz) { + T property = getProperty(clazz); + if(property != null) return property; - return parent.get(clazz); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) + return parent.get(clazz); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) public T cmd(Class clazz) { - Supplier supplier = commandSuppliers.get(clazz); + Supplier supplier = commandSuppliers.get(clazz); if(supplier != null) return (T) supplier.get(); return parent.cmd(clazz); } - - public void setExecutorService(ScheduledExecutorService executorService) { - this.executorService = executorService; - this.properties.put(ScheduledExecutorService.class, executorService); - } + + public void setExecutorService(ScheduledExecutorService executorService) { + this.executorService = executorService; + this.properties.put(ScheduledExecutorService.class, executorService); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAppContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAppContext.java index 4393165d0..b1353f895 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAppContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyAppContext.java @@ -5,5 +5,5 @@ public interface EzyAppContext extends EzyZoneChildContext { EzyApplication getApp(); - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyComplexContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyComplexContext.java index 33f931309..6d34b1cb4 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyComplexContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyComplexContext.java @@ -47,8 +47,8 @@ default void send( // ======================= tcp/send ================= default void send( - EzyResponse response, - Collection recipients, boolean encrypted) { + EzyResponse response, + Collection recipients, boolean encrypted) { send(response, recipients, encrypted, EzyTransportType.TCP); } @@ -61,12 +61,12 @@ default void stream(byte[] bytes, Collection recipients) { } default void send( - EzyResponse response, EzySession recipient, boolean encrypted) { + EzyResponse response, EzySession recipient, boolean encrypted) { send(response, recipient, encrypted, EzyTransportType.TCP); } default void send( - EzyResponse response, EzyUser recipient, boolean encrypted) { + EzyResponse response, EzyUser recipient, boolean encrypted) { send(response, recipient, encrypted, EzyTransportType.TCP); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyContext.java index dbd7046a5..b2c1ca1e0 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyContext.java @@ -6,12 +6,12 @@ public interface EzyContext extends EzyProperties { - T get(Class clazz); - - T cmd(Class clazz); - - void handleEvent(EzyConstant eventType, EzyEvent event); - - void handleException(Thread thread, Throwable throwable); - + T get(Class clazz); + + T cmd(Class clazz); + + void handleEvent(EzyConstant eventType, EzyEvent event); + + void handleException(Thread thread, Throwable throwable); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyPluginContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyPluginContext.java index 472261596..728febf10 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyPluginContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyPluginContext.java @@ -5,5 +5,5 @@ public interface EzyPluginContext extends EzyZoneChildContext { EzyPlugin getPlugin(); - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyServerContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyServerContext.java index 0c70b246b..6b9a1e908 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyServerContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyServerContext.java @@ -8,14 +8,14 @@ public interface EzyServerContext extends EzyComplexContext { - void sendNow(EzyResponse response, EzySession recipient); - - EzyServer getServer(); - - EzyZoneContext getZoneContext(int zoneId); - - EzyZoneContext getZoneContext(String zoneName); - - List getZoneContexts(); - + void sendNow(EzyResponse response, EzySession recipient); + + EzyServer getServer(); + + EzyZoneContext getZoneContext(int zoneId); + + EzyZoneContext getZoneContext(String zoneName); + + List getZoneContexts(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleAppContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleAppContext.java index 6c6987110..c2b86a735 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleAppContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleAppContext.java @@ -27,67 +27,67 @@ import lombok.Getter; public class EzySimpleAppContext - extends EzyAbstractZoneChildContext - implements EzyAppContext { + extends EzyAbstractZoneChildContext + implements EzyAppContext { - @Getter - protected EzyApplication app; - protected EzyAppSendResponse sendResponse; - - @Override - protected void init0() { - EzySetup setup = new EzyAppSetupImpl(app); - this.sendResponse = new EzyAppSendResponseImpl(this); - this.properties.put(EzyAppSendResponse.class, sendResponse); - this.properties.put(EzyHandleException.class, new EzyAppHandleExceptionImpl(app)); - this.properties.put(EzySetup.class, setup); - this.properties.put(EzyAppSetup.class, setup); - } - - @Override - public void send( - EzyData data, - EzySession recipient, - boolean encrypted, EzyTransportType transportType) { - this.sendResponse.execute(data, recipient, encrypted, transportType); - } - - @Override - public void send( - EzyData data, - Collection recipients, - boolean encrypted, EzyTransportType transportType) { - this.sendResponse.execute(data, recipients, encrypted, transportType); - } - - public void setApp(EzyApplication app) { + @Getter + protected EzyApplication app; + protected EzyAppSendResponse sendResponse; + + @Override + protected void init0() { + EzySetup setup = new EzyAppSetupImpl(app); + this.sendResponse = new EzyAppSendResponseImpl(this); + this.properties.put(EzyAppSendResponse.class, sendResponse); + this.properties.put(EzyHandleException.class, new EzyAppHandleExceptionImpl(app)); + this.properties.put(EzySetup.class, setup); + this.properties.put(EzyAppSetup.class, setup); + } + + @Override + public void send( + EzyData data, + EzySession recipient, + boolean encrypted, EzyTransportType transportType) { + this.sendResponse.execute(data, recipient, encrypted, transportType); + } + + @Override + public void send( + EzyData data, + Collection recipients, + boolean encrypted, EzyTransportType transportType) { + this.sendResponse.execute(data, recipients, encrypted, transportType); + } + + public void setApp(EzyApplication app) { this.app = app; this.component = (EzyComponent)app; } - - @SuppressWarnings("rawtypes") - @Override - protected void addCommandSuppliers(Map suppliers) { - suppliers.put(EzyAppResponse.class, () -> new EzyAppResponseImpl(this)); - } - - @Override - public void destroy() { - super.destroy(); - this.destroyApp(); - this.clearProperties(); - } - protected void clearProperties() { - this.app = null; - this.sendResponse = null; - } - - protected void destroyApp() { - processWithLogException(( )-> ((EzyDestroyable)app).destroy()); - } - - @Override + @SuppressWarnings("rawtypes") + @Override + protected void addCommandSuppliers(Map suppliers) { + suppliers.put(EzyAppResponse.class, () -> new EzyAppResponseImpl(this)); + } + + @Override + public void destroy() { + super.destroy(); + this.destroyApp(); + this.clearProperties(); + } + + protected void clearProperties() { + this.app = null; + this.sendResponse = null; + } + + protected void destroyApp() { + processWithLogException(( )-> ((EzyDestroyable)app).destroy()); + } + + @Override public boolean equals(Object obj) { return new EzyEquals() .function(t -> t.app) diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimplePluginContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimplePluginContext.java index 20869ff24..b0a1aa785 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimplePluginContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimplePluginContext.java @@ -28,50 +28,50 @@ public class EzySimplePluginContext - extends EzyAbstractZoneChildContext - implements EzyPluginContext { + extends EzyAbstractZoneChildContext + implements EzyPluginContext { - @Getter - protected EzyPlugin plugin; - protected EzyPluginSendResponse sendResponse; - - @Override - protected void init0() { - EzySetup setup = new EzyPluginSetupImpl(plugin); - this.sendResponse = new EzyPluginSendResponseImpl(this); - this.properties.put(EzyPluginSendResponse.class, sendResponse); - this.properties.put(EzyHandleException.class, new EzyPluginHandleExceptionImpl(plugin)); - this.properties.put(EzySetup.class, setup); - this.properties.put(EzyPluginSetup.class, setup); - } - - @Override - public void send( - EzyData data, - EzySession recipient, - boolean encrypted, EzyTransportType transportType) { - this.sendResponse.execute(data, recipient, encrypted, transportType); - } - - @Override - public void send( - EzyData data, - Collection recipients, - boolean encrypted, EzyTransportType transportType) { - this.sendResponse.execute(data, recipients, encrypted, transportType); - } - - public void setPlugin(EzyPlugin plugin) { + @Getter + protected EzyPlugin plugin; + protected EzyPluginSendResponse sendResponse; + + @Override + protected void init0() { + EzySetup setup = new EzyPluginSetupImpl(plugin); + this.sendResponse = new EzyPluginSendResponseImpl(this); + this.properties.put(EzyPluginSendResponse.class, sendResponse); + this.properties.put(EzyHandleException.class, new EzyPluginHandleExceptionImpl(plugin)); + this.properties.put(EzySetup.class, setup); + this.properties.put(EzyPluginSetup.class, setup); + } + + @Override + public void send( + EzyData data, + EzySession recipient, + boolean encrypted, EzyTransportType transportType) { + this.sendResponse.execute(data, recipient, encrypted, transportType); + } + + @Override + public void send( + EzyData data, + Collection recipients, + boolean encrypted, EzyTransportType transportType) { + this.sendResponse.execute(data, recipients, encrypted, transportType); + } + + public void setPlugin(EzyPlugin plugin) { this.plugin = plugin; this.component = (EzyComponent)plugin; } - - @SuppressWarnings("rawtypes") - @Override - protected void addCommandSuppliers(Map suppliers) { - suppliers.put(EzyPluginResponse.class, () -> new EzyPluginResponseImpl(this)); - } - + + @SuppressWarnings("rawtypes") + @Override + protected void addCommandSuppliers(Map suppliers) { + suppliers.put(EzyPluginResponse.class, () -> new EzyPluginResponseImpl(this)); + } + @Override public void destroy() { super.destroy(); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleServerContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleServerContext.java index 943783e8e..e82c5043b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleServerContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleServerContext.java @@ -34,18 +34,18 @@ public class EzySimpleServerContext extends EzyAbstractComplexContext implements EzyServerContext { - @Getter - protected EzyServer server; - protected EzyStreamBytes streamBytes; - protected EzySendResponse sendResponse; - protected EzyBroadcastEvent broadcastEvent; - - @Getter - protected final List zoneContexts = new ArrayList<>(); - protected final Map zoneContextsById = new ConcurrentHashMap<>(); + @Getter + protected EzyServer server; + protected EzyStreamBytes streamBytes; + protected EzySendResponse sendResponse; + protected EzyBroadcastEvent broadcastEvent; + + @Getter + protected final List zoneContexts = new ArrayList<>(); + protected final Map zoneContextsById = new ConcurrentHashMap<>(); protected final Map zoneContextsByName = new ConcurrentHashMap<>(); - - + + @Override protected void init0() { this.broadcastEvent = new EzyBroadcastEventImpl(this); @@ -58,134 +58,134 @@ protected void init0() { this.properties.put(EzyCloseSession.class, new EzyCloseSessionImpl(this)); } - @Override - public T get(Class clazz) { - T property = getProperty(clazz); - if(property != null) + @Override + public T get(Class clazz) { + T property = getProperty(clazz); + if(property != null) return property; - throw new IllegalArgumentException("has no instance of " + clazz); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) + throw new IllegalArgumentException("has no instance of " + clazz); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public T cmd(Class clazz) { - Supplier supplier = commandSuppliers.get(clazz); - if(supplier != null) + public T cmd(Class clazz) { + Supplier supplier = commandSuppliers.get(clazz); + if(supplier != null) return (T) supplier.get(); throw new IllegalArgumentException("has no command of " + clazz); - } - - @Override - public void broadcast( - EzyConstant eventType, EzyEvent event, boolean catchException) { - broadcastEvent.fire(eventType, event, catchException); - } - - @Override - public void send( - EzyResponse response, - EzySession recipient, - boolean encrypted, EzyTransportType transportType) { - sendResponse.execute(response, recipient, encrypted, false, transportType); - } - - @Override - public void send(EzyResponse response, - Collection recipients, - boolean encrypted, EzyTransportType transportType) { - sendResponse.execute(response, recipients, encrypted, false, transportType); - } - - @Override - public void sendNow(EzyResponse response, EzySession recipient) { - sendResponse.execute(response, recipient, false, true, EzyTransportType.TCP); - } - - @Override - public void stream( - byte[] bytes, - EzySession recipient, EzyTransportType transportType) { - streamBytes.execute(bytes, recipient, transportType); - } - - @Override - public void stream( - byte[] bytes, - Collection recipients, EzyTransportType transportType) { - streamBytes.execute(bytes, recipients, transportType); - } - - public void addZoneContexts(Collection zoneContexts) { + } + + @Override + public void broadcast( + EzyConstant eventType, EzyEvent event, boolean catchException) { + broadcastEvent.fire(eventType, event, catchException); + } + + @Override + public void send( + EzyResponse response, + EzySession recipient, + boolean encrypted, EzyTransportType transportType) { + sendResponse.execute(response, recipient, encrypted, false, transportType); + } + + @Override + public void send(EzyResponse response, + Collection recipients, + boolean encrypted, EzyTransportType transportType) { + sendResponse.execute(response, recipients, encrypted, false, transportType); + } + + @Override + public void sendNow(EzyResponse response, EzySession recipient) { + sendResponse.execute(response, recipient, false, true, EzyTransportType.TCP); + } + + @Override + public void stream( + byte[] bytes, + EzySession recipient, EzyTransportType transportType) { + streamBytes.execute(bytes, recipient, transportType); + } + + @Override + public void stream( + byte[] bytes, + Collection recipients, EzyTransportType transportType) { + streamBytes.execute(bytes, recipients, transportType); + } + + public void addZoneContexts(Collection zoneContexts) { for(EzyZoneContext ctx : zoneContexts) addZoneContext(ctx.getZone().getSetting(), ctx); } - - public void addZoneContext(EzyZoneSetting zone, EzyZoneContext zoneContext) { - zoneContexts.add(zoneContext); - zoneContextsById.put(zone.getId(), zoneContext); - zoneContextsByName.put(zone.getName(), zoneContext); - addAppContexts(((EzyAppContextsFetcher)zoneContext).getAppContexts()); - addPluginContexts(((EzyPluginContextsFetcher)zoneContext).getPluginContexts()); - } - - @Override - public EzyZoneContext getZoneContext(int zoneId) { - EzyZoneContext zoneContext = zoneContextsById.get(zoneId); - if(zoneContext != null) - return zoneContext; - throw new EzyZoneNotFoundException(zoneId); - } - - @Override - public EzyZoneContext getZoneContext(String zoneName) { - EzyZoneContext zoneContext = zoneContextsByName.get(zoneName); - if(zoneContext != null) - return zoneContext; - throw new EzyZoneNotFoundException(zoneName); - } - - public void setServer(EzyServer server) { + + public void addZoneContext(EzyZoneSetting zone, EzyZoneContext zoneContext) { + zoneContexts.add(zoneContext); + zoneContextsById.put(zone.getId(), zoneContext); + zoneContextsByName.put(zone.getName(), zoneContext); + addAppContexts(((EzyAppContextsFetcher)zoneContext).getAppContexts()); + addPluginContexts(((EzyPluginContextsFetcher)zoneContext).getPluginContexts()); + } + + @Override + public EzyZoneContext getZoneContext(int zoneId) { + EzyZoneContext zoneContext = zoneContextsById.get(zoneId); + if(zoneContext != null) + return zoneContext; + throw new EzyZoneNotFoundException(zoneId); + } + + @Override + public EzyZoneContext getZoneContext(String zoneName) { + EzyZoneContext zoneContext = zoneContextsByName.get(zoneName); + if(zoneContext != null) + return zoneContext; + throw new EzyZoneNotFoundException(zoneName); + } + + public void setServer(EzyServer server) { this.server = server; this.component = (EzyComponent)server; } - - @Override - protected void destroyComponents() { - destroyZoneContexts(); - destroyServer(); - } - - @Override - protected void clearProperties() { - super.clearProperties(); - this.server = null; - this.sendResponse = null; - this.broadcastEvent = null; - this.zoneContexts.clear(); - this.zoneContextsById.clear(); - this.zoneContextsByName.clear(); - } - - private void destroyServer() { - processWithLogException(() -> ((EzyDestroyable)server).destroy()); - } - - private void destroyZoneContexts() { - for(EzyZoneContext zc : zoneContextsById.values()) - this.destroyZoneContext(zc); - } - - private void destroyZoneContext(EzyZoneContext zoneContext) { - processWithLogException(() -> ((EzyDestroyable)zoneContext).destroy()); - } - - @Override - protected void preDestroy() { - logger.debug("destroy ServerContext ..."); - } - - @Override - protected void postDestroy() { - logger.debug("ServerContext has destroyed"); - } + + @Override + protected void destroyComponents() { + destroyZoneContexts(); + destroyServer(); + } + + @Override + protected void clearProperties() { + super.clearProperties(); + this.server = null; + this.sendResponse = null; + this.broadcastEvent = null; + this.zoneContexts.clear(); + this.zoneContextsById.clear(); + this.zoneContextsByName.clear(); + } + + private void destroyServer() { + processWithLogException(() -> ((EzyDestroyable)server).destroy()); + } + + private void destroyZoneContexts() { + for(EzyZoneContext zc : zoneContextsById.values()) + this.destroyZoneContext(zc); + } + + private void destroyZoneContext(EzyZoneContext zoneContext) { + processWithLogException(() -> ((EzyDestroyable)zoneContext).destroy()); + } + + @Override + protected void preDestroy() { + logger.debug("destroy ServerContext ..."); + } + + @Override + protected void postDestroy() { + logger.debug("ServerContext has destroyed"); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleZoneContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleZoneContext.java index d13cc0df8..d88b6e88a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleZoneContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleZoneContext.java @@ -35,32 +35,32 @@ public class EzySimpleZoneContext extends EzyAbstractComplexContext implements EzyZoneContext, EzyChildContext { - @Getter - protected EzyZone zone; - - @Setter @Getter - protected EzyServerContext parent; - protected EzyBroadcastEvent broadcastEvent; - protected EzyBroadcastAppsEvent broadcastAppsEvent; - protected EzyBroadcastPluginsEvent broadcastPluginsEvent; - - protected final Map appContextsByName = new ConcurrentHashMap<>(); - protected final Map pluginContextsByName = new ConcurrentHashMap<>(); - - @Override - protected void init0() { - this.broadcastEvent = new EzyZoneBroadcastEventImpl(this); - this.broadcastAppsEvent = new EzyBroadcastAppsEventImpl(this); - this.broadcastPluginsEvent = new EzyBroadcastPluginsEventImpl(this); - this.properties.put(EzyBroadcastEvent.class, broadcastEvent); - this.properties.put(EzyBroadcastAppsEvent.class, broadcastAppsEvent); - this.properties.put(EzyBroadcastPluginsEvent.class, broadcastPluginsEvent); - } - - @Override + protected EzyZone zone; + + @Setter + @Getter + protected EzyServerContext parent; + protected EzyBroadcastEvent broadcastEvent; + protected EzyBroadcastAppsEvent broadcastAppsEvent; + protected EzyBroadcastPluginsEvent broadcastPluginsEvent; + + protected final Map appContextsByName = new ConcurrentHashMap<>(); + protected final Map pluginContextsByName = new ConcurrentHashMap<>(); + + @Override + protected void init0() { + this.broadcastEvent = new EzyZoneBroadcastEventImpl(this); + this.broadcastAppsEvent = new EzyBroadcastAppsEventImpl(this); + this.broadcastPluginsEvent = new EzyBroadcastPluginsEventImpl(this); + this.properties.put(EzyBroadcastEvent.class, broadcastEvent); + this.properties.put(EzyBroadcastAppsEvent.class, broadcastAppsEvent); + this.properties.put(EzyBroadcastPluginsEvent.class, broadcastPluginsEvent); + } + + @Override public T get(Class clazz) { - T property = getProperty(clazz); + T property = getProperty(clazz); if(property != null) return property; return parent.get(clazz); @@ -104,92 +104,92 @@ public void broadcastApps(EzyConstant type, EzyEvent event, EzyUser user, boolea public void broadcastApps(EzyConstant type, EzyEvent event, Predicate filter, boolean catchException) { broadcastAppsEvent.fire(type, event, filter, catchException); } - - @Override - public void addAppContext(EzyAppSetting app, EzyAppContext appContext) { - super.addAppContext(app, appContext); - appContextsByName.put(app.getName(), appContext); - } - - @Override - public void addPluginContext(EzyPluginSetting plugin, EzyPluginContext pluginContext) { - super.addPluginContext(plugin, pluginContext); - pluginContextsByName.put(plugin.getName(), pluginContext); - } - - @Override + + @Override + public void addAppContext(EzyAppSetting app, EzyAppContext appContext) { + super.addAppContext(app, appContext); + appContextsByName.put(app.getName(), appContext); + } + + @Override + public void addPluginContext(EzyPluginSetting plugin, EzyPluginContext pluginContext) { + super.addPluginContext(plugin, pluginContext); + pluginContextsByName.put(plugin.getName(), pluginContext); + } + + @Override public EzyAppContext getAppContext(String appName) { - EzyAppContext appContext = appContextsByName.get(appName); + EzyAppContext appContext = appContextsByName.get(appName); if(appContext != null) return appContext; throw new IllegalArgumentException("has not app with name = " + appName); } - - @Override + + @Override public EzyPluginContext getPluginContext(String pluginName) { - EzyPluginContext pluginContext = pluginContextsByName.get(pluginName); + EzyPluginContext pluginContext = pluginContextsByName.get(pluginName); if(pluginContext != null) return pluginContext; throw new IllegalArgumentException("has not plugin with name = " + pluginName); } - - public void setZone(EzyZone zone) { + + public void setZone(EzyZone zone) { this.zone = zone; this.component = (EzyComponent)zone; } - - @Override - public void send( - EzyResponse response, - EzySession recipient, - boolean encrypted, - EzyTransportType transportType) { - parent.send(response, recipient, encrypted, transportType); - } - - @Override - public void send( - EzyResponse response, - Collection recipients, - boolean encrypted, - EzyTransportType transportType) { - parent.send(response, recipients, encrypted, transportType); - } - - @Override - public void stream( - byte[] bytes, - EzySession recipient, EzyTransportType transportType) { - parent.stream(bytes, recipient, transportType); - } - - @Override - public void stream( - byte[] bytes, - Collection recipients, EzyTransportType transportType) { - parent.stream(bytes, recipients, transportType); - } - - @Override - protected void destroyComponents() { - destroyAppContexts(); + + @Override + public void send( + EzyResponse response, + EzySession recipient, + boolean encrypted, + EzyTransportType transportType) { + parent.send(response, recipient, encrypted, transportType); + } + + @Override + public void send( + EzyResponse response, + Collection recipients, + boolean encrypted, + EzyTransportType transportType) { + parent.send(response, recipients, encrypted, transportType); + } + + @Override + public void stream( + byte[] bytes, + EzySession recipient, EzyTransportType transportType) { + parent.stream(bytes, recipient, transportType); + } + + @Override + public void stream( + byte[] bytes, + Collection recipients, EzyTransportType transportType) { + parent.stream(bytes, recipients, transportType); + } + + @Override + protected void destroyComponents() { + destroyAppContexts(); destroyPluginContexts(); destroyZone(); - } - - @Override - protected void clearProperties() { - super.clearProperties(); - this.zone = null; - this.parent = null; - this.broadcastEvent = null; - this.broadcastAppsEvent = null; - this.broadcastPluginsEvent = null; - this.appContextsByName.clear(); - this.pluginContextsByName.clear(); - } - - private void destroyAppContexts() { + } + + @Override + protected void clearProperties() { + super.clearProperties(); + this.zone = null; + this.parent = null; + this.broadcastEvent = null; + this.broadcastAppsEvent = null; + this.broadcastPluginsEvent = null; + this.appContextsByName.clear(); + this.pluginContextsByName.clear(); + } + + private void destroyAppContexts() { for(EzyAppContext ac : appContexts) this.destroyAppContext(ac); } @@ -210,8 +210,8 @@ private void destroyAppContext(EzyAppContext appContext) { private void destroyPluginContext(EzyPluginContext pluginContext) { processWithLogException(() -> ((EzyDestroyable)pluginContext).destroy()); } - - @Override + + @Override public boolean equals(Object obj) { return new EzyEquals() .function(t -> t.zone) @@ -227,5 +227,5 @@ public int hashCode() { protected void preDestroy() { logger.debug("destroy ZoneContext({})", zone); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyZoneContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyZoneContext.java index 7abda8356..1ad7e2e63 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyZoneContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyZoneContext.java @@ -9,22 +9,22 @@ public interface EzyZoneContext extends EzyComplexContext { - EzyZone getZone(); - - EzyServerContext getParent(); - - EzyAppContext getAppContext(String appName); - - EzyPluginContext getPluginContext(String pluginName); - - void broadcastPlugins(EzyConstant type, EzyEvent event, boolean catchExeption); - - void broadcastApps(EzyConstant type, EzyEvent event, boolean catchExeption); - - void broadcastApps(EzyConstant type, EzyEvent event, String username, boolean catchExeption); - - void broadcastApps(EzyConstant type, EzyEvent event, EzyUser user, boolean catchExeption); - - void broadcastApps(EzyConstant type, EzyEvent event, Predicate filter, boolean catchExeption); - + EzyZone getZone(); + + EzyServerContext getParent(); + + EzyAppContext getAppContext(String appName); + + EzyPluginContext getPluginContext(String pluginName); + + void broadcastPlugins(EzyConstant type, EzyEvent event, boolean catchExeption); + + void broadcastApps(EzyConstant type, EzyEvent event, boolean catchExeption); + + void broadcastApps(EzyConstant type, EzyEvent event, String username, boolean catchExeption); + + void broadcastApps(EzyConstant type, EzyEvent event, EzyUser user, boolean catchExeption); + + void broadcastApps(EzyConstant type, EzyEvent event, Predicate filter, boolean catchExeption); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractAppEventController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractAppEventController.java index 14e0b03e0..9f799d39a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractAppEventController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractAppEventController.java @@ -3,7 +3,7 @@ import com.tvd12.ezyfox.util.EzyEntityBuilders; public abstract class EzyAbstractAppEventController - extends EzyEntityBuilders - implements EzyAppEventController { + extends EzyEntityBuilders + implements EzyAppEventController { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractPluginEventController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractPluginEventController.java index 6eed4ebb4..f0e1b9381 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractPluginEventController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractPluginEventController.java @@ -3,7 +3,7 @@ import com.tvd12.ezyfox.util.EzyLoggable; public abstract class EzyAbstractPluginEventController - extends EzyLoggable - implements EzyPluginEventController { + extends EzyLoggable + implements EzyPluginEventController { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractServerController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractServerController.java index 0c0d1a34a..4b95ad091 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractServerController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAbstractServerController.java @@ -15,33 +15,33 @@ public class EzyAbstractServerController extends EzyAbstractController { - protected EzyServer getServer(EzyServerContext ctx) { - return ctx.getServer(); - } - - protected EzySettings getSettings(EzyServerContext ctx) { - return EzyServerContexts.getSettings(ctx); - } - - protected EzyZoneUserManager getUserManager(EzyZoneContext ctx) { - return EzyZoneContexts.getUserManager(ctx); - } - - protected EzySessionManager getSessionManager(EzyServerContext ctx) { - return EzyServerContexts.getSessionManager(ctx); - } - - protected EzyAppContext getAppContext(EzyServerContext ctx, int appId) { - return ctx.getAppContext(appId); - } - - protected EzyServerControllers getControllers(EzyServerContext ctx) { - return getServer(ctx).getControllers(); - } - - @SuppressWarnings("rawtypes") - protected EzyController getController(EzyServerContext ctx, EzyConstant cmd) { - return getServer(ctx).getControllers().getController(cmd); - } - + protected EzyServer getServer(EzyServerContext ctx) { + return ctx.getServer(); + } + + protected EzySettings getSettings(EzyServerContext ctx) { + return EzyServerContexts.getSettings(ctx); + } + + protected EzyZoneUserManager getUserManager(EzyZoneContext ctx) { + return EzyZoneContexts.getUserManager(ctx); + } + + protected EzySessionManager getSessionManager(EzyServerContext ctx) { + return EzyServerContexts.getSessionManager(ctx); + } + + protected EzyAppContext getAppContext(EzyServerContext ctx, int appId) { + return ctx.getAppContext(appId); + } + + protected EzyServerControllers getControllers(EzyServerContext ctx) { + return getServer(ctx).getControllers(); + } + + @SuppressWarnings("rawtypes") + protected EzyController getController(EzyServerContext ctx, EzyConstant cmd) { + return getServer(ctx).getControllers().getController(cmd); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAccessAppController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAccessAppController.java index 4a8f3ba07..c18acba91 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAccessAppController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAccessAppController.java @@ -27,23 +27,23 @@ import com.tvd12.ezyfoxserver.wrapper.EzyAppUserManager; public class EzyAccessAppController - extends EzyAbstractServerController - implements EzyServerController { + extends EzyAbstractServerController + implements EzyServerController { - @Override - public void handle(EzyServerContext ctx, EzyAccessAppRequest request) { - try { - handle0(ctx, request); - } - catch(EzyAccessAppException e) { + @Override + public void handle(EzyServerContext ctx, EzyAccessAppRequest request) { + try { + handle0(ctx, request); + } + catch(EzyAccessAppException e) { responseAccessAppError(ctx, request.getSession(), e); throw e; } - } - - protected void handle0(EzyServerContext ctx, EzyAccessAppRequest request) { - EzyUser user = request.getUser(); - int zoneId = user.getZoneId(); + } + + protected void handle0(EzyServerContext ctx, EzyAccessAppRequest request) { + EzyUser user = request.getUser(); + int zoneId = user.getZoneId(); EzyAccessAppParams params = request.getParams(); EzyZoneContext zoneContext = ctx.getZoneContext(zoneId); EzyAppContext appContext = zoneContext.getAppContext(params.getAppName()); @@ -69,7 +69,7 @@ protected void handle0(EzyServerContext ctx, EzyAccessAppRequest request) { EzyUserAccessedAppEvent accessedAppEvent = newAccessedAppEvent(user); appContext.handleEvent(EzyEventType.USER_ACCESSED_APP, accessedAppEvent); } - + EzyArray output = accessAppEvent.getOutput(); EzyResponse accessAppResponse = newAccessAppResponse(zoneId, appSetting, output); ctx.send(accessAppResponse, session, false); @@ -80,50 +80,50 @@ protected void handle0(EzyServerContext ctx, EzyAccessAppRequest request) { } } - - protected void checkAppUserMangerAvailable(EzyAppUserManager appUserManger) { - int current = appUserManger.getUserCount(); - int max = appUserManger.getMaxUsers(); - String appName = appUserManger.getAppName(); - if(current >= max) - throw EzyAccessAppException.maximumUser(appName, current, max); - } - - protected void addUser( - EzyAppUserManager appUserManger, EzyUser user, EzyAppSetting setting) { - try { - appUserManger.addUser(user); - } - catch(EzyMaxUserException e) { - throw EzyAccessAppException.maximumUser(setting.getName(), e); - } - } - - protected EzyUserAccessAppEvent newAccessAppEvent(EzyUser user) { - return new EzySimpleUserAccessAppEvent(user); - } - - protected EzyUserAccessedAppEvent newAccessedAppEvent(EzyUser user) { - return new EzySimpleUserAccessedAppEvent(user); + + protected void checkAppUserMangerAvailable(EzyAppUserManager appUserManger) { + int current = appUserManger.getUserCount(); + int max = appUserManger.getMaxUsers(); + String appName = appUserManger.getAppName(); + if(current >= max) + throw EzyAccessAppException.maximumUser(appName, current, max); + } + + protected void addUser( + EzyAppUserManager appUserManger, EzyUser user, EzyAppSetting setting) { + try { + appUserManger.addUser(user); + } + catch(EzyMaxUserException e) { + throw EzyAccessAppException.maximumUser(setting.getName(), e); + } + } + + protected EzyUserAccessAppEvent newAccessAppEvent(EzyUser user) { + return new EzySimpleUserAccessAppEvent(user); + } + + protected EzyUserAccessedAppEvent newAccessedAppEvent(EzyUser user) { + return new EzySimpleUserAccessedAppEvent(user); } - - protected EzyResponse newAccessAppResponse(int zoneId, EzyAppSetting app, EzyArray data) { - com.tvd12.ezyfoxserver.response.EzyAccessAppParams params = - new com.tvd12.ezyfoxserver.response.EzyAccessAppParams(); - params.setApp(app); - params.setData(data); - return new EzyAccessAppResponse(params); - } - - protected EzyResponse newAccessAppErrorResponse(EzyIAccessAppError error) { - EzyErrorParams params = new EzyErrorParams(); - params.setError(error); + + protected EzyResponse newAccessAppResponse(int zoneId, EzyAppSetting app, EzyArray data) { + com.tvd12.ezyfoxserver.response.EzyAccessAppParams params = + new com.tvd12.ezyfoxserver.response.EzyAccessAppParams(); + params.setApp(app); + params.setData(data); + return new EzyAccessAppResponse(params); + } + + protected EzyResponse newAccessAppErrorResponse(EzyIAccessAppError error) { + EzyErrorParams params = new EzyErrorParams(); + params.setError(error); return new EzyAccessAppErrorResponse(params); } - - protected void responseAccessAppError( - EzyServerContext ctx, EzySession session, EzyAccessAppException exception) { - EzyResponse response = newAccessAppErrorResponse(exception.getError()); - ctx.send(response, session, false); + + protected void responseAccessAppError( + EzyServerContext ctx, EzySession session, EzyAccessAppException exception) { + EzyResponse response = newAccessAppErrorResponse(exception.getError()); + ctx.send(response, session, false); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppController.java index d30d3e914..2318dfe57 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppController.java @@ -3,5 +3,5 @@ import com.tvd12.ezyfoxserver.context.EzyAppContext; public interface EzyAppController - extends EzyController { + extends EzyController { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppEventController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppEventController.java index 81bbc4768..367b3a548 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppEventController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyAppEventController.java @@ -3,6 +3,6 @@ import com.tvd12.ezyfoxserver.context.EzyAppContext; public interface EzyAppEventController - extends EzyEventController { + extends EzyEventController { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyController.java index 1a015e6e3..18506162a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyController.java @@ -1,7 +1,7 @@ package com.tvd12.ezyfoxserver.controller; public interface EzyController { - - void handle(C ctx, R request); - + + void handle(C ctx, R request); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyEventController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyEventController.java index 2178f9440..74cee5daf 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyEventController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyEventController.java @@ -2,6 +2,6 @@ public interface EzyEventController { - void handle(C ctx, E event); - + void handle(C ctx, E event); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyHandshakeController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyHandshakeController.java index 86f28d5a0..121ec5745 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyHandshakeController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyHandshakeController.java @@ -15,77 +15,77 @@ import com.tvd12.ezyfoxserver.response.EzyResponse; public class EzyHandshakeController - extends EzyAbstractServerController - implements EzyServerController { + extends EzyAbstractServerController + implements EzyServerController { - @Override - public void handle(EzyServerContext ctx, EzyHandShakeRequest request) { - EzySession session = request.getSession(); - EzyHandshakeParams params = request.getParams(); - EzyHandshakeEvent event = newHandshakeEvent(session, params); - handleSocketSSL(ctx, event); - updateSession(session, event); - EzyResponse response = newHandShakeResponse(session, event); - ctx.send(response, session, false); - event.release(); - } - - protected void handleSocketSSL(EzyServerContext ctx, EzyHandshakeEvent event) { - EzySession session = event.getSession(); - if(session.getConnectionType() == EzyConnectionType.WEBSOCKET) - return; - boolean enableSSL = ctx.getServer().getSettings().getSocket().isSslActive(); - if(!enableSSL) - return; - if(!event.isEnableEncryption()) - return; - byte[] clientKey = event.getClientKey(); - byte[] sessionKey = EzyAesCrypt.randomKey(); - byte[] encryptedSessionKey = sessionKey; - try { - if(clientKey.length > 0) { - encryptedSessionKey = EzyAsyCrypt.builder() - .publicKey(clientKey) - .build() - .encrypt(sessionKey); - } - } - catch (Exception e) { - logger.debug("cannot encrypt session key for session: {}", session, e); - } - event.setSessionKey(sessionKey); - event.setEncryptedSessionKey(encryptedSessionKey); - } - - protected void updateSession(EzySession session, EzyHandshakeEvent event) { - session.setClientId(event.getClientId()); - session.setClientKey(event.getClientKey()); - session.setClientType(event.getClientType()); - session.setClientVersion(event.getClientVersion()); - session.setSessionKey(event.getSessionKey()); - ((EzyAbstractSession)session).setBeforeToken(event.getReconnectToken()); - } - - protected EzyHandshakeEvent newHandshakeEvent( - EzySession session, EzyHandshakeParams params) { - return new EzySimpleHandshakeEvent( - session, - params.getClientId(), - params.getClientKey(), - params.getClientType(), - params.getClientVersion(), - params.getReconnectToken(), - params.isEnableEncryption()); - } - - protected EzyResponse newHandShakeResponse( - EzySession session, EzyHandshakeEvent event) { - EzyHandShakeParams params = new EzyHandShakeParams(); - params.setServerPublicKey(session.getPublicKey()); - params.setReconnectToken(session.getToken()); - params.setSessionId(session.getId()); - params.setSessionKey(event.getEncryptedSessionKey()); - return new EzyHandShakeResponse(params); - } - + @Override + public void handle(EzyServerContext ctx, EzyHandShakeRequest request) { + EzySession session = request.getSession(); + EzyHandshakeParams params = request.getParams(); + EzyHandshakeEvent event = newHandshakeEvent(session, params); + handleSocketSSL(ctx, event); + updateSession(session, event); + EzyResponse response = newHandShakeResponse(session, event); + ctx.send(response, session, false); + event.release(); + } + + protected void handleSocketSSL(EzyServerContext ctx, EzyHandshakeEvent event) { + EzySession session = event.getSession(); + if(session.getConnectionType() == EzyConnectionType.WEBSOCKET) + return; + boolean enableSSL = ctx.getServer().getSettings().getSocket().isSslActive(); + if(!enableSSL) + return; + if(!event.isEnableEncryption()) + return; + byte[] clientKey = event.getClientKey(); + byte[] sessionKey = EzyAesCrypt.randomKey(); + byte[] encryptedSessionKey = sessionKey; + try { + if(clientKey.length > 0) { + encryptedSessionKey = EzyAsyCrypt.builder() + .publicKey(clientKey) + .build() + .encrypt(sessionKey); + } + } + catch (Exception e) { + logger.debug("cannot encrypt session key for session: {}", session, e); + } + event.setSessionKey(sessionKey); + event.setEncryptedSessionKey(encryptedSessionKey); + } + + protected void updateSession(EzySession session, EzyHandshakeEvent event) { + session.setClientId(event.getClientId()); + session.setClientKey(event.getClientKey()); + session.setClientType(event.getClientType()); + session.setClientVersion(event.getClientVersion()); + session.setSessionKey(event.getSessionKey()); + ((EzyAbstractSession)session).setBeforeToken(event.getReconnectToken()); + } + + protected EzyHandshakeEvent newHandshakeEvent( + EzySession session, EzyHandshakeParams params) { + return new EzySimpleHandshakeEvent( + session, + params.getClientId(), + params.getClientKey(), + params.getClientType(), + params.getClientVersion(), + params.getReconnectToken(), + params.isEnableEncryption()); + } + + protected EzyResponse newHandShakeResponse( + EzySession session, EzyHandshakeEvent event) { + EzyHandShakeParams params = new EzyHandShakeParams(); + params.setServerPublicKey(session.getPublicKey()); + params.setReconnectToken(session.getToken()); + params.setSessionId(session.getId()); + params.setSessionKey(event.getEncryptedSessionKey()); + return new EzyHandShakeResponse(params); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginController.java index f113816b7..f550dcf7a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginController.java @@ -21,70 +21,70 @@ import com.tvd12.ezyfoxserver.response.EzyResponse; public class EzyLoginController - extends EzyAbstractServerController - implements EzyServerController { + extends EzyAbstractServerController + implements EzyServerController { - @Override - public void handle(EzyServerContext ctx, EzyLoginRequest request) { - try { - EzySession session = request.getSession(); - EzyLoginParams params = request.getParams(); - EzyZoneContext zoneContext = ctx.getZoneContext(params.getZoneName()); - EzyUserLoginEvent loginEvent = newLoginEvent(session, params); - try { - control(ctx, zoneContext, loginEvent); - } - finally { - loginEvent.release(); - } + @Override + public void handle(EzyServerContext ctx, EzyLoginRequest request) { + try { + EzySession session = request.getSession(); + EzyLoginParams params = request.getParams(); + EzyZoneContext zoneContext = ctx.getZoneContext(params.getZoneName()); + EzyUserLoginEvent loginEvent = newLoginEvent(session, params); + try { + control(ctx, zoneContext, loginEvent); + } + finally { + loginEvent.release(); + } } catch(EzyLoginErrorException e) { processException(ctx, request.getSession(), e); throw e; } - catch(EzyMaxUserException e) { - processException(ctx, request.getSession(), maximumUsers(e)); - throw e; - } - catch(EzyZoneNotFoundException e) { - processException(ctx, request.getSession(), zoneNotFound(e)); - throw e; - } - catch(Exception e) { - processException(ctx, request.getSession(), serverError(e)); - throw e; - } - } - - protected void processException( - EzyServerContext ctx, EzySession session, EzyLoginErrorException e) { - responseLoginError(ctx, session, e.getError()); - } - - protected void control( - EzyServerContext ctx, EzyZoneContext zoneContext, EzyUserLoginEvent event) { - firePluginEvent(zoneContext, event); - process(ctx, zoneContext, event); - } - - protected void process( - EzyServerContext ctx, EzyZoneContext zoneContext, EzyUserLoginEvent event) { - EzyLoginProcessor processor = new EzyLoginProcessor(ctx); - processor.apply(zoneContext, event); - } - - protected void firePluginEvent(EzyZoneContext ctx, EzyUserLoginEvent event) { + catch(EzyMaxUserException e) { + processException(ctx, request.getSession(), maximumUsers(e)); + throw e; + } + catch(EzyZoneNotFoundException e) { + processException(ctx, request.getSession(), zoneNotFound(e)); + throw e; + } + catch(Exception e) { + processException(ctx, request.getSession(), serverError(e)); + throw e; + } + } + + protected void processException( + EzyServerContext ctx, EzySession session, EzyLoginErrorException e) { + responseLoginError(ctx, session, e.getError()); + } + + protected void control( + EzyServerContext ctx, EzyZoneContext zoneContext, EzyUserLoginEvent event) { + firePluginEvent(zoneContext, event); + process(ctx, zoneContext, event); + } + + protected void process( + EzyServerContext ctx, EzyZoneContext zoneContext, EzyUserLoginEvent event) { + EzyLoginProcessor processor = new EzyLoginProcessor(ctx); + processor.apply(zoneContext, event); + } + + protected void firePluginEvent(EzyZoneContext ctx, EzyUserLoginEvent event) { ctx.broadcastPlugins(EzyEventType.USER_LOGIN, event, false); } - - protected EzyUserLoginEvent newLoginEvent(EzySession session, EzyLoginParams params) { - return new EzySimpleUserLoginEvent( - session, - params.getZoneName(), - params.getUsername(), - params.getPassword(), params.getData()); - } - + + protected EzyUserLoginEvent newLoginEvent(EzySession session, EzyLoginParams params) { + return new EzySimpleUserLoginEvent( + session, + params.getZoneName(), + params.getUsername(), + params.getPassword(), params.getData()); + } + protected void responseLoginError(EzyServerContext ctx, EzySession session, EzyILoginError error) { EzyResponse response = newLoginErrorReponse(error); ctx.send(response, session, false); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginProcessor.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginProcessor.java index 400470916..e3698955a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginProcessor.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginProcessor.java @@ -45,8 +45,8 @@ public class EzyLoginProcessor extends EzyEntityBuilders { public EzyLoginProcessor(EzyServerContext serverContext) { this.serverContext = serverContext; - this.sessionManager = getSessionManager(serverContext); - this.userStats = getStatistics(serverContext).getUserStats(); + this.sessionManager = getSessionManager(serverContext); + this.userStats = getStatistics(serverContext).getUserStats(); } public void apply(EzyZoneContext zoneContext, EzyUserLoginEvent event) { @@ -110,8 +110,8 @@ protected void processUserSessions(EzyUser user, int sessionCount = user.getSessionCount(); if(sessionCount >= maxSessionPerUser) { if(sessionCount > maxSessionPerUser - || maxSessionPerUser > 1 - || !allowChangeSession) + || maxSessionPerUser > 1 + || !allowChangeSession) throw new EzyLoginErrorException(EzyLoginError.MAXIMUM_SESSION); } session.setLoggedIn(true); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginEventController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginEventController.java index 4169da33c..080679061 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginEventController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginEventController.java @@ -3,6 +3,6 @@ import com.tvd12.ezyfoxserver.context.EzyPluginContext; public interface EzyPluginEventController - extends EzyEventController { + extends EzyEventController { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginInfoController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginInfoController.java index 2319a4992..f14df894a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginInfoController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPluginInfoController.java @@ -12,28 +12,28 @@ import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; public class EzyPluginInfoController - extends EzyAbstractServerController - implements EzyServerController { + extends EzyAbstractServerController + implements EzyServerController { - @Override - public void handle(EzyServerContext ctx, EzyPluginInfoRequest request) { - EzyUser user = request.getUser(); - EzySession session = request.getSession(); - EzyPluginInfoParams params = request.getParams(); - EzyZoneContext zoneCtx = ctx.getZoneContext(user.getZoneId()); - EzyPluginContext pluginCtx = zoneCtx.getPluginContext(params.getPluginName()); - if(pluginCtx != null) { - EzyPluginSetting setting = pluginCtx.getPlugin().getSetting(); - EzyResponse response = newPluginInfoResponse(setting); - ctx.send(response, session, false); - } - } - - protected EzyResponse newPluginInfoResponse(EzyPluginSetting pluginSetting) { + @Override + public void handle(EzyServerContext ctx, EzyPluginInfoRequest request) { + EzyUser user = request.getUser(); + EzySession session = request.getSession(); + EzyPluginInfoParams params = request.getParams(); + EzyZoneContext zoneCtx = ctx.getZoneContext(user.getZoneId()); + EzyPluginContext pluginCtx = zoneCtx.getPluginContext(params.getPluginName()); + if(pluginCtx != null) { + EzyPluginSetting setting = pluginCtx.getPlugin().getSetting(); + EzyResponse response = newPluginInfoResponse(setting); + ctx.send(response, session, false); + } + } + + protected EzyResponse newPluginInfoResponse(EzyPluginSetting pluginSetting) { com.tvd12.ezyfoxserver.response.EzyPluginInfoParams params = new com.tvd12.ezyfoxserver.response.EzyPluginInfoParams(); params.setPlugin(pluginSetting); return new EzyPluginInfoResponse(params); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestAppController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestAppController.java index 8d00be3f3..e2af59ae8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestAppController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestAppController.java @@ -18,43 +18,43 @@ import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; public class EzyRequestAppController - extends EzyAbstractServerController - implements EzyServerController { + extends EzyAbstractServerController + implements EzyServerController { - @Override - public void handle(EzyServerContext ctx, EzyRequestAppRequest request) { - EzyRequestAppParams params = request.getParams(); - EzyAppContext appCtx = ctx.getAppContext(params.getAppId()); - EzyApplication app = appCtx.getApp(); - EzyAppRequestController requestController = app.getRequestController(); - - // user manager for checking, user must be managed - EzyUserManager userManger = appCtx.getApp().getUserManager(); - - EzyUser user = request.getUser(); - - // check user joined app or not to prevent spam request - boolean hasAccessed = userManger.containsUser(user); - - if(hasAccessed) { + @Override + public void handle(EzyServerContext ctx, EzyRequestAppRequest request) { + EzyRequestAppParams params = request.getParams(); + EzyAppContext appCtx = ctx.getAppContext(params.getAppId()); + EzyApplication app = appCtx.getApp(); + EzyAppRequestController requestController = app.getRequestController(); + + // user manager for checking, user must be managed + EzyUserManager userManger = appCtx.getApp().getUserManager(); + + EzyUser user = request.getUser(); + + // check user joined app or not to prevent spam request + boolean hasAccessed = userManger.containsUser(user); + + if(hasAccessed) { // redirect handling to app - EzyUserRequestAppEvent event = newRequestAppEvent(request); + EzyUserRequestAppEvent event = newRequestAppEvent(request); requestController.handle(appCtx, event); - } - else { - EzySession session = request.getSession(); - responseRequestAppError(ctx, session, EzyRequestAppError.HAS_NOT_ACCESSED); - } - } - - protected EzyUserRequestAppEvent newRequestAppEvent(EzyRequestAppRequest request) { - return new EzySimpleUserRequestAppEvent( - request.getUser(), - request.getSession(), - request.getParams().getData()); - } - - protected EzyResponse newRequestAppErrorReponse(EzyIRequestAppError error) { + } + else { + EzySession session = request.getSession(); + responseRequestAppError(ctx, session, EzyRequestAppError.HAS_NOT_ACCESSED); + } + } + + protected EzyUserRequestAppEvent newRequestAppEvent(EzyRequestAppRequest request) { + return new EzySimpleUserRequestAppEvent( + request.getUser(), + request.getSession(), + request.getParams().getData()); + } + + protected EzyResponse newRequestAppErrorReponse(EzyIRequestAppError error) { EzyErrorParams params = new EzyErrorParams(); params.setError(error); return new EzyRequestAppErrorResponse(params); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestPluginController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestPluginController.java index 8e8cd261e..86a7dd2a0 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestPluginController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestPluginController.java @@ -12,33 +12,33 @@ import com.tvd12.ezyfoxserver.request.EzyRequestPluginRequest; public class EzyRequestPluginController - extends EzyAbstractServerController - implements EzyServerController { + extends EzyAbstractServerController + implements EzyServerController { - @Override - public void handle(EzyServerContext ctx, EzyRequestPluginRequest request) { - EzyRequestPluginParams params = request.getParams(); - EzyUser user = request.getUser(); - EzyZoneContext zoneCtx = ctx.getZoneContext(user.getZoneId()); - EzyPluginContext pluginCtx = getPluginContext(zoneCtx, params); - EzyPlugin plugin = pluginCtx.getPlugin(); - EzyPluginRequestController requestController = plugin.getRequestController(); - EzyUserRequestPluginEvent event = newRequestPluginEvent(request); + @Override + public void handle(EzyServerContext ctx, EzyRequestPluginRequest request) { + EzyRequestPluginParams params = request.getParams(); + EzyUser user = request.getUser(); + EzyZoneContext zoneCtx = ctx.getZoneContext(user.getZoneId()); + EzyPluginContext pluginCtx = getPluginContext(zoneCtx, params); + EzyPlugin plugin = pluginCtx.getPlugin(); + EzyPluginRequestController requestController = plugin.getRequestController(); + EzyUserRequestPluginEvent event = newRequestPluginEvent(request); requestController.handle(pluginCtx, event); - } - - protected EzyPluginContext getPluginContext( + } + + protected EzyPluginContext getPluginContext( EzyZoneContext zoneCtx, EzyRequestPluginParams requestParams) { int pluginId = requestParams.getPluginId(); EzyPluginContext pluginContext = zoneCtx.getPluginContext(pluginId); return pluginContext; } - - protected EzyUserRequestPluginEvent newRequestPluginEvent(EzyRequestPluginRequest request) { - return new EzySimpleUserRequestPluginEvent( - request.getUser(), - request.getSession(), - request.getParams().getData()); - } - + + protected EzyUserRequestPluginEvent newRequestPluginEvent(EzyRequestPluginRequest request) { + return new EzySimpleUserRequestPluginEvent( + request.getUser(), + request.getSession(), + request.getParams().getData()); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyServerController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyServerController.java index b22a73da2..e9d92f391 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyServerController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyServerController.java @@ -3,5 +3,5 @@ import com.tvd12.ezyfoxserver.context.EzyServerContext; public interface EzyServerController - extends EzyController { + extends EzyController { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyZoneController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyZoneController.java index cd96edaa6..b07ea3821 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyZoneController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyZoneController.java @@ -3,5 +3,5 @@ import com.tvd12.ezyfoxserver.context.EzyZoneContext; public interface EzyZoneController - extends EzyController { + extends EzyController { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyAbstractSessionDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyAbstractSessionDelegate.java index a3d942659..fba93513e 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyAbstractSessionDelegate.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyAbstractSessionDelegate.java @@ -7,8 +7,8 @@ public abstract class EzyAbstractSessionDelegate extends EzyLoggable implements EzySessionDelegate { - @Override - public void onSessionLoggedIn(EzyUser user) { - } - + @Override + public void onSessionLoggedIn(EzyUser user) { + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyAbstractSession.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyAbstractSession.java index 14056d77d..8e61acb17 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyAbstractSession.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyAbstractSession.java @@ -47,44 +47,44 @@ public abstract class EzyAbstractSession protected String name; protected String clientId; protected String ownerName; - protected long creationTime; - protected long lastReadTime; - protected long lastWriteTime; - @Setter(AccessLevel.NONE) - protected long readBytes; - @Setter(AccessLevel.NONE) - protected long writtenBytes; - protected long lastActivityTime; - protected long loggedInTime; - protected int readRequests; - protected int writtenResponses; - - protected byte[] privateKey; - protected byte[] publicKey; - protected byte[] clientKey; - protected byte[] sessionKey; - - protected volatile boolean loggedIn; + protected long creationTime; + protected long lastReadTime; + protected long lastWriteTime; + @Setter(AccessLevel.NONE) + protected long readBytes; + @Setter(AccessLevel.NONE) + protected long writtenBytes; + protected long lastActivityTime; + protected long loggedInTime; + protected int readRequests; + protected int writtenResponses; + + protected byte[] privateKey; + protected byte[] publicKey; + protected byte[] clientKey; + protected byte[] sessionKey; + + protected volatile boolean loggedIn; protected volatile boolean activated; protected volatile boolean destroyed; protected volatile boolean streamingEnable; protected String token; - protected String clientType; - protected String clientVersion; - protected String beforeToken; - protected EzyConstant connectionType; - protected EzyConstant disconnectReason; - protected SocketAddress udpClientAddress; - protected DatagramChannel datagramChannel; - protected EzyDatagramChannelPool datagramChannelPool; + protected String clientType; + protected String clientVersion; + protected String beforeToken; + protected EzyConstant connectionType; + protected EzyConstant disconnectReason; + protected SocketAddress udpClientAddress; + protected DatagramChannel datagramChannel; + protected EzyDatagramChannelPool datagramChannelPool; - protected long maxWaitingTime = 5 * 1000; - protected long maxIdleTime = 3 * 60 * 1000; - - protected EzyChannel channel; - protected EzyDroppedPackets droppedPackets; - protected EzyImmediateDeliver immediateDeliver; + protected long maxWaitingTime = 5 * 1000; + protected long maxIdleTime = 3 * 60 * 1000; + + protected EzyChannel channel; + protected EzyDroppedPackets droppedPackets; + protected EzyImmediateDeliver immediateDeliver; protected EzySessionTicketsQueue sessionTicketsQueue; protected EzySocketDisconnectionQueue disconnectionQueue; @@ -92,94 +92,94 @@ public abstract class EzyAbstractSession protected EzyRequestQueue systemRequestQueue; protected EzyRequestQueue extensionRequestQueue; protected EzyRequestFrame requestFrameInSecond; - - protected transient EzySessionDelegate delegate; - - @Setter(AccessLevel.NONE) - protected volatile boolean disconnectionRegistered; - @Setter(AccessLevel.NONE) - protected Object disconnectionLock = new Object(); - @Setter(AccessLevel.NONE) - protected Map locks = new ConcurrentHashMap<>(); - - public void setOwner(EzyUser owner) { - this.ownerName = owner.getName(); - this.delegate.onSessionLoggedIn(owner); - } - - @Override - public void addReadBytes(long bytes) { - this.readBytes += bytes; - } - - @Override - public void addWrittenBytes(long bytes) { - this.writtenBytes += bytes; - } - - @Override - public void addReadRequests(int requests) { - this.readRequests += requests; - } - - @Override - public boolean addReceviedRequests(int requests) { - if(requestFrameInSecond.isExpired()) + + protected transient EzySessionDelegate delegate; + + @Setter(AccessLevel.NONE) + protected volatile boolean disconnectionRegistered; + @Setter(AccessLevel.NONE) + protected Object disconnectionLock = new Object(); + @Setter(AccessLevel.NONE) + protected Map locks = new ConcurrentHashMap<>(); + + public void setOwner(EzyUser owner) { + this.ownerName = owner.getName(); + this.delegate.onSessionLoggedIn(owner); + } + + @Override + public void addReadBytes(long bytes) { + this.readBytes += bytes; + } + + @Override + public void addWrittenBytes(long bytes) { + this.writtenBytes += bytes; + } + + @Override + public void addReadRequests(int requests) { + this.readRequests += requests; + } + + @Override + public boolean addReceviedRequests(int requests) { + if(requestFrameInSecond.isExpired()) requestFrameInSecond = requestFrameInSecond.nextFrame(); return requestFrameInSecond.addRequests(requests); - } - - @Override - public void addWrittenResponses(int responses) { - this.writtenResponses += responses; - } - - @Override - public void setActivated(boolean value) { - this.activated = value; - } - - @Override - public boolean isIdle() { - if(loggedIn) { - long offset = System.currentTimeMillis() - lastReadTime; - boolean idle = maxIdleTime < offset; - return idle; - } - return false; - } - - @Override - public Lock getLock(String name) { - Lock lock = locks.computeIfAbsent(name, EzyFunctions.NEW_REENTRANT_LOCK_FUNC); - return lock; - } - - @Override - public final void send(EzyPacket packet) { - if(activated) { - addWrittenResponses(1); - setLastWriteTime(System.currentTimeMillis()); + } + + @Override + public void addWrittenResponses(int responses) { + this.writtenResponses += responses; + } + + @Override + public void setActivated(boolean value) { + this.activated = value; + } + + @Override + public boolean isIdle() { + if(loggedIn) { + long offset = System.currentTimeMillis() - lastReadTime; + boolean idle = maxIdleTime < offset; + return idle; + } + return false; + } + + @Override + public Lock getLock(String name) { + Lock lock = locks.computeIfAbsent(name, EzyFunctions.NEW_REENTRANT_LOCK_FUNC); + return lock; + } + + @Override + public final void send(EzyPacket packet) { + if(activated) { + addWrittenResponses(1); + setLastWriteTime(System.currentTimeMillis()); setLastActivityTime(System.currentTimeMillis()); addPacketToSessionQueue(packet); - } - } - - @Override - public void sendNow(EzyPacket packet) { + } + } + + @Override + public void sendNow(EzyPacket packet) { immediateDeliver.sendPacketNow(packet); - } - + } + private void addPacketToSessionQueue(EzyPacket packet) { - boolean empty = false; + boolean empty = false; boolean success = false; synchronized (packetQueue) { - empty = packetQueue.isEmpty(); + empty = packetQueue.isEmpty(); success = packetQueue.add(packet); if(success && empty) { - EzySessionTicketsQueue ticketsQueue = this.sessionTicketsQueue; - if(ticketsQueue != null) - sessionTicketsQueue.add(this); + EzySessionTicketsQueue ticketsQueue = this.sessionTicketsQueue; + if(ticketsQueue != null) + sessionTicketsQueue.add(this); } } if(!success) { @@ -197,7 +197,7 @@ public void disconnect(EzyConstant disconnectReason) { this.disconnectReason = disconnectReason; EzySocketDisconnectionQueue queue = this.disconnectionQueue; if(queue != null) - queue.add(newDisconnection(disconnectReason)); + queue.add(newDisconnection(disconnectReason)); this.disconnectionRegistered = true; } } @@ -238,72 +238,72 @@ public String getName() { .append(")") .toString(); } - - @Override - public void destroy() { - this.destroyed = true; - this.activated = false; - this.channel = null; - this.delegate = null; - this.loggedIn = false; - this.readBytes = 0L; - this.writtenBytes = 0L; - this.connectionType = null; - this.disconnectionLock = null; - if(locks != null) - this.locks.clear(); + + @Override + public void destroy() { + this.destroyed = true; + this.activated = false; + this.channel = null; + this.delegate = null; + this.loggedIn = false; + this.readBytes = 0L; + this.writtenBytes = 0L; + this.connectionType = null; + this.disconnectionLock = null; + if(locks != null) + this.locks.clear(); this.properties.clear(); - this.locks = null; - this.droppedPackets = null; - this.immediateDeliver = null; - if(packetQueue != null) { - synchronized (packetQueue) { - this.packetQueue.clear(); - } - } - if(systemRequestQueue != null) { - synchronized (systemRequestQueue) { - systemRequestQueue.clear(); - } - } - if(extensionRequestQueue != null) { - synchronized (extensionRequestQueue) { - extensionRequestQueue.clear(); - } - } - this.sessionTicketsQueue = null; - this.disconnectionQueue = null; - this.udpClientAddress = null; - this.datagramChannel = null; - } - - @Override - public boolean equals(Object obj) { - if(obj == null) - return false; - if(obj == this) - return true; - if(obj instanceof EzyAbstractSession) - return id == ((EzyAbstractSession)obj).id; - return false; - } - - @Override - public int hashCode() { - return Long.hashCode(id); - } - - @Override - public String toString() { - return new StringBuilder() - .append("(") - .append("id: ").append(id) - .append(", type: ").append(clientType) - .append(", version: ").append(clientVersion) - .append(", address: ").append(getClientAddress()) - .append(", token: ").append(token) - .append(")") - .toString(); - } - + this.locks = null; + this.droppedPackets = null; + this.immediateDeliver = null; + if(packetQueue != null) { + synchronized (packetQueue) { + this.packetQueue.clear(); + } + } + if(systemRequestQueue != null) { + synchronized (systemRequestQueue) { + systemRequestQueue.clear(); + } + } + if(extensionRequestQueue != null) { + synchronized (extensionRequestQueue) { + extensionRequestQueue.clear(); + } + } + this.sessionTicketsQueue = null; + this.disconnectionQueue = null; + this.udpClientAddress = null; + this.datagramChannel = null; + } + + @Override + public boolean equals(Object obj) { + if(obj == null) + return false; + if(obj == this) + return true; + if(obj instanceof EzyAbstractSession) + return id == ((EzyAbstractSession)obj).id; + return false; + } + + @Override + public int hashCode() { + return Long.hashCode(id); + } + + @Override + public String toString() { + return new StringBuilder() + .append("(") + .append("id: ").append(id) + .append(", type: ").append(clientType) + .append(", version: ").append(clientVersion) + .append(", address: ").append(getClientAddress()) + .append(", token: ").append(token) + .append(")") + .toString(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyDeliver.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyDeliver.java index 7ba08e532..283105ba2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyDeliver.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyDeliver.java @@ -4,8 +4,8 @@ public interface EzyDeliver { - void send(EzyPacket packet); - - void sendNow(EzyPacket packet); - + void send(EzyPacket packet); + + void sendNow(EzyPacket packet); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySession.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySession.java index 7b320be56..8cbf4f77e 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySession.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySession.java @@ -17,378 +17,378 @@ public interface EzySession extends EzyDeliver, EzyHasName, EzyProperties, EzyDestroyable, Serializable { - /** - * Get session id - * - * @return the session id - */ - long getId(); - - /** - * Get client id - * - * @return the client id - */ - String getClientId(); - - /** - * Set client id - * - * @param id the client id - */ - void setClientId(String id); - - /** - * Get client key to encrypt data send to client - * - * @return the client key - */ - byte[] getClientKey(); - - /** - * - * Set client key - * - * @param key the client key - */ - void setClientKey(byte[] key); - - /** - * - * Set session key - * - * @param key the session key - */ - void setSessionKey(byte[] key); - - - /** - * Get session key to encrypt data send to client - * - * @return the session key - */ - byte[] getSessionKey(); - - - /** - * Get client type - * - * @return the client type - */ - String getClientType(); - - /** - * Set client type - * - * @param type the client type - */ - void setClientType(String type); - - /** - * Get client version - * - * @return the client version - */ - String getClientVersion(); - - /** - * Set client version - * - * @param version the client version - */ - void setClientVersion(String version); - - /** - * Get session connection type - * - * @return the connection type - */ - EzyConstant getConnectionType(); - - /** - * Get session reconnect token - * - * @return the session reconnect token - */ - String getToken(); - - /** - * Get before reconnect token - * - * @return before reconnect token - */ - String getBeforeToken(); - - /** - * Set reconnect token - * - * @param token the reconnect token - */ - void setToken(String token); - - /** - * The private key that decrypt data - * - * @param key the key - */ - void setPrivateKey(byte[] key); - - /** - * Get private key - * - * @return the private key - */ - byte[] getPrivateKey(); - - /** - * Set public key that encrypt data - * - * @param key the public key - */ - void setPublicKey(byte[] key); - - /** - * Get public key - * - * @return the public key - */ - byte[] getPublicKey(); - - /** - * Get creation time in long - * - * @return the creation time - */ - long getCreationTime(); - - /** - * Set creation time - * - * @param time the creation time - */ - void setCreationTime(long time); - - /** - * Get last activity time in long - * - * @return the last activity time - */ - long getLastActivityTime(); - - /** - * Set last activity time - * - * @param time the last activity time - */ - void setLastActivityTime(long time); - - /** - * Get last read time in long - * - * @return the last read time - */ - long getLastReadTime(); - - /** - * Set last read time - * - * @param time the last read time - */ - void setLastReadTime(long time); - - /** - * Get last write time in long - * - * @return the last read time - */ - long getLastWriteTime(); - - /** - * Set last write time - * - * @param time the last read time - */ - void setLastWriteTime(long time); - - /** - * Get read bytes - * - * @return the read bytes - */ - long getReadBytes(); - - /** - * Add read bytes - * - * @param bytes the read bytes - */ - void addReadBytes(long bytes); - - /** - * Get written bytes - * - * @return the written bytes - */ - long getWrittenBytes(); - - /** - * Add written bytes - * - * @param bytes the written bytes - */ - void addWrittenBytes(long bytes); - - /** - * Get read requests - * - * @return the number of read request - */ - int getReadRequests(); - - /** - * add read requests - * - * @param requests number of read requests - */ - void addReadRequests(int requests); - - /** - * add received requests - * - * @param requests number of received requests - * @return max request per second or not - */ - boolean addReceviedRequests(int requests); - - /** - * Get written responses - * - * @return number of written responses - */ - int getWrittenResponses(); - - /** - * add written responses - * - * @param responses number of responses - */ - void addWrittenResponses(int responses); - - /** - * Get max idle time - * - * @return the max idle time - */ - long getMaxIdleTime(); - - /** - * - * @param time the max idle time - */ - void setMaxIdleTime(long time); - - /** - * Set logged in or not - * - * @param value logged in or not - */ - void setLoggedIn(boolean value); - - /** - * @return true of user has logged in - */ - boolean isLoggedIn(); - - /** - * @param time the logged time - */ - void setLoggedInTime(long time); - - /** - * @return the logged in time - */ - long getLoggedInTime(); - - /** - * @param time the max waiting for user login time - */ - void setMaxWaitingTime(long time); - - /** - * - * @return time the max waiting for user login time - */ - long getMaxWaitingTime(); - - /** - * @param activated session is active or not - */ - void setActivated(boolean activated); - - /** - * @return session is active or not - */ - boolean isActivated(); - - /** - * @return session is idle or not - */ - boolean isIdle(); - - /** + /** + * Get session id + * + * @return the session id + */ + long getId(); + + /** + * Get client id + * + * @return the client id + */ + String getClientId(); + + /** + * Set client id + * + * @param id the client id + */ + void setClientId(String id); + + /** + * Get client key to encrypt data send to client + * + * @return the client key + */ + byte[] getClientKey(); + + /** + * + * Set client key + * + * @param key the client key + */ + void setClientKey(byte[] key); + + /** + * + * Set session key + * + * @param key the session key + */ + void setSessionKey(byte[] key); + + + /** + * Get session key to encrypt data send to client + * + * @return the session key + */ + byte[] getSessionKey(); + + + /** + * Get client type + * + * @return the client type + */ + String getClientType(); + + /** + * Set client type + * + * @param type the client type + */ + void setClientType(String type); + + /** + * Get client version + * + * @return the client version + */ + String getClientVersion(); + + /** + * Set client version + * + * @param version the client version + */ + void setClientVersion(String version); + + /** + * Get session connection type + * + * @return the connection type + */ + EzyConstant getConnectionType(); + + /** + * Get session reconnect token + * + * @return the session reconnect token + */ + String getToken(); + + /** + * Get before reconnect token + * + * @return before reconnect token + */ + String getBeforeToken(); + + /** + * Set reconnect token + * + * @param token the reconnect token + */ + void setToken(String token); + + /** + * The private key that decrypt data + * + * @param key the key + */ + void setPrivateKey(byte[] key); + + /** + * Get private key + * + * @return the private key + */ + byte[] getPrivateKey(); + + /** + * Set public key that encrypt data + * + * @param key the public key + */ + void setPublicKey(byte[] key); + + /** + * Get public key + * + * @return the public key + */ + byte[] getPublicKey(); + + /** + * Get creation time in long + * + * @return the creation time + */ + long getCreationTime(); + + /** + * Set creation time + * + * @param time the creation time + */ + void setCreationTime(long time); + + /** + * Get last activity time in long + * + * @return the last activity time + */ + long getLastActivityTime(); + + /** + * Set last activity time + * + * @param time the last activity time + */ + void setLastActivityTime(long time); + + /** + * Get last read time in long + * + * @return the last read time + */ + long getLastReadTime(); + + /** + * Set last read time + * + * @param time the last read time + */ + void setLastReadTime(long time); + + /** + * Get last write time in long + * + * @return the last read time + */ + long getLastWriteTime(); + + /** + * Set last write time + * + * @param time the last read time + */ + void setLastWriteTime(long time); + + /** + * Get read bytes + * + * @return the read bytes + */ + long getReadBytes(); + + /** + * Add read bytes + * + * @param bytes the read bytes + */ + void addReadBytes(long bytes); + + /** + * Get written bytes + * + * @return the written bytes + */ + long getWrittenBytes(); + + /** + * Add written bytes + * + * @param bytes the written bytes + */ + void addWrittenBytes(long bytes); + + /** + * Get read requests + * + * @return the number of read request + */ + int getReadRequests(); + + /** + * add read requests + * + * @param requests number of read requests + */ + void addReadRequests(int requests); + + /** + * add received requests + * + * @param requests number of received requests + * @return max request per second or not + */ + boolean addReceviedRequests(int requests); + + /** + * Get written responses + * + * @return number of written responses + */ + int getWrittenResponses(); + + /** + * add written responses + * + * @param responses number of responses + */ + void addWrittenResponses(int responses); + + /** + * Get max idle time + * + * @return the max idle time + */ + long getMaxIdleTime(); + + /** + * + * @param time the max idle time + */ + void setMaxIdleTime(long time); + + /** + * Set logged in or not + * + * @param value logged in or not + */ + void setLoggedIn(boolean value); + + /** + * @return true of user has logged in + */ + boolean isLoggedIn(); + + /** + * @param time the logged time + */ + void setLoggedInTime(long time); + + /** + * @return the logged in time + */ + long getLoggedInTime(); + + /** + * @param time the max waiting for user login time + */ + void setMaxWaitingTime(long time); + + /** + * + * @return time the max waiting for user login time + */ + long getMaxWaitingTime(); + + /** + * @param activated session is active or not + */ + void setActivated(boolean activated); + + /** + * @return session is active or not + */ + boolean isActivated(); + + /** + * @return session is idle or not + */ + boolean isIdle(); + + /** * @return destroyed or not */ boolean isDestroyed(); - - /** - * @return streaming enable or not - */ - boolean isStreamingEnable(); - - /** - * @return the owner name - */ - String getOwnerName(); - - /** - * @return the disconnect reason - */ - EzyConstant getDisconnectReason(); - - /** - * - * @param name the lock name - * @return the lock - */ - Lock getLock(String name); - - /** - * Get client full ip address - * - * @return the client full ip address - */ - SocketAddress getClientAddress(); - - /** - * Get server full ip address - * - * @return the server full ip address - */ - SocketAddress getServerAddress(); - - /** - * close this session - */ - void close(); - - /** - * disconnect this session - * - * @param reason the reason - */ - void disconnect(EzyConstant reason); - - /** + + /** + * @return streaming enable or not + */ + boolean isStreamingEnable(); + + /** + * @return the owner name + */ + String getOwnerName(); + + /** + * @return the disconnect reason + */ + EzyConstant getDisconnectReason(); + + /** + * + * @param name the lock name + * @return the lock + */ + Lock getLock(String name); + + /** + * Get client full ip address + * + * @return the client full ip address + */ + SocketAddress getClientAddress(); + + /** + * Get server full ip address + * + * @return the server full ip address + */ + SocketAddress getServerAddress(); + + /** + * close this session + */ + void close(); + + /** + * disconnect this session + * + * @param reason the reason + */ + void disconnect(EzyConstant reason); + + /** * Get the channel mapped to this session * * @return the channel @@ -409,8 +409,8 @@ public interface EzySession extends EzyDeliver, EzyHasName, EzyProperties, EzyDe * @return the connection */ T getConnection(); - - /** + + /** * Get packet queue * * @return the packet queue @@ -458,5 +458,5 @@ public interface EzySession extends EzyDeliver, EzyHasName, EzyProperties, EzyDe default void disconnect() { disconnect(EzyDisconnectReason.UNKNOWN); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySimpleUser.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySimpleUser.java index e1bc9ac7f..221df893f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySimpleUser.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySimpleUser.java @@ -24,132 +24,132 @@ public class EzySimpleUser extends EzyEntity implements EzyUser, EzyNameAware, EzyZoneIdAware, Serializable { - private static final long serialVersionUID = -7846882289922504595L; - - protected long id = COUNTER.incrementAndGet(); - protected String name = ""; - protected String password = ""; - protected int zoneId = 0; - protected int maxSessions = 30; - protected long maxIdleTime = 3 * 60 * 1000; - protected long startIdleTime = System.currentTimeMillis(); - protected volatile boolean destroyed = false; - @Setter(AccessLevel.NONE) + private static final long serialVersionUID = -7846882289922504595L; + + protected long id = COUNTER.incrementAndGet(); + protected String name = ""; + protected String password = ""; + protected int zoneId = 0; + protected int maxSessions = 30; + protected long maxIdleTime = 3 * 60 * 1000; + protected long startIdleTime = System.currentTimeMillis(); + protected volatile boolean destroyed = false; + @Setter(AccessLevel.NONE) protected Map locks = new ConcurrentHashMap<>(); - @Setter(AccessLevel.NONE) - protected Map sessionMap = new ConcurrentHashMap<>(); - - private transient static final AtomicLong COUNTER = new AtomicLong(0); - - @Override - public void addSession(EzySession session) { - sessionMap.put(session.getId(), session); - } - - @Override - public void removeSession(EzySession session) { - startIdleTime = System.currentTimeMillis(); - sessionMap.remove(session.getId()); - } - - @Override - public List changeSession(EzySession session) { - Map newSessionMap = new ConcurrentHashMap<>(); - newSessionMap.put(session.getId(), session); - Map oldSessionMap = sessionMap; - this.sessionMap = newSessionMap; - List answer = new ArrayList<>(oldSessionMap.values()); - oldSessionMap.clear(); - return answer; - } - - @Override - public EzySession getSession() { - List sessions = getSessions(); - EzySession session = sessions.isEmpty() ? null : sessions.get(0); - return session; - } - - @Override - public List getSessions() { - List sessions = new ArrayList<>(); - Map sessionMapNow = sessionMap; - if(sessionMapNow != null) - sessions.addAll(sessionMapNow.values()); - return sessions; - } - - @Override - public int getSessionCount() { - int size = sessionMap.size(); - return size; - } - - @Override + @Setter(AccessLevel.NONE) + protected Map sessionMap = new ConcurrentHashMap<>(); + + private transient static final AtomicLong COUNTER = new AtomicLong(0); + + @Override + public void addSession(EzySession session) { + sessionMap.put(session.getId(), session); + } + + @Override + public void removeSession(EzySession session) { + startIdleTime = System.currentTimeMillis(); + sessionMap.remove(session.getId()); + } + + @Override + public List changeSession(EzySession session) { + Map newSessionMap = new ConcurrentHashMap<>(); + newSessionMap.put(session.getId(), session); + Map oldSessionMap = sessionMap; + this.sessionMap = newSessionMap; + List answer = new ArrayList<>(oldSessionMap.values()); + oldSessionMap.clear(); + return answer; + } + + @Override + public EzySession getSession() { + List sessions = getSessions(); + EzySession session = sessions.isEmpty() ? null : sessions.get(0); + return session; + } + + @Override + public List getSessions() { + List sessions = new ArrayList<>(); + Map sessionMapNow = sessionMap; + if(sessionMapNow != null) + sessions.addAll(sessionMapNow.values()); + return sessions; + } + + @Override + public int getSessionCount() { + int size = sessionMap.size(); + return size; + } + + @Override public Lock getLock(String name) { Lock lock = locks.computeIfAbsent(name, EzyFunctions.NEW_REENTRANT_LOCK_FUNC); return lock; } - - @Override - public void send(EzyPacket packet) { - for(EzySession session : getSessions()) - session.send(packet); - } - - @Override - public void sendNow(EzyPacket packet) { - for(EzySession session : getSessions()) + + @Override + public void send(EzyPacket packet) { + for(EzySession session : getSessions()) + session.send(packet); + } + + @Override + public void sendNow(EzyPacket packet) { + for(EzySession session : getSessions()) session.sendNow(packet); - } - - @Override - public boolean isIdle() { - if(sessionMap.isEmpty()) { - long offset = System.currentTimeMillis() - startIdleTime; - boolean idle = maxIdleTime < offset; - return idle; - } - return false; - } - - @Override - public void disconnect(EzyConstant reason) { - for(EzySession session : getSessions()) - session.disconnect(reason); - } - - @Override - public void destroy() { - this.destroyed = true; - if(locks != null) - locks.clear(); - if(sessionMap != null) - this.sessionMap.clear(); - this.properties.clear(); - this.locks = null; - this.sessionMap = null; - } - - @Override - public boolean equals(Object obj) { - if(obj == null) - return false; - if(obj == this) - return true; - if(obj instanceof EzySimpleUser) - return id == ((EzySimpleUser)obj).id; - return false; - } - - @Override - public int hashCode() { - return Long.hashCode(id); - } + } + + @Override + public boolean isIdle() { + if(sessionMap.isEmpty()) { + long offset = System.currentTimeMillis() - startIdleTime; + boolean idle = maxIdleTime < offset; + return idle; + } + return false; + } + + @Override + public void disconnect(EzyConstant reason) { + for(EzySession session : getSessions()) + session.disconnect(reason); + } + + @Override + public void destroy() { + this.destroyed = true; + if(locks != null) + locks.clear(); + if(sessionMap != null) + this.sessionMap.clear(); + this.properties.clear(); + this.locks = null; + this.sessionMap = null; + } + + @Override + public boolean equals(Object obj) { + if(obj == null) + return false; + if(obj == this) + return true; + if(obj instanceof EzySimpleUser) + return id == ((EzySimpleUser)obj).id; + return false; + } + + @Override + public int hashCode() { + return Long.hashCode(id); + } @Override public String toString() { return name; } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyUser.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyUser.java index 90fc191e6..2e0063c44 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyUser.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyUser.java @@ -11,49 +11,49 @@ public interface EzyUser extends EzyDeliver, EzyHasName, EzyProperties, EzyDestroyable { - /** - * Get user id - * - * @return the user id - */ - long getId(); - - /** - * Get zone id - * - * @return the zone id - */ - int getZoneId(); - - /** - * Get max session - * - * @return the max session - */ - int getMaxSessions(); - - /** - * Get max idle time - * - * @return the max idle time - */ - long getMaxIdleTime(); - - /** - * Get start idle time - * - * @return the start idle time - */ - long getStartIdleTime(); - - /** - * Set start idle time - * - * @param time the start idle time - */ - void setStartIdleTime(long time); - - /** + /** + * Get user id + * + * @return the user id + */ + long getId(); + + /** + * Get zone id + * + * @return the zone id + */ + int getZoneId(); + + /** + * Get max session + * + * @return the max session + */ + int getMaxSessions(); + + /** + * Get max idle time + * + * @return the max idle time + */ + long getMaxIdleTime(); + + /** + * Get start idle time + * + * @return the start idle time + */ + long getStartIdleTime(); + + /** + * Set start idle time + * + * @param time the start idle time + */ + void setStartIdleTime(long time); + + /** * Get the session count * * @return the session count @@ -66,22 +66,22 @@ public interface EzyUser extends EzyDeliver, EzyHasName, EzyProperties, EzyDestr * @return the first session */ EzySession getSession(); - - /** - * Get current session - * - * @return the current session - */ - List getSessions(); - - /** - * Add new session - * - * @param session the session to add - */ - void addSession(EzySession session); - - /** + + /** + * Get current session + * + * @return the current session + */ + List getSessions(); + + /** + * Add new session + * + * @param session the session to add + */ + void addSession(EzySession session); + + /** * remove a session * * @param session the session to remove @@ -106,24 +106,24 @@ public interface EzyUser extends EzyDeliver, EzyHasName, EzyProperties, EzyDestr */ boolean isDestroyed(); - /** - * @param name the lock name - * @return the lock - */ - Lock getLock(String name); - - /** - * disconnect - * - * @param reason the reason - */ - void disconnect(EzyConstant reason); - - /** + /** + * @param name the lock name + * @return the lock + */ + Lock getLock(String name); + + /** + * disconnect + * + * @param reason the reason + */ + void disconnect(EzyConstant reason); + + /** * disconnect */ default void disconnect() { disconnect(EzyDisconnectReason.UNKNOWN); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyHandshakeEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyHandshakeEvent.java index fbbf67efd..e5c7257e9 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyHandshakeEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyHandshakeEvent.java @@ -2,23 +2,23 @@ public interface EzyHandshakeEvent extends EzySessionEvent { - String getClientId(); + String getClientId(); - byte[] getClientKey(); + byte[] getClientKey(); - String getClientType(); + String getClientType(); - String getClientVersion(); - - String getReconnectToken(); + String getClientVersion(); + + String getReconnectToken(); - boolean isEnableEncryption(); - - byte[] getSessionKey(); - - void setSessionKey(byte[] sessionKey); - - void setEncryptedSessionKey(byte[] sessionKey); - - byte[] getEncryptedSessionKey(); + boolean isEnableEncryption(); + + byte[] getSessionKey(); + + void setSessionKey(byte[] sessionKey); + + void setEncryptedSessionKey(byte[] sessionKey); + + byte[] getEncryptedSessionKey(); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleHandshakeEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleHandshakeEvent.java index c6143c3cb..b3cef45fc 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleHandshakeEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleHandshakeEvent.java @@ -7,41 +7,41 @@ @Getter public class EzySimpleHandshakeEvent - extends EzySimpleSessionEvent - implements EzyHandshakeEvent { + extends EzySimpleSessionEvent + implements EzyHandshakeEvent { - protected final String clientId; - protected final byte[] clientKey; - protected final String clientType; - protected final String clientVersion; - protected final String reconnectToken; - protected final boolean enableEncryption; - @Setter - protected byte[] sessionKey; - @Setter - protected byte[] encryptedSessionKey; - - public EzySimpleHandshakeEvent( - EzySession session, - String clientId, - byte[] clientKey, - String clientType, - String clientVersion, - String reconnectToken, - boolean enableEncryption - ) { - super(session); - this.clientId = clientId; - this.clientKey = clientKey; - this.clientType = clientType; - this.clientVersion = clientVersion; - this.reconnectToken = reconnectToken; - this.enableEncryption = enableEncryption; - } - - @Override - public void release() { - this.sessionKey = null; - this.encryptedSessionKey = null; - } + protected final String clientId; + protected final byte[] clientKey; + protected final String clientType; + protected final String clientVersion; + protected final String reconnectToken; + protected final boolean enableEncryption; + @Setter + protected byte[] sessionKey; + @Setter + protected byte[] encryptedSessionKey; + + public EzySimpleHandshakeEvent( + EzySession session, + String clientId, + byte[] clientKey, + String clientType, + String clientVersion, + String reconnectToken, + boolean enableEncryption + ) { + super(session); + this.clientId = clientId; + this.clientKey = clientKey; + this.clientType = clientType; + this.clientVersion = clientVersion; + this.reconnectToken = reconnectToken; + this.enableEncryption = enableEncryption; + } + + @Override + public void release() { + this.sessionKey = null; + this.encryptedSessionKey = null; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleSessionRemovedEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleSessionRemovedEvent.java index 7cfcc4c6b..7d6ae8efb 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleSessionRemovedEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleSessionRemovedEvent.java @@ -8,8 +8,8 @@ @Getter public class EzySimpleSessionRemovedEvent - extends EzySimpleUserSessionEvent - implements EzySessionRemovedEvent { + extends EzySimpleUserSessionEvent + implements EzySessionRemovedEvent { protected final EzyConstant reason; @@ -18,5 +18,5 @@ public EzySimpleSessionRemovedEvent( super(user, session); this.reason = reason; } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAccessAppEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAccessAppEvent.java index f2d1b2647..688b20ba8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAccessAppEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAccessAppEvent.java @@ -8,8 +8,8 @@ @Getter public class EzySimpleUserAccessAppEvent - extends EzySimpleUserEvent - implements EzyUserAccessAppEvent { + extends EzySimpleUserEvent + implements EzyUserAccessAppEvent { protected final EzyArray output; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAddedEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAddedEvent.java index ab933d2d9..9ce30d35c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAddedEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserAddedEvent.java @@ -8,8 +8,8 @@ @Getter public class EzySimpleUserAddedEvent - extends EzySimpleUserSessionEvent - implements EzyUserAddedEvent { + extends EzySimpleUserSessionEvent + implements EzyUserAddedEvent { protected final EzyData loginData; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserLoginEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserLoginEvent.java index 497e01a87..4522ece84 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserLoginEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserLoginEvent.java @@ -14,58 +14,58 @@ public class EzySimpleUserLoginEvent extends EzySimpleSessionEvent implements EzyUserLoginEvent { - protected final EzyData data; - protected final String zoneName; - @Setter - protected String username; - @Setter - protected String password; - @Setter - protected EzyData output; - @Setter - protected boolean streamingEnable; - - protected Map userProperties; - - public EzySimpleUserLoginEvent( - EzySession session, - String zoneName, - String username, String password, EzyData data) { - super(session); - this.zoneName = zoneName; - this.data = data; - this.username = username; - this.password = password; - this.streamingEnable = true; - this.userProperties = new HashMap<>(); - } - - public String getUsername() { - return username == null ? "" : username; - } - - public String getPassword() { - return password == null ? "" : password; - } - - @Override - public void setUserProperty(Object key, Object value) { - this.userProperties.put(key, value); - } - - @Override - public void setUserProperties(Map properties) { - this.userProperties.putAll(properties); - } - - @Override - public void release() { - super.release(); - this.username = null; - this.password = null; - this.output = null; - this.userProperties.clear(); - this.userProperties = null; - } - + protected final EzyData data; + protected final String zoneName; + @Setter + protected String username; + @Setter + protected String password; + @Setter + protected EzyData output; + @Setter + protected boolean streamingEnable; + + protected Map userProperties; + + public EzySimpleUserLoginEvent( + EzySession session, + String zoneName, + String username, String password, EzyData data) { + super(session); + this.zoneName = zoneName; + this.data = data; + this.username = username; + this.password = password; + this.streamingEnable = true; + this.userProperties = new HashMap<>(); + } + + public String getUsername() { + return username == null ? "" : username; + } + + public String getPassword() { + return password == null ? "" : password; + } + + @Override + public void setUserProperty(Object key, Object value) { + this.userProperties.put(key, value); + } + + @Override + public void setUserProperties(Map properties) { + this.userProperties.putAll(properties); + } + + @Override + public void release() { + super.release(); + this.username = null; + this.password = null; + this.output = null; + this.userProperties.clear(); + this.userProperties = null; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRemovedEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRemovedEvent.java index 11eb72e97..d1c403ed8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRemovedEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRemovedEvent.java @@ -7,12 +7,12 @@ @Getter public class EzySimpleUserRemovedEvent - extends EzySimpleUserEvent - implements EzyUserRemovedEvent { + extends EzySimpleUserEvent + implements EzyUserRemovedEvent { protected final EzyConstant reason; - public EzySimpleUserRemovedEvent(EzyUser user, EzyConstant reason) { + public EzySimpleUserRemovedEvent(EzyUser user, EzyConstant reason) { super(user); this.reason = reason; } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestAppEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestAppEvent.java index e5b19ed62..4c72e9faa 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestAppEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestAppEvent.java @@ -8,10 +8,10 @@ @Getter public class EzySimpleUserRequestAppEvent - extends EzySimpleUserRequestEvent - implements EzyUserRequestAppEvent { + extends EzySimpleUserRequestEvent + implements EzyUserRequestAppEvent { - public EzySimpleUserRequestAppEvent(EzyUser user, EzySession session, EzyArray data) { + public EzySimpleUserRequestAppEvent(EzyUser user, EzySession session, EzyArray data) { super(user, session, data); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestEvent.java index 985aa8f4e..c6b44b155 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestEvent.java @@ -8,12 +8,12 @@ @Getter public class EzySimpleUserRequestEvent - extends EzySimpleUserSessionEvent - implements EzyUserRequestAppEvent { + extends EzySimpleUserSessionEvent + implements EzyUserRequestAppEvent { protected final EzyArray data; - public EzySimpleUserRequestEvent(EzyUser user, EzySession session, EzyArray data) { + public EzySimpleUserRequestEvent(EzyUser user, EzySession session, EzyArray data) { super(user, session); this.data = data; } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestPluginEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestPluginEvent.java index 11bd441af..65981f3c1 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestPluginEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySimpleUserRequestPluginEvent.java @@ -8,13 +8,13 @@ @Getter public class EzySimpleUserRequestPluginEvent - extends EzySimpleUserRequestEvent - implements EzyUserRequestPluginEvent { + extends EzySimpleUserRequestEvent + implements EzyUserRequestPluginEvent { - public EzySimpleUserRequestPluginEvent( - EzyUser user, - EzySession session, EzyArray data) { + public EzySimpleUserRequestPluginEvent( + EzyUser user, + EzySession session, EzyArray data) { super(user, session, data); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserLoginEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserLoginEvent.java index 6f627590c..b1cb42cdd 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserLoginEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserLoginEvent.java @@ -8,28 +8,28 @@ public interface EzyUserLoginEvent extends EzySessionEvent { String getZoneName(); - EzyData getOutput(); - - String getUsername(); - - String getPassword(); - - T getData(); - - Map getUserProperties(); - - boolean isStreamingEnable(); - - void setOutput(EzyData output); - - void setUsername(String username); - - void setPassword(String password); - - void setStreamingEnable(boolean enable); - - void setUserProperty(Object key, Object value); - - void setUserProperties(Map properties); - + EzyData getOutput(); + + String getUsername(); + + String getPassword(); + + T getData(); + + Map getUserProperties(); + + boolean isStreamingEnable(); + + void setOutput(EzyData output); + + void setUsername(String username); + + void setPassword(String password); + + void setStreamingEnable(boolean enable); + + void setUserProperty(Object key, Object value); + + void setUserProperties(Map properties); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRemovedEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRemovedEvent.java index efeb08b69..ed781a645 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRemovedEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRemovedEvent.java @@ -5,5 +5,5 @@ public interface EzyUserRemovedEvent extends EzyUserEvent { EzyConstant getReason(); - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestEvent.java index 73535269c..9a3c18f06 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestEvent.java @@ -3,7 +3,7 @@ import com.tvd12.ezyfox.entity.EzyArray; public interface EzyUserRequestEvent extends EzyUserSessionEvent { - - EzyArray getData(); - + + EzyArray getData(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyNotAuthorizedException.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyNotAuthorizedException.java index a7714922d..d1d1cee4e 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyNotAuthorizedException.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyNotAuthorizedException.java @@ -1,10 +1,10 @@ package com.tvd12.ezyfoxserver.exception; public class EzyNotAuthorizedException extends Exception { - private static final long serialVersionUID = 8292545377354181644L; - - public EzyNotAuthorizedException(String msg) { - super(msg); - } + private static final long serialVersionUID = 8292545377354181644L; + + public EzyNotAuthorizedException(String msg) { + super(msg); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyResponseHandleException.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyResponseHandleException.java index 56111d0a0..5e2bacaeb 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyResponseHandleException.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyResponseHandleException.java @@ -1,10 +1,10 @@ package com.tvd12.ezyfoxserver.exception; public class EzyResponseHandleException extends IllegalStateException { - private static final long serialVersionUID = 6288790755559864267L; - - public EzyResponseHandleException(String msg, Throwable e) { - super(msg, e); - } + private static final long serialVersionUID = 6288790755559864267L; + + public EzyResponseHandleException(String msg, Throwable e) { + super(msg, e); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractAppEntry.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractAppEntry.java index cbcc9f7a4..1ad79af97 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractAppEntry.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractAppEntry.java @@ -8,6 +8,6 @@ * */ public abstract class EzyAbstractAppEntry - extends EzyAbstractEntry - implements EzyAppEntry { + extends EzyAbstractEntry + implements EzyAppEntry { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractPluginEntry.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractPluginEntry.java index b0ff356ee..616e8737d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractPluginEntry.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAbstractPluginEntry.java @@ -8,6 +8,6 @@ * */ public abstract class EzyAbstractPluginEntry - extends EzyAbstractEntry - implements EzyPluginEntry { + extends EzyAbstractEntry + implements EzyPluginEntry { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntry.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntry.java index 7e561888b..5fe865856 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntry.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntry.java @@ -11,6 +11,6 @@ */ public interface EzyAppEntry extends EzyEntry { - default void config(EzyAppContext ctx) {} - + default void config(EzyAppContext ctx) {} + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntryLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntryLoader.java index 632d1eb4c..c432deec8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntryLoader.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyAppEntryLoader.java @@ -2,6 +2,6 @@ public interface EzyAppEntryLoader { - EzyAppEntry load() throws Exception; - + EzyAppEntry load() throws Exception; + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntry.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntry.java index 80c232fdc..67494f09d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntry.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntry.java @@ -4,7 +4,7 @@ import com.tvd12.ezyfoxserver.context.EzyPluginContext; public interface EzyPluginEntry extends EzyEntry, EzyDestroyable { - - default void config(EzyPluginContext ctx) {} - + + default void config(EzyPluginContext ctx) {} + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntryLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntryLoader.java index 66976c45b..3ece2be28 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntryLoader.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyPluginEntryLoader.java @@ -2,6 +2,6 @@ public interface EzyPluginEntryLoader{ - EzyPluginEntry load() throws Exception; - + EzyPluginEntry load() throws Exception; + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzyAbstractSessionFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzyAbstractSessionFactory.java index 4e922c243..a76114c16 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzyAbstractSessionFactory.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzyAbstractSessionFactory.java @@ -12,28 +12,28 @@ import lombok.Setter; public abstract class EzyAbstractSessionFactory - implements EzySessionFactory { - - @Setter - protected EzyMaxRequestPerSecond maxRequestPerSecond; - protected final AtomicInteger counter = new AtomicInteger(0); - - @Override - public final S newProduct() { - S session = newSession(); - initSession((EzyAbstractSession)session); - return session; - } - - protected void initSession(EzyAbstractSession session) { - session.setId(counter.incrementAndGet()); - session.setCreationTime(System.currentTimeMillis()); - session.setPacketQueue(new EzyNonBlockingPacketQueue()); - session.setSystemRequestQueue(new EzyNonBlockingRequestQueue()); - session.setExtensionRequestQueue(new EzyNonBlockingRequestQueue()); - session.setRequestFrameInSecond(new EzyRequestFrameSecond(maxRequestPerSecond.getValue())); - } - - protected abstract S newSession(); - + implements EzySessionFactory { + + @Setter + protected EzyMaxRequestPerSecond maxRequestPerSecond; + protected final AtomicInteger counter = new AtomicInteger(0); + + @Override + public final S newProduct() { + S session = newSession(); + initSession((EzyAbstractSession)session); + return session; + } + + protected void initSession(EzyAbstractSession session) { + session.setId(counter.incrementAndGet()); + session.setCreationTime(System.currentTimeMillis()); + session.setPacketQueue(new EzyNonBlockingPacketQueue()); + session.setSystemRequestQueue(new EzyNonBlockingRequestQueue()); + session.setExtensionRequestQueue(new EzyNonBlockingRequestQueue()); + session.setRequestFrameInSecond(new EzyRequestFrameSecond(maxRequestPerSecond.getValue())); + } + + protected abstract S newSession(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzySessionFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzySessionFactory.java index ff40ca6c9..619f15338 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzySessionFactory.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/factory/EzySessionFactory.java @@ -4,5 +4,5 @@ import com.tvd12.ezyfoxserver.entity.EzySession; public interface EzySessionFactory - extends EzyObjectFactory { + extends EzyObjectFactory { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesReceived.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesReceived.java index bae82cd73..87569edbe 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesReceived.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesReceived.java @@ -2,6 +2,6 @@ public interface EzyBytesReceived { - void bytesReceived(int bytes); - + void bytesReceived(int bytes); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesSent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesSent.java index b0a015281..98ab68ae3 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesSent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyBytesSent.java @@ -2,6 +2,6 @@ public interface EzyBytesSent { - void bytesSent(int bytes); - + void bytesSent(int bytes); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySimpleRequestFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySimpleRequestFactory.java index 14735fef9..835e22768 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySimpleRequestFactory.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySimpleRequestFactory.java @@ -42,4 +42,4 @@ protected Map> newSuppliers() { answer.put(EzyCommand.PLUGIN_REQUEST, () -> new EzySimpleRequestPluginRequest()); return answer; } -} \ No newline at end of file +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserDataHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserDataHandler.java index d6d828968..dad2f4bc5 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserDataHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserDataHandler.java @@ -45,4 +45,4 @@ protected EzyStreamingRequest newStreamingRequest(byte[] bytes) { return request; } -} \ No newline at end of file +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyAbstractServerInterceptor.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyAbstractServerInterceptor.java index a5ec10c41..0b10de3cb 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyAbstractServerInterceptor.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyAbstractServerInterceptor.java @@ -3,7 +3,7 @@ import com.tvd12.ezyfox.util.EzyLoggable; public abstract class EzyAbstractServerInterceptor - extends EzyLoggable - implements EzyServerInterceptor { + extends EzyLoggable + implements EzyServerInterceptor { } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyInterceptor.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyInterceptor.java index 078c28b7c..80ecff923 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyInterceptor.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyInterceptor.java @@ -6,10 +6,10 @@ * */ public interface EzyInterceptor { - - @SuppressWarnings("rawtypes") - EzyInterceptor ALWAYS_PASS = (ctx, request) -> {}; - - void intercept(C ctx, R request) throws Exception; - -} \ No newline at end of file + + @SuppressWarnings("rawtypes") + EzyInterceptor ALWAYS_PASS = (ctx, request) -> {}; + + void intercept(C ctx, R request) throws Exception; + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyRawBytesInterceptor.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyRawBytesInterceptor.java index 1af933549..9f9b6859a 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyRawBytesInterceptor.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyRawBytesInterceptor.java @@ -6,10 +6,10 @@ public class EzyRawBytesInterceptor extends EzyAbstractServerInterceptor { - @Override - public void intercept(EzyServerContext ctx, EzyStreamingRequest request) throws Exception { - if(request.getUser() == null) - throw new EzyNotAuthorizedException("user has not logged in"); - } - + @Override + public void intercept(EzyServerContext ctx, EzyStreamingRequest request) throws Exception { + if(request.getUser() == null) + throw new EzyNotAuthorizedException("user has not logged in"); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerUserInterceptor.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerUserInterceptor.java index 6b6eb3bf4..4014cfe52 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerUserInterceptor.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerUserInterceptor.java @@ -7,10 +7,10 @@ @SuppressWarnings("rawtypes") public class EzyServerUserInterceptor extends EzyAbstractServerInterceptor { - @Override - public void intercept(EzyServerContext ctx, EzyUserRequest request) throws Exception { - if(request.getUser() == null) - throw new EzyNotAuthorizedException("user has not logged in"); - } - + @Override + public void intercept(EzyServerContext ctx, EzyUserRequest request) throws Exception { + if(request.getUser() == null) + throw new EzyNotAuthorizedException("user has not logged in"); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppParams.java index 4e793fe95..5ff9be6a8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppParams.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppParams.java @@ -13,21 +13,21 @@ public class EzyAccessAppParams extends EzySimpleResponseParams { private static final long serialVersionUID = -2355811939162393678L; protected EzyData data; - protected EzyAppSetting app; - - @Override - protected EzyArrayBuilder serialize0() { - return newArrayBuilder() + protected EzyAppSetting app; + + @Override + protected EzyArrayBuilder serialize0() { + return newArrayBuilder() .append(app.getId()) .append(app.getName()) .append(data); - } - - @Override - public void release() { - super.release(); - this.data = null; - this.app = null; - } + } + + @Override + public void release() { + super.release(); + this.data = null; + this.app = null; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppResponse.java index 881ed32cd..8161b1cf0 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAccessAppResponse.java @@ -6,8 +6,8 @@ public class EzyAccessAppResponse extends EzySimpleParamsResponse { private static final long serialVersionUID = 1179311642566987837L; - public EzyAccessAppResponse(EzyAccessAppParams params) { - super(EzyCommand.APP_ACCESS, params); - } + public EzyAccessAppResponse(EzyAccessAppParams params) { + super(EzyCommand.APP_ACCESS, params); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectParams.java index eb090adba..672052521 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectParams.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectParams.java @@ -18,5 +18,5 @@ protected EzyArrayBuilder serialize0() { return newArrayBuilder() .append(reason.getId()); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectResponse.java index 93b13682b..7e73e44be 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyDisconnectResponse.java @@ -7,7 +7,7 @@ public class EzyDisconnectResponse private static final long serialVersionUID = -5720385557675923841L; public EzyDisconnectResponse(EzyDisconnectParams params) { - super(EzyCommand.DISCONNECT, params); - } - + super(EzyCommand.DISCONNECT, params); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyErrorResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyErrorResponse.java index 3470d0876..2aae92ca0 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyErrorResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyErrorResponse.java @@ -5,9 +5,9 @@ public class EzyErrorResponse extends EzySimpleParamsResponse { private static final long serialVersionUID = -657770402301316673L; - + public EzyErrorResponse(EzyErrorParams params) { - super(EzyCommand.ERROR, params); - } + super(EzyCommand.ERROR, params); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppParams.java index 2d5722dcc..ccdf4a244 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppParams.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppParams.java @@ -12,21 +12,21 @@ public class EzyExitedAppParams extends EzySimpleResponseParams { private static final long serialVersionUID = -2355811939162393678L; - protected EzyAppSetting app; - protected EzyConstant reason; - - @Override - protected EzyArrayBuilder serialize0() { - return newArrayBuilder() + protected EzyAppSetting app; + protected EzyConstant reason; + + @Override + protected EzyArrayBuilder serialize0() { + return newArrayBuilder() .append(app.getId()) .append(reason.getId()); - } - - @Override - public void release() { - super.release(); - this.app = null; - this.reason = null; - } + } + + @Override + public void release() { + super.release(); + this.app = null; + this.reason = null; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppResponse.java index 7eaf4ed1c..15f548c88 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyExitedAppResponse.java @@ -6,8 +6,8 @@ public class EzyExitedAppResponse extends EzySimpleParamsResponse { private static final long serialVersionUID = 1179311642566987837L; - public EzyExitedAppResponse(EzyExitedAppParams params) { - super(EzyCommand.APP_EXIT, params); - } + public EzyExitedAppResponse(EzyExitedAppParams params) { + super(EzyCommand.APP_EXIT, params); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeParams.java index 1549710bd..a367b0f61 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeParams.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeParams.java @@ -14,13 +14,13 @@ public class EzyHandShakeParams extends EzySimpleResponseParams { protected String reconnectToken; protected long sessionId; protected byte[] sessionKey; - - @Override - protected EzyArrayBuilder serialize0() { - return newArrayBuilder() + + @Override + protected EzyArrayBuilder serialize0() { + return newArrayBuilder() .append(serverPublicKey) .append(reconnectToken) .append(sessionId) .append(sessionKey); - } + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeResponse.java index 0e22daab0..134b50ca9 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyHandShakeResponse.java @@ -7,7 +7,7 @@ public class EzyHandShakeResponse private static final long serialVersionUID = -464917427945070426L; public EzyHandShakeResponse(EzyHandShakeParams params) { - super(EzyCommand.HANDSHAKE, params); - } - + super(EzyCommand.HANDSHAKE, params); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginParams.java index ce59032bc..28c7b9f9c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginParams.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginParams.java @@ -13,23 +13,23 @@ public class EzyLoginParams extends EzySimpleResponseParams { protected int zoneId; protected String zoneName; protected long userId; - protected Object data; - protected String username; - - @Override - protected EzyArrayBuilder serialize0() { - return newArrayBuilder() - .append(zoneId) - .append(zoneName) + protected Object data; + protected String username; + + @Override + protected EzyArrayBuilder serialize0() { + return newArrayBuilder() + .append(zoneId) + .append(zoneName) .append(userId) .append(username) .append(data); - } - - @Override - public void release() { - super.release(); - this.data = null; - } + } + + @Override + public void release() { + super.release(); + this.data = null; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginResponse.java index 6d288dde3..9b81c104e 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginResponse.java @@ -7,7 +7,7 @@ public class EzyLoginResponse private static final long serialVersionUID = -6999045776866818316L; public EzyLoginResponse(EzyLoginParams params) { - super(EzyCommand.LOGIN, params); - } - + super(EzyCommand.LOGIN, params); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyPluginInfoResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyPluginInfoResponse.java index a50abad27..24e710c5d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyPluginInfoResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyPluginInfoResponse.java @@ -9,5 +9,5 @@ public class EzyPluginInfoResponse public EzyPluginInfoResponse(EzyPluginInfoParams params) { super(EzyCommand.PLUGIN_INFO, params); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestAppResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestAppResponse.java index 77b88b96e..0a61b6fe7 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestAppResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestAppResponse.java @@ -9,5 +9,5 @@ public class EzyRequestAppResponse public EzyRequestAppResponse(EzyRequestAppResponseParams params) { super(EzyCommand.APP_REQUEST, params); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestPluginResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestPluginResponse.java index c65e352b3..45e693fd2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestPluginResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestPluginResponse.java @@ -9,5 +9,5 @@ public class EzyRequestPluginResponse public EzyRequestPluginResponse(EzyRequestPluginResponseParams params) { super(EzyCommand.PLUGIN_REQUEST, params); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyResponse.java index e4508feaa..31fa6a946 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyResponse.java @@ -8,6 +8,6 @@ public interface EzyResponse extends EzyArraySerializable, EzyReleasable, Serializable { - EzyConstant getCommand(); - + EzyConstant getCommand(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGenerator.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGenerator.java index ec8d665b7..d8ece8792 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGenerator.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGenerator.java @@ -2,6 +2,6 @@ public interface EzySessionTokenGenerator { - String generate(); - + String generate(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleSessionTokenGenerator.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleSessionTokenGenerator.java index 3e4cbc5bb..dd95069e4 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleSessionTokenGenerator.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleSessionTokenGenerator.java @@ -8,31 +8,31 @@ public class EzySimpleSessionTokenGenerator implements EzySessionTokenGenerator { - private final AtomicLong counter; - private final String serverNodeName; - - public EzySimpleSessionTokenGenerator() { - this("ezyfox"); - } - - public EzySimpleSessionTokenGenerator(String serverNodeName) { - this.counter = new AtomicLong(); - this.serverNodeName = serverNodeName; - } - - @Override - public String generate() { - String token = new StringBuilder() - .append(serverNodeName).append("#") - .append(getCount()).append("#") - .append(UUID.randomUUID()).append("#") - .append(System.currentTimeMillis()) - .toString(); - return EzySHA256.cryptUtfToLowercase(token); - } - - private long getCount() { - return counter.incrementAndGet(); - } - + private final AtomicLong counter; + private final String serverNodeName; + + public EzySimpleSessionTokenGenerator() { + this("ezyfox"); + } + + public EzySimpleSessionTokenGenerator(String serverNodeName) { + this.counter = new AtomicLong(); + this.serverNodeName = serverNodeName; + } + + @Override + public String generate() { + String token = new StringBuilder() + .append(serverNodeName).append("#") + .append(getCount()).append("#") + .append(UUID.randomUUID()).append("#") + .append(System.currentTimeMillis()) + .toString(); + return EzySHA256.cryptUtfToLowercase(token); + } + + private long getCount() { + return counter.incrementAndGet(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSetting.java index 9bd289555..086fa2e7b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSetting.java @@ -22,105 +22,105 @@ public abstract class EzyAbstractSetting implements EzyBaseSetting, EzyZoneIdAware, EzyHomePathAware { - protected final int id = newId(); - - @XmlElement(name = "name") - protected String name; - - @XmlElement(name = "folder") + protected final int id = newId(); + + @XmlElement(name = "name") + protected String name; + + @XmlElement(name = "folder") protected String folder; - @XmlElement(name = "active-profiles") + @XmlElement(name = "active-profiles") protected String activeProfiles; - - @XmlElement(name = "package-name") + + @XmlElement(name = "package-name") protected String packageName; - - protected int zoneId; - - @XmlElement(name = "entry-loader") - protected String entryLoader; - - @XmlElement(name = "thread-pool-size") - protected int threadPoolSize = 0; - - @XmlElement(name = "config-file") - protected String configFile = "config.properties"; - - protected String homePath = ""; - - protected Object[] entryLoaderArgs; - - protected int newId() { - return getIdCounter().incrementAndGet(); - } - - public void setEntryLoader(Class loaderClass) { - this.entryLoader = loaderClass.getName(); - } - - public void setEntryLoader(String loaderClass) { + + protected int zoneId; + + @XmlElement(name = "entry-loader") + protected String entryLoader; + + @XmlElement(name = "thread-pool-size") + protected int threadPoolSize = 0; + + @XmlElement(name = "config-file") + protected String configFile = "config.properties"; + + protected String homePath = ""; + + protected Object[] entryLoaderArgs; + + protected int newId() { + return getIdCounter().incrementAndGet(); + } + + public void setEntryLoader(Class loaderClass) { + this.entryLoader = loaderClass.getName(); + } + + public void setEntryLoader(String loaderClass) { this.entryLoader = loaderClass; } - - public void setEntryLoaderArgs(Object[] args) { - this.entryLoaderArgs = args; - } - - @Override - public String getFolder() { - return EzyStrings.isNoContent(folder) ? name : folder; - } - - @Override - public String getLocation() { - return Paths.get(homePath, getParentFolder(), getFolder()).toString(); - } - - @Override + + public void setEntryLoaderArgs(Object[] args) { + this.entryLoaderArgs = args; + } + + @Override + public String getFolder() { + return EzyStrings.isNoContent(folder) ? name : folder; + } + + @Override + public String getLocation() { + return Paths.get(homePath, getParentFolder(), getFolder()).toString(); + } + + @Override public String getConfigFile() { return getConfigFile(false); } - - @Override - public String getConfigFileInput() { - return getConfigFile(true); - } - - @Override - public String getConfigFile(boolean noParent) { - if(noParent) - return configFile; - return Paths.get(getLocation(), configFile).toString(); - } - - protected abstract String getParentFolder(); - protected abstract AtomicInteger getIdCounter(); - - @Override + + @Override + public String getConfigFileInput() { + return getConfigFile(true); + } + + @Override + public String getConfigFile(boolean noParent) { + if(noParent) + return configFile; + return Paths.get(getLocation(), configFile).toString(); + } + + protected abstract String getParentFolder(); + protected abstract AtomicInteger getIdCounter(); + + @Override public boolean equals(Object obj) { return new EzyEquals() .function(t -> t.id) .isEquals(this, obj); } - - @Override - public int hashCode() { - return new EzyHashCodes().append(id).toHashCode(); - } - - @Override - public Map toMap() { - Map map = new HashMap<>(); - map.put("id", id); - map.put("name", name); - map.put("folder", getFolder()); - map.put("packageName", packageName); - map.put("activeProfiles", activeProfiles); - map.put("entryLoader", entryLoader); - map.put("threadPoolSize", threadPoolSize); - map.put("configFile", configFile != null ? configFile : ""); - return map; - } - + + @Override + public int hashCode() { + return new EzyHashCodes().append(id).toHashCode(); + } + + @Override + public Map toMap() { + Map map = new HashMap<>(); + map.put("id", id); + map.put("name", name); + map.put("folder", getFolder()); + map.put("packageName", packageName); + map.put("activeProfiles", activeProfiles); + map.put("entryLoader", entryLoader); + map.put("threadPoolSize", threadPoolSize); + map.put("configFile", configFile != null ? configFile : ""); + return map; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSettingBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSettingBuilder.java index b3ec3d6fc..66becbe0b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSettingBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSettingBuilder.java @@ -53,7 +53,7 @@ public T build() { p.setEntryLoaderArgs(entryLoaderArgs); return p; } - + protected abstract T newSetting(); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSocketSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSocketSetting.java index 58e6a7e94..531eb2c5e 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSocketSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSocketSetting.java @@ -27,23 +27,23 @@ public abstract class EzyAbstractSocketSetting implements EzyBaseSocketSetting { @XmlElement(name = "ssl-active") protected boolean sslActive; - @XmlElement(name = "codec-creator") - protected String codecCreator; - - public EzyAbstractSocketSetting() { - setActive(true); - setSslActive(false); - setAddress("0.0.0.0"); - } - - @Override - public Map toMap() { - Map map = new HashMap<>(); + @XmlElement(name = "codec-creator") + protected String codecCreator; + + public EzyAbstractSocketSetting() { + setActive(true); + setSslActive(false); + setAddress("0.0.0.0"); + } + + @Override + public Map toMap() { + Map map = new HashMap<>(); map.put("port", port); map.put("address", address); map.put("active", active); map.put("codecCreator", codecCreator); return map; - } - + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyEventControllerSettingBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyEventControllerSettingBuilder.java index 53a5c5fc2..f4302a82f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyEventControllerSettingBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyEventControllerSettingBuilder.java @@ -4,27 +4,27 @@ import com.tvd12.ezyfoxserver.constant.EzyEventType; public class EzyEventControllerSettingBuilder - implements EzyBuilder { + implements EzyBuilder { - private String eventType; - private String controller; - - public EzyEventControllerSettingBuilder eventType(EzyEventType eventType) { - this.eventType = eventType.toString(); - return this; - } - - public EzyEventControllerSettingBuilder controller(Class controllerClass) { - this.controller = controllerClass.getName(); - return this; - } - - @Override - public EzySimpleEventControllerSetting build() { - EzySimpleEventControllerSetting setting = new EzySimpleEventControllerSetting(); - setting.setEventType(eventType); - setting.setController(controller); - return setting; - } + private String eventType; + private String controller; + + public EzyEventControllerSettingBuilder eventType(EzyEventType eventType) { + this.eventType = eventType.toString(); + return this; + } + + public EzyEventControllerSettingBuilder controller(Class controllerClass) { + this.controller = controllerClass.getName(); + return this; + } + + @Override + public EzySimpleEventControllerSetting build() { + EzySimpleEventControllerSetting setting = new EzySimpleEventControllerSetting(); + setting.setEventType(eventType); + setting.setController(controller); + return setting; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginSettingBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginSettingBuilder.java index 611fd0606..890aebfb1 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginSettingBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginSettingBuilder.java @@ -20,7 +20,7 @@ public EzyPluginSettingBuilder addListenEvent(String event) { } public EzyPluginSettingBuilder addListenEvent(EzyConstant event) { - return addListenEvent(event.toString()); + return addListenEvent(event.toString()); } public EzyPluginSettingBuilder listenEvents(EzySimpleListenEvents listenEvents) { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppSetting.java index b6b092d99..4c3ef77d2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppSetting.java @@ -28,25 +28,25 @@ public class EzySimpleAppSetting extends EzyAbstractSetting implements EzyAppSet @XmlElement(name = "max-users") protected int maxUsers = 999999; - private static final AtomicInteger COUNTER = new AtomicInteger(0); - - @Override - protected AtomicInteger getIdCounter() { - return COUNTER; - } - - @Override - protected String getParentFolder() { - Path path = Paths.get(homePath, APPS, ENTRIES); - return (Files.exists(path) - ? Paths.get(APPS, ENTRIES) - : Paths.get(APPS)).toString(); - } - - @Override - public Map toMap() { - Map map = super.toMap(); - map.put("maxUsers", maxUsers); - return map; - } + private static final AtomicInteger COUNTER = new AtomicInteger(0); + + @Override + protected AtomicInteger getIdCounter() { + return COUNTER; + } + + @Override + protected String getParentFolder() { + Path path = Paths.get(homePath, APPS, ENTRIES); + return (Files.exists(path) + ? Paths.get(APPS, ENTRIES) + : Paths.get(APPS)).toString(); + } + + @Override + public Map toMap() { + Map map = super.toMap(); + map.put("maxUsers", maxUsers); + return map; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppsSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppsSetting.java index 159731b3a..aebdc05f5 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppsSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppsSetting.java @@ -23,53 +23,53 @@ @XmlRootElement(name = "applications") public class EzySimpleAppsSetting implements EzyAppsSetting { - protected final List apps = new ArrayList<>(); - protected final Map appsByIds = new ConcurrentHashMap<>(); - protected final Map appsByNames = new ConcurrentHashMap<>(); - - @XmlElement(name = "application") - public void setItem(EzySimpleAppSetting item) { - apps.add(item); - appsByIds.put(item.getId(), item); - appsByNames.put(item.getName(), item); - } - - @Override - public Set getAppNames() { - return appsByNames.keySet(); - } - - @Override - public Set getAppIds() { - return appsByIds.keySet(); - } - - @Override - public EzySimpleAppSetting getAppByName(String name) { - EzySimpleAppSetting appSetting = appsByNames.get(name); - if(appSetting != null) - return appSetting; - throw new IllegalArgumentException("has no app with name: " + name); - } - - @Override - public EzySimpleAppSetting getAppById(Integer id) { - EzySimpleAppSetting appSetting = appsByIds.get(id); - if(appSetting != null) - return appSetting; - throw new IllegalArgumentException("has no app with id: " + id); - } - - @Override - public int getSize() { - return apps.size(); - } - - public void setZoneId(int zoneId) { + protected final List apps = new ArrayList<>(); + protected final Map appsByIds = new ConcurrentHashMap<>(); + protected final Map appsByNames = new ConcurrentHashMap<>(); + + @XmlElement(name = "application") + public void setItem(EzySimpleAppSetting item) { + apps.add(item); + appsByIds.put(item.getId(), item); + appsByNames.put(item.getName(), item); + } + + @Override + public Set getAppNames() { + return appsByNames.keySet(); + } + + @Override + public Set getAppIds() { + return appsByIds.keySet(); + } + + @Override + public EzySimpleAppSetting getAppByName(String name) { + EzySimpleAppSetting appSetting = appsByNames.get(name); + if(appSetting != null) + return appSetting; + throw new IllegalArgumentException("has no app with name: " + name); + } + + @Override + public EzySimpleAppSetting getAppById(Integer id) { + EzySimpleAppSetting appSetting = appsByIds.get(id); + if(appSetting != null) + return appSetting; + throw new IllegalArgumentException("has no app with id: " + id); + } + + @Override + public int getSize() { + return apps.size(); + } + + public void setZoneId(int zoneId) { apps.forEach(a -> ((EzyZoneIdAware)a).setZoneId(zoneId)); } - - @Override + + @Override public Map toMap() { Map map = new HashMap<>(); List appMaps = new ArrayList<>(); @@ -79,5 +79,5 @@ public Map toMap() { map.put("apps", appMaps); return map; } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleEventControllersSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleEventControllersSetting.java index dbc7ab992..927f20d9f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleEventControllersSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleEventControllersSetting.java @@ -25,7 +25,7 @@ public class EzySimpleEventControllersSetting implements EzyEventControllersSett @XmlElement(name = "event-controller") public void setItem(EzySimpleEventControllerSetting item) { - eventControllers.add(item); + eventControllers.add(item); } @Override diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginSetting.java index d0e456188..9ba11e945 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginSetting.java @@ -24,25 +24,25 @@ @XmlRootElement(name = "plugin") public class EzySimplePluginSetting extends EzyAbstractSetting implements EzyPluginSetting { - @XmlElement(name = "priority") - protected int priority; - - @XmlElement(name = "listen-events") - protected EzySimpleListenEvents listenEvents = new EzySimpleListenEvents(); - - private static final AtomicInteger COUNTER = new AtomicInteger(0); - - @Override - protected AtomicInteger getIdCounter() { - return COUNTER; - } - - @Override - protected String getParentFolder() { - return EzyFolderNamesSetting.PLUGINS; - } - - @Override + @XmlElement(name = "priority") + protected int priority; + + @XmlElement(name = "listen-events") + protected EzySimpleListenEvents listenEvents = new EzySimpleListenEvents(); + + private static final AtomicInteger COUNTER = new AtomicInteger(0); + + @Override + protected AtomicInteger getIdCounter() { + return COUNTER; + } + + @Override + protected String getParentFolder() { + return EzyFolderNamesSetting.PLUGINS; + } + + @Override public Map toMap() { Map map = super.toMap(); map.put("priority", priority); @@ -50,18 +50,18 @@ public Map toMap() { return map; } - @Getter - @ToString - @XmlAccessorType(XmlAccessType.NONE) - @XmlRootElement(name = "listen-events") - public static class EzySimpleListenEvents implements EzyListenEvents { - protected Set events = new HashSet<>(); - - @XmlElement(name = "event") - public void setEvent(String string) { - events.add(EzyEventType.valueOf(string)); - } - - } - + @Getter + @ToString + @XmlAccessorType(XmlAccessType.NONE) + @XmlRootElement(name = "listen-events") + public static class EzySimpleListenEvents implements EzyListenEvents { + protected Set events = new HashSet<>(); + + @XmlElement(name = "event") + public void setEvent(String string) { + events.add(EzyEventType.valueOf(string)); + } + + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginsSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginsSetting.java index 92103d2be..3e7ec0b9b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginsSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginsSetting.java @@ -23,53 +23,53 @@ @XmlRootElement(name = "plugins") public class EzySimplePluginsSetting implements EzyPluginsSetting { - protected final List plugins = new ArrayList<>(); - protected final Map pluginsByIds = new ConcurrentHashMap<>(); - protected final Map pluginsByNames = new ConcurrentHashMap<>(); - - @XmlElement(name = "plugin") - public void setItem(EzySimplePluginSetting item) { - plugins.add(item); - pluginsByIds.put(item.getId(), item); - pluginsByNames.put(item.getName(), item); - } - - @Override - public Set getPluginNames() { - return pluginsByNames.keySet(); - } - - @Override - public Set getPluginIds() { - return pluginsByIds.keySet(); - } - - @Override - public EzySimplePluginSetting getPluginByName(String name) { - EzySimplePluginSetting pluginSetting = pluginsByNames.get(name); - if(pluginSetting != null) - return pluginSetting; - throw new IllegalArgumentException("has no plugin with name: " + name); - } - - @Override - public EzySimplePluginSetting getPluginById(Integer id) { - EzySimplePluginSetting pluginSetting = pluginsByIds.get(id); - if(pluginSetting != null) - return pluginSetting; - throw new IllegalArgumentException("has no plugin with id: " + id); - } - - @Override - public int getSize() { - return plugins.size(); - } - - public void setZoneId(int zoneId) { - plugins.forEach(p -> ((EzyZoneIdAware)p).setZoneId(zoneId)); - } - - @Override + protected final List plugins = new ArrayList<>(); + protected final Map pluginsByIds = new ConcurrentHashMap<>(); + protected final Map pluginsByNames = new ConcurrentHashMap<>(); + + @XmlElement(name = "plugin") + public void setItem(EzySimplePluginSetting item) { + plugins.add(item); + pluginsByIds.put(item.getId(), item); + pluginsByNames.put(item.getName(), item); + } + + @Override + public Set getPluginNames() { + return pluginsByNames.keySet(); + } + + @Override + public Set getPluginIds() { + return pluginsByIds.keySet(); + } + + @Override + public EzySimplePluginSetting getPluginByName(String name) { + EzySimplePluginSetting pluginSetting = pluginsByNames.get(name); + if(pluginSetting != null) + return pluginSetting; + throw new IllegalArgumentException("has no plugin with name: " + name); + } + + @Override + public EzySimplePluginSetting getPluginById(Integer id) { + EzySimplePluginSetting pluginSetting = pluginsByIds.get(id); + if(pluginSetting != null) + return pluginSetting; + throw new IllegalArgumentException("has no plugin with id: " + id); + } + + @Override + public int getSize() { + return plugins.size(); + } + + public void setZoneId(int zoneId) { + plugins.forEach(p -> ((EzyZoneIdAware)p).setZoneId(zoneId)); + } + + @Override public Map toMap() { Map map = new HashMap<>(); List pluginMaps = new ArrayList<>(); @@ -79,5 +79,5 @@ public Map toMap() { map.put("plugins", pluginMaps); return map; } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettings.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettings.java index 91e6a4ff2..e8d67ef69 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettings.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettings.java @@ -33,34 +33,34 @@ public class EzySimpleSettings implements EzySettings { @XmlElement(name = "streaming") protected EzySimpleStreamingSetting streaming = new EzySimpleStreamingSetting(); - @XmlElement(name = "http") - protected EzySimpleHttpSetting http = new EzySimpleHttpSetting(); - - @XmlElement(name = "socket") - protected EzySimpleSocketSetting socket = new EzySimpleSocketSetting(); - - @XmlElement(name = "udp") - protected EzySimpleUdpSetting udp = new EzySimpleUdpSetting(); - - @XmlElement(name = "administrators") - protected EzySimpleAdminsSetting admins = new EzySimpleAdminsSetting(); - - @XmlElement(name = "logger") - protected EzySimpleLoggerSetting logger = new EzySimpleLoggerSetting(); - - @XmlElement(name = "web-socket") - protected EzySimpleWebSocketSetting websocket = new EzySimpleWebSocketSetting(); - - @XmlElement(name = "thread-pool-size") - protected EzySimpleThreadPoolSizeSetting threadPoolSize = new EzySimpleThreadPoolSizeSetting(); - - @XmlElement(name = "session-management") - protected EzySimpleSessionManagementSetting sessionManagement = new EzySimpleSessionManagementSetting(); - - @XmlElement(name = "event-controllers") - protected EzySimpleEventControllersSetting eventControllers = new EzySimpleEventControllersSetting(); - - @Setter(AccessLevel.NONE) + @XmlElement(name = "http") + protected EzySimpleHttpSetting http = new EzySimpleHttpSetting(); + + @XmlElement(name = "socket") + protected EzySimpleSocketSetting socket = new EzySimpleSocketSetting(); + + @XmlElement(name = "udp") + protected EzySimpleUdpSetting udp = new EzySimpleUdpSetting(); + + @XmlElement(name = "administrators") + protected EzySimpleAdminsSetting admins = new EzySimpleAdminsSetting(); + + @XmlElement(name = "logger") + protected EzySimpleLoggerSetting logger = new EzySimpleLoggerSetting(); + + @XmlElement(name = "web-socket") + protected EzySimpleWebSocketSetting websocket = new EzySimpleWebSocketSetting(); + + @XmlElement(name = "thread-pool-size") + protected EzySimpleThreadPoolSizeSetting threadPoolSize = new EzySimpleThreadPoolSizeSetting(); + + @XmlElement(name = "session-management") + protected EzySimpleSessionManagementSetting sessionManagement = new EzySimpleSessionManagementSetting(); + + @XmlElement(name = "event-controllers") + protected EzySimpleEventControllersSetting eventControllers = new EzySimpleEventControllersSetting(); + + @Setter(AccessLevel.NONE) protected EzySimpleZonesSetting zones = new EzySimpleZonesSetting(); @XmlElement(name = "zones") @@ -90,25 +90,25 @@ public void addZone(EzySimpleZoneSetting zone) { this.zones.setItem(zone); } - @Override - public Set getZoneNames() { - return zones.getZoneNames(); - } - - @Override - public Set getZoneIds() { - return zones.getZoneIds(); - } - - @Override - public EzySimpleZoneSetting getZoneByName(String name) { - return zones.getZoneByName(name); - } - - @Override - public EzySimpleZoneSetting getZoneById(Integer id) { - return zones.getZoneById(id); - } - //=============================================// - + @Override + public Set getZoneNames() { + return zones.getZoneNames(); + } + + @Override + public Set getZoneIds() { + return zones.getZoneIds(); + } + + @Override + public EzySimpleZoneSetting getZoneByName(String name) { + return zones.getZoneByName(name); + } + + @Override + public EzySimpleZoneSetting getZoneById(Integer id) { + return zones.getZoneById(id); + } + //=============================================// + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFileSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFileSetting.java index cd270f235..52f33a8b7 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFileSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFileSetting.java @@ -24,5 +24,5 @@ public class EzySimpleZoneFileSetting { @XmlElement(name = "active") protected boolean active = true; - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFilesSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFilesSetting.java index ed0cdb89b..de486d683 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFilesSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneFilesSetting.java @@ -26,5 +26,5 @@ public class EzySimpleZoneFilesSetting { public void forEach(Consumer consumer) { zoneFiles.forEach(consumer); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneSetting.java index e096626b3..92c96ce27 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZoneSetting.java @@ -36,8 +36,8 @@ public class EzySimpleZoneSetting implements EzyZoneSetting, EzyInitable { @XmlElement(name = "streaming") protected EzySimpleStreamingSetting streaming = new EzySimpleStreamingSetting(); - - @XmlElement(name = "plugins") + + @XmlElement(name = "plugins") protected EzySimplePluginsSetting plugins = new EzySimplePluginsSetting(); @XmlElement(name = "applications") @@ -56,48 +56,48 @@ public void init() { plugins.setZoneId(id); applications.setZoneId(id); } - - //==================== apps ================// - public Set getAppNames() { - return applications.getAppNames(); - } - - public Set getAppIds() { - return applications.getAppIds(); - } - - public EzySimpleAppSetting getAppByName(String name) { - return applications.getAppByName(name); - } - - public EzySimpleAppSetting getAppById(Integer id) { - return applications.getAppById(id); - } - //=============================================// - - //==================== plugins ================// - @Override - public Set getPluginNames() { - return plugins.getPluginNames(); - } - - @Override - public Set getPluginIds() { - return plugins.getPluginIds(); - } - - @Override - public EzySimplePluginSetting getPluginByName(String name) { - return plugins.getPluginByName(name); - } - - @Override - public EzySimplePluginSetting getPluginById(Integer id) { - return plugins.getPluginById(id); - } - //=============================================// - - @Override + + //==================== apps ================// + public Set getAppNames() { + return applications.getAppNames(); + } + + public Set getAppIds() { + return applications.getAppIds(); + } + + public EzySimpleAppSetting getAppByName(String name) { + return applications.getAppByName(name); + } + + public EzySimpleAppSetting getAppById(Integer id) { + return applications.getAppById(id); + } + //=============================================// + + //==================== plugins ================// + @Override + public Set getPluginNames() { + return plugins.getPluginNames(); + } + + @Override + public Set getPluginIds() { + return plugins.getPluginIds(); + } + + @Override + public EzySimplePluginSetting getPluginByName(String name) { + return plugins.getPluginByName(name); + } + + @Override + public EzySimplePluginSetting getPluginById(Integer id) { + return plugins.getPluginById(id); + } + //=============================================// + + @Override public boolean equals(Object obj) { return new EzyEquals() .function(t -> t.id) @@ -123,5 +123,5 @@ public Map toMap() { map.put("applications", applications.toMap()); return map; } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZonesSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZonesSetting.java index 16c6abd27..cf231f332 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZonesSetting.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleZonesSetting.java @@ -18,57 +18,57 @@ @ToString public class EzySimpleZonesSetting implements EzyZonesSetting { - protected final List zones = new ArrayList<>(); - protected final Map zonesByIds = new ConcurrentHashMap<>(); - protected final Map zonesByNames = new ConcurrentHashMap<>(); + protected final List zones = new ArrayList<>(); + protected final Map zonesByIds = new ConcurrentHashMap<>(); + protected final Map zonesByNames = new ConcurrentHashMap<>(); + + @XmlElement(name = "zone") + public void setItem(EzySimpleZoneSetting item) { + zones.add(item); + zonesByIds.put(item.getId(), item); + zonesByNames.put(item.getName(), item); + } + + @Override + public Set getZoneNames() { + return zonesByNames.keySet(); + } + + @Override + public Set getZoneIds() { + return zonesByIds.keySet(); + } + + @Override + public EzySimpleZoneSetting getZoneByName(String name) { + EzySimpleZoneSetting zoneSetting = zonesByNames.get(name); + if(zoneSetting != null) + return zoneSetting; + throw new IllegalArgumentException("has no zone with name: " + name); + } + + @Override + public EzySimpleZoneSetting getZoneById(Integer id) { + EzySimpleZoneSetting zoneSetting = zonesByIds.get(id); + if(zoneSetting != null) + return zoneSetting; + throw new IllegalArgumentException("has no zone with id: " + id); + } + + @Override + public int getSize() { + return zones.size(); + } + + @Override + public Map toMap() { + Map map = new HashMap<>(); + List zoneMaps = new ArrayList<>(); + for(EzyZoneSetting zone : zones) + zoneMaps.add(zone.toMap()); + map.put("size", zones.size()); + map.put("zones", zoneMaps); + return map; + } - @XmlElement(name = "zone") - public void setItem(EzySimpleZoneSetting item) { - zones.add(item); - zonesByIds.put(item.getId(), item); - zonesByNames.put(item.getName(), item); - } - - @Override - public Set getZoneNames() { - return zonesByNames.keySet(); - } - - @Override - public Set getZoneIds() { - return zonesByIds.keySet(); - } - - @Override - public EzySimpleZoneSetting getZoneByName(String name) { - EzySimpleZoneSetting zoneSetting = zonesByNames.get(name); - if(zoneSetting != null) - return zoneSetting; - throw new IllegalArgumentException("has no zone with name: " + name); - } - - @Override - public EzySimpleZoneSetting getZoneById(Integer id) { - EzySimpleZoneSetting zoneSetting = zonesByIds.get(id); - if(zoneSetting != null) - return zoneSetting; - throw new IllegalArgumentException("has no zone with id: " + id); - } - - @Override - public int getSize() { - return zones.size(); - } - - @Override - public Map toMap() { - Map map = new HashMap<>(); - List zoneMaps = new ArrayList<>(); - for(EzyZoneSetting zone : zones) - zoneMaps.add(zone.toMap()); - map.put("size", zones.size()); - map.put("zones", zoneMaps); - return map; - } - } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySslConfigSettingBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySslConfigSettingBuilder.java index 56b20c699..2cf155bbf 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySslConfigSettingBuilder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySslConfigSettingBuilder.java @@ -9,27 +9,27 @@ public class EzySslConfigSettingBuilder implements EzyBuilder queue; - - public EzyBlockingSessionTicketsQueue() { - this.queue = new LinkedBlockingQueue<>(); - } - - @Override - public int size() { - return queue.size(); - } - - @Override - public void clear() { - queue.clear(); - } - - @Override - public boolean isEmpty() { - return queue.isEmpty(); - } - - @Override - public boolean add(EzySession session) { - boolean result = queue.offer(session); - return result; - } - - @SuppressWarnings("unchecked") + private final LinkedBlockingQueue queue; + + public EzyBlockingSessionTicketsQueue() { + this.queue = new LinkedBlockingQueue<>(); + } + + @Override + public int size() { + return queue.size(); + } + + @Override + public void clear() { + queue.clear(); + } + @Override - public T take() throws InterruptedException { - while(true) { - T session = (T) queue.take(); - if(session.isActivated()) - return session; - logger.debug("session: {} maybe destroyed", session); - } - } - + public boolean isEmpty() { + return queue.isEmpty(); + } + + @Override + public boolean add(EzySession session) { + boolean result = queue.offer(session); + return result; + } + + @SuppressWarnings("unchecked") + @Override + public T take() throws InterruptedException { + while(true) { + T session = (T) queue.take(); + if(session.isActivated()) + return session; + logger.debug("session: {} maybe destroyed", session); + } + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketDisconnectionQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketDisconnectionQueue.java index 6bc39f34b..b90bfdfd7 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketDisconnectionQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketDisconnectionQueue.java @@ -9,42 +9,42 @@ public class EzyBlockingSocketDisconnectionQueue extends EzyLoggable implements EzySocketDisconnectionQueue { - private final BlockingQueue queue; - - public EzyBlockingSocketDisconnectionQueue() { - this.queue = new LinkedBlockingQueue(); - } - + private final BlockingQueue queue; + + public EzyBlockingSocketDisconnectionQueue() { + this.queue = new LinkedBlockingQueue(); + } + - @Override - public int size() { - return queue.size(); - } - - @Override - public void clear() { - queue.clear(); - } - - @Override - public boolean isEmpty() { - return queue.isEmpty(); - } - - @Override - public boolean add(EzySocketDisconnection disconnection) { - return queue.offer(disconnection); - } - - @Override - public void remove(EzySocketDisconnection disconnection) { - queue.remove(disconnection); - } - @Override - public EzySocketDisconnection take() throws InterruptedException { + public int size() { + return queue.size(); + } + + @Override + public void clear() { + queue.clear(); + } + + @Override + public boolean isEmpty() { + return queue.isEmpty(); + } + + @Override + public boolean add(EzySocketDisconnection disconnection) { + return queue.offer(disconnection); + } + + @Override + public void remove(EzySocketDisconnection disconnection) { + queue.remove(disconnection); + } + + @Override + public EzySocketDisconnection take() throws InterruptedException { EzySocketDisconnection disconnection = queue.take(); - return disconnection; - } - + return disconnection; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketStreamQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketStreamQueue.java index eed026253..5673ff4ea 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketStreamQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketStreamQueue.java @@ -10,57 +10,57 @@ public class EzyBlockingSocketStreamQueue implements EzySocketStreamQueue { private final int capacity; - private final BlockingQueue queue; - - public EzyBlockingSocketStreamQueue() { - this(50000); - } - - public EzyBlockingSocketStreamQueue(int capacity) { - this.capacity = capacity; + private final BlockingQueue queue; + + public EzyBlockingSocketStreamQueue() { + this(50000); + } + + public EzyBlockingSocketStreamQueue(int capacity) { + this.capacity = capacity; this.queue = newQueue(capacity); - } - - protected BlockingQueue newQueue(int capacity) { - return new LinkedBlockingDeque<>(capacity); - } + } + + protected BlockingQueue newQueue(int capacity) { + return new LinkedBlockingDeque<>(capacity); + } + + @Override + public int size() { + return queue.size(); + } + + @Override + public void clear() { + queue.clear(); + } + + @Override + public boolean isFull() { + return queue.size() >= capacity; + } + + @Override + public boolean isEmpty() { + return queue.isEmpty(); + } + + @Override + public boolean add(EzySocketStream stream) { + if(queue.size() >= capacity) + return false; + return queue.offer(stream); + } + + @Override + public void remove(EzySocketStream stream) { + queue.remove(stream); + } - @Override - public int size() { - return queue.size(); - } - - @Override - public void clear() { - queue.clear(); - } - - @Override - public boolean isFull() { - return queue.size() >= capacity; - } - - @Override - public boolean isEmpty() { - return queue.isEmpty(); - } - - @Override - public boolean add(EzySocketStream stream) { - if(queue.size() >= capacity) - return false; - return queue.offer(stream); - } - - @Override - public void remove(EzySocketStream stream) { - queue.remove(stream); - } - @Override - public EzySocketStream take() throws InterruptedException { + public EzySocketStream take() throws InterruptedException { EzySocketStream stream = queue.take(); - return stream; - } - + return stream; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketUserRemovalQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketUserRemovalQueue.java index 6f8b52823..574e2ac62 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketUserRemovalQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyBlockingSocketUserRemovalQueue.java @@ -9,41 +9,41 @@ public class EzyBlockingSocketUserRemovalQueue extends EzyLoggable implements EzySocketUserRemovalQueue { - private final BlockingQueue queue; - - public EzyBlockingSocketUserRemovalQueue() { - this.queue = new LinkedBlockingQueue(); - } - - @Override - public int size() { - return queue.size(); - } - - @Override - public void clear() { - queue.clear(); - } - - @Override - public boolean isEmpty() { - return queue.isEmpty(); - } - - @Override - public boolean add(EzySocketUserRemoval removal) { - return queue.offer(removal); - } - - @Override - public void remove(EzySocketUserRemoval removal) { - queue.remove(removal); - } - + private final BlockingQueue queue; + + public EzyBlockingSocketUserRemovalQueue() { + this.queue = new LinkedBlockingQueue(); + } + + @Override + public int size() { + return queue.size(); + } + @Override - public EzySocketUserRemoval take() throws InterruptedException { + public void clear() { + queue.clear(); + } + + @Override + public boolean isEmpty() { + return queue.isEmpty(); + } + + @Override + public boolean add(EzySocketUserRemoval removal) { + return queue.offer(removal); + } + + @Override + public void remove(EzySocketUserRemoval removal) { + queue.remove(removal); + } + + @Override + public EzySocketUserRemoval take() throws InterruptedException { EzySocketUserRemoval removal = queue.take(); - return removal; - } - + return removal; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyChannel.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyChannel.java index e732e551f..64b3601f2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyChannel.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyChannel.java @@ -6,20 +6,20 @@ public interface EzyChannel { - void close(); - - void disconnect(); - - boolean isConnected(); - - int write(Object data, boolean binary) throws Exception; - - T getConnection(); - - EzyConnectionType getConnectionType(); - - SocketAddress getServerAddress(); - - SocketAddress getClientAddress(); - + void close(); + + void disconnect(); + + boolean isConnected(); + + int write(Object data, boolean binary) throws Exception; + + T getConnection(); + + EzyConnectionType getConnectionType(); + + SocketAddress getServerAddress(); + + SocketAddress getClientAddress(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyDatagramChannelPool.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyDatagramChannelPool.java index 72300d65f..3b5205962 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyDatagramChannelPool.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyDatagramChannelPool.java @@ -11,64 +11,64 @@ public class EzyDatagramChannelPool extends EzyLoggable { - protected final EzyRoundRobin channels; - - public EzyDatagramChannelPool(int poolSize) { - this.channels = new EzyRoundRobin<>(() -> newChannel(), poolSize); - } - - protected DatagramChannel newChannel() { - try { - DatagramChannel chan = openChannel(); - chan.configureBlocking(false); - chan.socket().setReuseAddress(true); - return chan; - } - catch (Exception e) { - throw new IllegalStateException(e); - } + protected final EzyRoundRobin channels; + + public EzyDatagramChannelPool(int poolSize) { + this.channels = new EzyRoundRobin<>(() -> newChannel(), poolSize); + } + + protected DatagramChannel newChannel() { + try { + DatagramChannel chan = openChannel(); + chan.configureBlocking(false); + chan.socket().setReuseAddress(true); + return chan; + } + catch (Exception e) { + throw new IllegalStateException(e); + } + } + + protected DatagramChannel openChannel() throws IOException { + return DatagramChannel.open(); + } + + public void bind(InetSocketAddress address) { + channels.forEach(channel -> { + try { + channel.bind(address); + } + catch (Exception e) { + throw new IllegalStateException(e); + } + }); } - - protected DatagramChannel openChannel() throws IOException { - return DatagramChannel.open(); - } - - public void bind(InetSocketAddress address) { - channels.forEach(channel -> { - try { - channel.bind(address); - } - catch (Exception e) { - throw new IllegalStateException(e); - } - }); - } - - public void register(Selector selector) { - channels.forEach(channel -> { - try { - channel.register(selector, SelectionKey.OP_READ); - } - catch (Exception e) { - throw new IllegalStateException(e); - } - }); - } - - public DatagramChannel getChannel() { - DatagramChannel channel = channels.get(); - return channel; - } - - public void close() { - channels.forEach(channel -> { - try { - channel.close(); - } - catch (Exception e) { - logger.warn("close datagram channel: {} error", channel, e); - } - }); - } - + + public void register(Selector selector) { + channels.forEach(channel -> { + try { + channel.register(selector, SelectionKey.OP_READ); + } + catch (Exception e) { + throw new IllegalStateException(e); + } + }); + } + + public DatagramChannel getChannel() { + DatagramChannel channel = channels.get(); + return channel; + } + + public void close() { + channels.forEach(channel -> { + try { + channel.close(); + } + catch (Exception e) { + logger.warn("close datagram channel: {} error", channel, e); + } + }); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingPacketQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingPacketQueue.java index f29110a56..9adcac730 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingPacketQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingPacketQueue.java @@ -7,57 +7,57 @@ public class EzyNonBlockingPacketQueue extends EzyLoggable implements EzyPacketQueue { - private final int capacity; - private final Queue queue ; - - public EzyNonBlockingPacketQueue() { - this(128); - } - - public EzyNonBlockingPacketQueue(int capacity) { - this.capacity = capacity; - this.queue = new LinkedList<>(); - } - - @Override - public int size() { - return queue.size(); - } - - @Override - public void clear() { - queue.clear(); - } - - - @Override - public EzyPacket take() { - EzyPacket packet = queue.poll(); - return packet; - } - - @Override - public EzyPacket peek() { - EzyPacket packet = queue.peek(); - return packet; - } - - @Override - public boolean isFull() { - return queue.size() >= capacity; - } - - @Override - public boolean isEmpty() { - return queue.isEmpty(); - } - - @Override - public boolean add(EzyPacket packet) { - if(isFull()) - return false; - boolean answer = queue.offer(packet); - return answer; - } - + private final int capacity; + private final Queue queue ; + + public EzyNonBlockingPacketQueue() { + this(128); + } + + public EzyNonBlockingPacketQueue(int capacity) { + this.capacity = capacity; + this.queue = new LinkedList<>(); + } + + @Override + public int size() { + return queue.size(); + } + + @Override + public void clear() { + queue.clear(); + } + + + @Override + public EzyPacket take() { + EzyPacket packet = queue.poll(); + return packet; + } + + @Override + public EzyPacket peek() { + EzyPacket packet = queue.peek(); + return packet; + } + + @Override + public boolean isFull() { + return queue.size() >= capacity; + } + + @Override + public boolean isEmpty() { + return queue.isEmpty(); + } + + @Override + public boolean add(EzyPacket packet) { + if(isFull()) + return false; + boolean answer = queue.offer(packet); + return answer; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingRequestQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingRequestQueue.java index 6ae2db43f..3efeeebb7 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingRequestQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyNonBlockingRequestQueue.java @@ -7,49 +7,49 @@ public class EzyNonBlockingRequestQueue extends EzyLoggable implements EzyRequestQueue { - private final int capacity; - private final Queue queue ; - - public EzyNonBlockingRequestQueue() { - this(128); - } - - public EzyNonBlockingRequestQueue(int capacity) { - this.capacity = capacity; - this.queue = new LinkedList<>(); - } - - @Override - public int size() { - return queue.size(); - } - - @Override - public void clear() { - queue.clear(); - } - - - @Override - public EzySocketRequest take() { - return queue.poll(); - } - - @Override - public boolean isFull() { - return queue.size() >= capacity; - } - - @Override - public boolean isEmpty() { - return queue.isEmpty(); - } - - @Override - public boolean add(EzySocketRequest packet) { - if(isFull()) - return false; - return queue.offer(packet); - } - + private final int capacity; + private final Queue queue ; + + public EzyNonBlockingRequestQueue() { + this(128); + } + + public EzyNonBlockingRequestQueue(int capacity) { + this.capacity = capacity; + this.queue = new LinkedList<>(); + } + + @Override + public int size() { + return queue.size(); + } + + @Override + public void clear() { + queue.clear(); + } + + + @Override + public EzySocketRequest take() { + return queue.poll(); + } + + @Override + public boolean isFull() { + return queue.size() >= capacity; + } + + @Override + public boolean isEmpty() { + return queue.isEmpty(); + } + + @Override + public boolean add(EzySocketRequest packet) { + if(isFull()) + return false; + return queue.offer(packet); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacket.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacket.java index 4131fe885..6cdc0e9f6 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacket.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacket.java @@ -5,18 +5,18 @@ public interface EzyPacket extends EzyReleasable { - Object getData(); - - boolean isBinary(); - - boolean isReleased(); - - boolean isFragmented(); - - void setFragment(Object fragment); - - EzyConstant getTransportType(); - - int getSize(); - + Object getData(); + + boolean isBinary(); + + boolean isReleased(); + + boolean isFragmented(); + + void setFragment(Object fragment); + + EzyConstant getTransportType(); + + int getSize(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacketQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacketQueue.java index b457e6de8..b2d8384f0 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacketQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyPacketQueue.java @@ -4,16 +4,16 @@ public interface EzyPacketQueue { int size(); - void clear(); - - EzyPacket take(); - - EzyPacket peek(); - - boolean isFull(); - - boolean isEmpty(); + void clear(); + + EzyPacket take(); + + EzyPacket peek(); + + boolean isFull(); + + boolean isEmpty(); - boolean add(EzyPacket packet); - + boolean add(EzyPacket packet); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyRequestQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyRequestQueue.java index 94ad5840b..daba52e14 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyRequestQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzyRequestQueue.java @@ -4,14 +4,14 @@ public interface EzyRequestQueue { int size(); - void clear(); - - EzySocketRequest take(); - - boolean isFull(); - - boolean isEmpty(); + void clear(); + + EzySocketRequest take(); + + boolean isFull(); + + boolean isEmpty(); + + boolean add(EzySocketRequest request); - boolean add(EzySocketRequest request); - } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsQueue.java index 2ac973057..7dbee24cc 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsQueue.java @@ -6,12 +6,12 @@ public interface EzySessionTicketsQueue { int size(); - void clear(); - - boolean isEmpty(); - - boolean add(EzySession session); - - T take() throws InterruptedException; - + void clear(); + + boolean isEmpty(); + + boolean add(EzySession session); + + T take() throws InterruptedException; + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsRequestQueues.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsRequestQueues.java index 09aa3f749..cc3926fc3 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsRequestQueues.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySessionTicketsRequestQueues.java @@ -7,33 +7,33 @@ @Getter public class EzySessionTicketsRequestQueues { - private final EzySessionTicketsQueue systemQueue; - private final EzySessionTicketsQueue extensionQueue; - - { - systemQueue = new EzyBlockingSessionTicketsQueue(); - extensionQueue = new EzyBlockingSessionTicketsQueue(); - } - - public boolean addRequest(EzySocketRequest request) { - EzyRequestQueue queue; - EzySessionTicketsQueue ticketsQueue; - EzySession session = request.getSession(); - if(request.isSystemRequest()) { - ticketsQueue = systemQueue; - queue = session.getSystemRequestQueue(); - } - else { - ticketsQueue = extensionQueue; - queue = session.getExtensionRequestQueue(); - } - boolean success; - synchronized (queue) { - boolean empty = queue.isEmpty(); - success = queue.add(request); - if(empty && success) - ticketsQueue.add(session); - } - return success; - } + private final EzySessionTicketsQueue systemQueue; + private final EzySessionTicketsQueue extensionQueue; + + { + systemQueue = new EzyBlockingSessionTicketsQueue(); + extensionQueue = new EzyBlockingSessionTicketsQueue(); + } + + public boolean addRequest(EzySocketRequest request) { + EzyRequestQueue queue; + EzySessionTicketsQueue ticketsQueue; + EzySession session = request.getSession(); + if(request.isSystemRequest()) { + ticketsQueue = systemQueue; + queue = session.getSystemRequestQueue(); + } + else { + ticketsQueue = extensionQueue; + queue = session.getExtensionRequestQueue(); + } + boolean success; + synchronized (queue) { + boolean empty = queue.isEmpty(); + success = queue.add(request); + if(empty && success) + ticketsQueue.add(session); + } + return success; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySimplePacket.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySimplePacket.java index d349d0e76..cc611d64c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySimplePacket.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySimplePacket.java @@ -10,42 +10,42 @@ public class EzySimplePacket implements EzyPacket { @Setter - private Object data; - private boolean released; - private boolean fragmented; - @Setter + private Object data; + private boolean released; + private boolean fragmented; + @Setter private boolean binary = true; - @Setter - private EzyConstant transportType = EzyTransportType.TCP; - - @Override - public void setFragment(Object fragment) { - this.data = fragment; - this.fragmented = true; - } - - @Override - public int getSize() { - if(data instanceof String) - return ((String)data).length(); - return ((byte[])data).length; - } - - @Override - public void release() { - this.data = null; - this.released = true; - } - - @Override - public String toString() { - return new StringBuilder() - .append("(") - .append("transportType: ") - .append(transportType) - .append(", data: ") - .append(data) - .append(")") - .toString(); - } + @Setter + private EzyConstant transportType = EzyTransportType.TCP; + + @Override + public void setFragment(Object fragment) { + this.data = fragment; + this.fragmented = true; + } + + @Override + public int getSize() { + if(data instanceof String) + return ((String)data).length(); + return ((byte[])data).length; + } + + @Override + public void release() { + this.data = null; + this.released = true; + } + + @Override + public String toString() { + return new StringBuilder() + .append("(") + .append("transportType: ") + .append(transportType) + .append(", data: ") + .append(data) + .append(")") + .toString(); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandler.java index dfb2aa500..3ad00dd82 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandler.java @@ -10,57 +10,57 @@ public class EzySocketDisconnectionHandler extends EzySocketAbstractEventHandler { @Setter - protected EzySocketDisconnectionQueue disconnectionQueue; + protected EzySocketDisconnectionQueue disconnectionQueue; @Setter protected EzySocketDataHandlerGroupRemover dataHandlerGroupRemover; - - @Override + + @Override public void handleEvent() { - processDisconnectionQueue(); - } - - @Override - public void destroy() { - processWithLogException(() -> disconnectionQueue.clear()); - } - - private void processDisconnectionQueue() { - try { - EzySocketDisconnection disconnection = disconnectionQueue.take(); - processDisconnection(disconnection); - } - catch (InterruptedException e) { - logger.info("disconnection-handler thread interrupted: {}", Thread.currentThread()); - } - catch(Throwable throwable) { - logger.warn("problems in disconnection-handler, thread: {}", Thread.currentThread(), throwable); - } - } - - private void processDisconnection(EzySocketDisconnection disconnection) { - try { - processDisconnection0(disconnection); - } - finally { + processDisconnectionQueue(); + } + + @Override + public void destroy() { + processWithLogException(() -> disconnectionQueue.clear()); + } + + private void processDisconnectionQueue() { + try { + EzySocketDisconnection disconnection = disconnectionQueue.take(); + processDisconnection(disconnection); + } + catch (InterruptedException e) { + logger.info("disconnection-handler thread interrupted: {}", Thread.currentThread()); + } + catch(Throwable throwable) { + logger.warn("problems in disconnection-handler, thread: {}", Thread.currentThread(), throwable); + } + } + + private void processDisconnection(EzySocketDisconnection disconnection) { + try { + processDisconnection0(disconnection); + } + finally { disconnection.release(); } - } - - private void processDisconnection0(EzySocketDisconnection disconnection) { - EzySession session = disconnection.getSession(); - EzyConstant disconnectReason = disconnection.getDisconnectReason(); - EzySocketDataHandlerGroup handlerGroup = removeDataHandlerGroup(session); - if(handlerGroup != null) { - handlerGroup.fireChannelInactive(disconnectReason); - } - else { - logger.warn("has no handler group with session: {}, ignore disconnection: {}", session, disconnection); - } - } - - protected EzySocketDataHandlerGroup removeDataHandlerGroup(EzySession session) { - EzySocketDataHandlerGroup group = dataHandlerGroupRemover.removeHandlerGroup(session); - return group; - } - + } + + private void processDisconnection0(EzySocketDisconnection disconnection) { + EzySession session = disconnection.getSession(); + EzyConstant disconnectReason = disconnection.getDisconnectReason(); + EzySocketDataHandlerGroup handlerGroup = removeDataHandlerGroup(session); + if(handlerGroup != null) { + handlerGroup.fireChannelInactive(disconnectReason); + } + else { + logger.warn("has no handler group with session: {}, ignore disconnection: {}", session, disconnection); + } + } + + protected EzySocketDataHandlerGroup removeDataHandlerGroup(EzySession session) { + EzySocketDataHandlerGroup group = dataHandlerGroupRemover.removeHandlerGroup(session); + return group; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandlingLoopHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandlingLoopHandler.java index 47b9746c0..05b6a11ca 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandlingLoopHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionHandlingLoopHandler.java @@ -2,9 +2,9 @@ public class EzySocketDisconnectionHandlingLoopHandler extends EzySocketEventLoopOneHandler { - @Override - protected final String getThreadName() { - return "disconnection-handler"; - } - + @Override + protected final String getThreadName() { + return "disconnection-handler"; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionQueue.java index 031d546e4..142353e5e 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketDisconnectionQueue.java @@ -4,14 +4,14 @@ public interface EzySocketDisconnectionQueue { int size(); - void clear(); - - boolean isEmpty(); - - boolean add(EzySocketDisconnection disconnection); - - void remove(EzySocketDisconnection disconnection); - - EzySocketDisconnection take() throws InterruptedException; - + void clear(); + + boolean isEmpty(); + + boolean add(EzySocketDisconnection disconnection); + + void remove(EzySocketDisconnection disconnection); + + EzySocketDisconnection take() throws InterruptedException; + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoop.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoop.java index b0bf3e28a..2fd254eea 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoop.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoop.java @@ -8,49 +8,49 @@ import com.tvd12.ezyfox.util.EzyStartable; public abstract class EzySocketEventLoop - extends EzyLoggable - implements EzyStartable, EzyDestroyable { - - protected volatile boolean active; - protected EzyThreadList threadPool; - - protected abstract String threadName(); - protected abstract int threadPoolSize(); - - @Override - public void start() throws Exception { - initThreadPool(); - setActive(true); - startLoopService(); - } - - protected void setActive(boolean value) { - this.active = value; - } - - private void startLoopService() { - threadPool.execute(); - } - - private Runnable newServiceTask() { - return () -> eventLoop(); - } - - protected abstract void eventLoop(); - - protected void initThreadPool() { - Runnable task = newServiceTask(); + extends EzyLoggable + implements EzyStartable, EzyDestroyable { + + protected volatile boolean active; + protected EzyThreadList threadPool; + + protected abstract String threadName(); + protected abstract int threadPoolSize(); + + @Override + public void start() throws Exception { + initThreadPool(); + setActive(true); + startLoopService(); + } + + protected void setActive(boolean value) { + this.active = value; + } + + private void startLoopService() { + threadPool.execute(); + } + + private Runnable newServiceTask() { + return () -> eventLoop(); + } + + protected abstract void eventLoop(); + + protected void initThreadPool() { + Runnable task = newServiceTask(); threadPool = new EzyThreadList(threadPoolSize(), task, threadName()); - } - - @Override - public void destroy() { - processWithLogException(() -> this.destroy0()); - } - - protected void destroy0() throws Exception { - setActive(false); - threadPool.interrupt(); - } - + } + + @Override + public void destroy() { + processWithLogException(() -> this.destroy0()); + } + + protected void destroy0() throws Exception { + setActive(false); + threadPool.interrupt(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopHandler.java index 9ba5a0301..94d937ae2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopHandler.java @@ -9,34 +9,34 @@ import lombok.Setter; public abstract class EzySocketEventLoopHandler - extends EzyLoggable - implements EzyThreadPoolSizeAware, EzyStartable, EzyDestroyable { + extends EzyLoggable + implements EzyThreadPoolSizeAware, EzyStartable, EzyDestroyable { @Setter protected int threadPoolSize; protected EzySocketEventLoop eventLoop; - @Override - public void start() throws Exception { - this.eventLoop = newEventLoop0(); - this.eventLoop.start(); - } - - private EzySimpleSocketEventLoop newEventLoop0() { - EzySimpleSocketEventLoop eventLoop = newEventLoop(); - eventLoop.setThreadName(getThreadName()); - eventLoop.setThreadPoolSize(threadPoolSize); - return eventLoop; - } - - protected abstract String getThreadName(); - - protected abstract EzySimpleSocketEventLoop newEventLoop(); - - @Override - public void destroy() { - if(eventLoop != null) - processWithLogException(() -> eventLoop.destroy()); - } - + @Override + public void start() throws Exception { + this.eventLoop = newEventLoop0(); + this.eventLoop.start(); + } + + private EzySimpleSocketEventLoop newEventLoop0() { + EzySimpleSocketEventLoop eventLoop = newEventLoop(); + eventLoop.setThreadName(getThreadName()); + eventLoop.setThreadPoolSize(threadPoolSize); + return eventLoop; + } + + protected abstract String getThreadName(); + + protected abstract EzySimpleSocketEventLoop newEventLoop(); + + @Override + public void destroy() { + if(eventLoop != null) + processWithLogException(() -> eventLoop.destroy()); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopMultiHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopMultiHandler.java index d6c6f5d7d..fcf835c14 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopMultiHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopMultiHandler.java @@ -14,27 +14,27 @@ public abstract class EzySocketEventLoopMultiHandler extends EzySocketEventLoopH protected Supplier eventHandlerSupplier; protected List eventHandlers = new ArrayList<>(); - @Override - protected EzySimpleSocketEventLoop newEventLoop() { - return new EzySimpleSocketEventLoop() { + @Override + protected EzySimpleSocketEventLoop newEventLoop() { + return new EzySimpleSocketEventLoop() { - @Override + @Override protected void eventLoop0() { - EzySocketEventHandler eventHandler = eventHandlerSupplier.get(); - eventHandlers.add(eventHandler); + EzySocketEventHandler eventHandler = eventHandlerSupplier.get(); + eventHandlers.add(eventHandler); while(active) { eventHandler.handleEvent(); } } }; - } - - @Override - public void destroy() { - super.destroy(); - for(EzySocketEventHandler eventHandler : eventHandlers) - processWithLogException(() -> eventHandler.destroy()); - } - + } + + @Override + public void destroy() { + super.destroy(); + for(EzySocketEventHandler eventHandler : eventHandlers) + processWithLogException(() -> eventHandler.destroy()); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopOneHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopOneHandler.java index aa1f27265..5fbdb7f25 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopOneHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketEventLoopOneHandler.java @@ -9,9 +9,9 @@ public abstract class EzySocketEventLoopOneHandler extends EzySocketEventLoopHan @Setter protected EzySocketEventHandler eventHandler; - @Override - protected EzySimpleSocketEventLoop newEventLoop() { - return new EzySimpleSocketEventLoop() { + @Override + protected EzySimpleSocketEventLoop newEventLoop() { + return new EzySimpleSocketEventLoop() { @Override protected void eventLoop0() { @@ -20,13 +20,13 @@ protected void eventLoop0() { } } }; - } - - @Override - public void destroy() { - super.destroy(); - if(eventHandler != null) - processWithLogException(() -> eventHandler.destroy()); - } - + } + + @Override + public void destroy() { + super.destroy(); + if(eventHandler != null) + processWithLogException(() -> eventHandler.destroy()); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketExtensionRequestHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketExtensionRequestHandler.java index 62269cbc7..4e9d96f8c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketExtensionRequestHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketExtensionRequestHandler.java @@ -4,11 +4,11 @@ public class EzySocketExtensionRequestHandler extends EzySocketRequestHandler { - @Override - protected EzyRequestQueue getRequestQueue(EzySession session) { - return session.getExtensionRequestQueue(); - } - + @Override + protected EzyRequestQueue getRequestQueue(EzySession session) { + return session.getExtensionRequestQueue(); + } + @Override protected String getRequestType() { return "extension"; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandler.java index 2e388d227..249b5ee18 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandler.java @@ -10,69 +10,69 @@ public abstract class EzySocketRequestHandler extends EzySocketAbstractEventHandler { @Setter - protected EzySessionTicketsQueue sessionTicketsQueue; + protected EzySessionTicketsQueue sessionTicketsQueue; @Setter protected EzySocketDataHandlerGroupFetcher dataHandlerGroupFetcher; - - @Override + + @Override public void handleEvent() { - processRequestQueue0(); - } - - @Override - public void destroy() { - processWithLogException(() -> sessionTicketsQueue.clear()); - } - - private void processRequestQueue0() { - EzySocketRequest request = null; - try { - EzySession session = sessionTicketsQueue.take(); - EzyRequestQueue requestQueue = getRequestQueue(session); - synchronized (requestQueue) { - request = requestQueue.take(); - if(requestQueue.size() > 0) - sessionTicketsQueue.add(session); - } - processRequestQueue(request); - } - catch (InterruptedException e) { - logger.info("{}-request-handler thread interrupted: {}", getRequestType(), Thread.currentThread()); - } - catch(Throwable throwable) { - logger.warn("problems in {}-request-handler, thread: {}", getRequestType(), Thread.currentThread(), throwable); - } - finally { - if(request != null) - request.release(); - } - } - - protected abstract EzyRequestQueue getRequestQueue(EzySession session); - - protected abstract String getRequestType(); - - private void processRequestQueue(EzySocketRequest request) throws Exception { - try { - processRequestQueue0(request); - } - finally { - request.release(); - } - } - - private void processRequestQueue0(EzySocketRequest request) throws Exception { - EzyArray data = request.getData(); - EzySession session = request.getSession(); - EzySocketDataHandlerGroup handlerGroup = getDataHandlerGroup(session); - if(handlerGroup != null) - handlerGroup.fireChannelRead(request.getCommand(), data); - else - logger.warn("has no handler group with session: {}, drop request: {}", session, request); - } - - protected EzySocketDataHandlerGroup getDataHandlerGroup(EzySession session) { - return dataHandlerGroupFetcher.getDataHandlerGroup(session); - } - + processRequestQueue0(); + } + + @Override + public void destroy() { + processWithLogException(() -> sessionTicketsQueue.clear()); + } + + private void processRequestQueue0() { + EzySocketRequest request = null; + try { + EzySession session = sessionTicketsQueue.take(); + EzyRequestQueue requestQueue = getRequestQueue(session); + synchronized (requestQueue) { + request = requestQueue.take(); + if(requestQueue.size() > 0) + sessionTicketsQueue.add(session); + } + processRequestQueue(request); + } + catch (InterruptedException e) { + logger.info("{}-request-handler thread interrupted: {}", getRequestType(), Thread.currentThread()); + } + catch(Throwable throwable) { + logger.warn("problems in {}-request-handler, thread: {}", getRequestType(), Thread.currentThread(), throwable); + } + finally { + if(request != null) + request.release(); + } + } + + protected abstract EzyRequestQueue getRequestQueue(EzySession session); + + protected abstract String getRequestType(); + + private void processRequestQueue(EzySocketRequest request) throws Exception { + try { + processRequestQueue0(request); + } + finally { + request.release(); + } + } + + private void processRequestQueue0(EzySocketRequest request) throws Exception { + EzyArray data = request.getData(); + EzySession session = request.getSession(); + EzySocketDataHandlerGroup handlerGroup = getDataHandlerGroup(session); + if(handlerGroup != null) + handlerGroup.fireChannelRead(request.getCommand(), data); + else + logger.warn("has no handler group with session: {}, drop request: {}", session, request); + } + + protected EzySocketDataHandlerGroup getDataHandlerGroup(EzySession session) { + return dataHandlerGroupFetcher.getDataHandlerGroup(session); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandlingLoopHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandlingLoopHandler.java index 8aca87776..8e0bb3927 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandlingLoopHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketRequestHandlingLoopHandler.java @@ -2,11 +2,11 @@ public abstract class EzySocketRequestHandlingLoopHandler extends EzySocketEventLoopOneHandler { - @Override - protected final String getThreadName() { - return getRequestType() + "-request-handler"; - } - - protected abstract String getRequestType(); - + @Override + protected final String getThreadName() { + return getRequestType() + "-request-handler"; + } + + protected abstract String getRequestType(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandler.java index 517791500..1196e414d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandler.java @@ -9,54 +9,54 @@ public class EzySocketStreamHandler extends EzySocketAbstractEventHandler { @Setter - protected EzySocketStreamQueue streamQueue; + protected EzySocketStreamQueue streamQueue; @Setter protected EzySocketDataHandlerGroupFetcher dataHandlerGroupFetcher; - - @Override + + @Override public void handleEvent() { - processStreamQueue0(); - } - - @Override - public void destroy() { - processWithLogException(() -> streamQueue.clear()); - } - - private void processStreamQueue0() { - try { - EzySocketStream stream = streamQueue.take(); - processStreamQueue(stream); - } - catch (InterruptedException e) { - logger.warn("socket-stream-handler thread interrupted: {}", Thread.currentThread()); - } - catch(Throwable throwable) { - logger.warn("problems in socket-stream-handler, thread: {}", Thread.currentThread(), throwable); - } - } - - private void processStreamQueue(EzySocketStream stream) throws Exception { - try { - processStreamQueue0(stream); - } - finally { - stream.release(); - } - } - - private void processStreamQueue0(EzySocketStream stream) throws Exception { - byte[] bytes = stream.getBytes(); - EzySession session = stream.getSession(); - EzySocketDataHandlerGroup handlerGroup = getDataHandlerGroup(session); - if(handlerGroup != null) - handlerGroup.fireStreamBytesReceived(bytes); - else - logger.warn("has no handler group with session: {}, drop: {} bytes", session, bytes.length); - } - - protected EzySocketDataHandlerGroup getDataHandlerGroup(EzySession session) { - return dataHandlerGroupFetcher.getDataHandlerGroup(session); - } - + processStreamQueue0(); + } + + @Override + public void destroy() { + processWithLogException(() -> streamQueue.clear()); + } + + private void processStreamQueue0() { + try { + EzySocketStream stream = streamQueue.take(); + processStreamQueue(stream); + } + catch (InterruptedException e) { + logger.warn("socket-stream-handler thread interrupted: {}", Thread.currentThread()); + } + catch(Throwable throwable) { + logger.warn("problems in socket-stream-handler, thread: {}", Thread.currentThread(), throwable); + } + } + + private void processStreamQueue(EzySocketStream stream) throws Exception { + try { + processStreamQueue0(stream); + } + finally { + stream.release(); + } + } + + private void processStreamQueue0(EzySocketStream stream) throws Exception { + byte[] bytes = stream.getBytes(); + EzySession session = stream.getSession(); + EzySocketDataHandlerGroup handlerGroup = getDataHandlerGroup(session); + if(handlerGroup != null) + handlerGroup.fireStreamBytesReceived(bytes); + else + logger.warn("has no handler group with session: {}, drop: {} bytes", session, bytes.length); + } + + protected EzySocketDataHandlerGroup getDataHandlerGroup(EzySession session) { + return dataHandlerGroupFetcher.getDataHandlerGroup(session); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandlingLoopHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandlingLoopHandler.java index 2cadd381e..1b3df960d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandlingLoopHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamHandlingLoopHandler.java @@ -2,9 +2,9 @@ public class EzySocketStreamHandlingLoopHandler extends EzySocketEventLoopOneHandler { - @Override - protected final String getThreadName() { - return "socket-stream-handler"; - } - + @Override + protected final String getThreadName() { + return "socket-stream-handler"; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamQueue.java index e2c31a935..1ffa30297 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketStreamQueue.java @@ -4,16 +4,16 @@ public interface EzySocketStreamQueue { int size(); - void clear(); - - boolean isFull(); - - boolean isEmpty(); - - boolean add(EzySocketStream stream); - - void remove(EzySocketStream stream); - - EzySocketStream take() throws InterruptedException; - + void clear(); + + boolean isFull(); + + boolean isEmpty(); + + boolean add(EzySocketStream stream); + + void remove(EzySocketStream stream); + + EzySocketStream take() throws InterruptedException; + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketSystemRequestHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketSystemRequestHandler.java index 0105e9a09..ab435c08d 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketSystemRequestHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketSystemRequestHandler.java @@ -4,11 +4,11 @@ public class EzySocketSystemRequestHandler extends EzySocketRequestHandler { - @Override - protected EzyRequestQueue getRequestQueue(EzySession session) { - return session.getSystemRequestQueue(); - } - + @Override + protected EzyRequestQueue getRequestQueue(EzySession session) { + return session.getSystemRequestQueue(); + } + @Override protected String getRequestType() { return "system"; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandler.java index 256ab91db..f6686a67c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandler.java @@ -16,60 +16,60 @@ public class EzySocketUserRemovalHandler extends EzySocketAbstractEventHandler { - protected final EzySocketUserRemovalQueue userRemovalQueue; - - public EzySocketUserRemovalHandler(EzySocketUserRemovalQueue userRemovalQueue) { - this.userRemovalQueue = userRemovalQueue; - } - - @Override + protected final EzySocketUserRemovalQueue userRemovalQueue; + + public EzySocketUserRemovalHandler(EzySocketUserRemovalQueue userRemovalQueue) { + this.userRemovalQueue = userRemovalQueue; + } + + @Override public void handleEvent() { - processUserRemovalQueue(); - } - - @Override - public void destroy() { - processWithLogException(() -> userRemovalQueue.clear()); - } - - private void processUserRemovalQueue() { - try { - EzySocketUserRemoval removal = userRemovalQueue.take(); - processUserRemoval(removal); - } - catch (InterruptedException e) { - logger.info("user-removal-handler thread interrupted: {}", Thread.currentThread()); - } - catch(Throwable throwable) { - logger.warn("problems in user-removal-handler, thread: {}", Thread.currentThread(), throwable); - } - } - - private void processUserRemoval(EzySocketUserRemoval removal) { - try { - processUserRemoval0(removal); - } - finally { - removal.release(); + processUserRemovalQueue(); + } + + @Override + public void destroy() { + processWithLogException(() -> userRemovalQueue.clear()); + } + + private void processUserRemovalQueue() { + try { + EzySocketUserRemoval removal = userRemovalQueue.take(); + processUserRemoval(removal); + } + catch (InterruptedException e) { + logger.info("user-removal-handler thread interrupted: {}", Thread.currentThread()); } - } - - private void processUserRemoval0(EzySocketUserRemoval removal) { - EzyUser user = removal.getUser(); - try { - EzyConstant reason = removal.getReason(); - EzyZoneContext zoneContext = removal.getZoneContext(); + catch(Throwable throwable) { + logger.warn("problems in user-removal-handler, thread: {}", Thread.currentThread(), throwable); + } + } + + private void processUserRemoval(EzySocketUserRemoval removal) { + try { + processUserRemoval0(removal); + } + finally { + removal.release(); + } + } + + private void processUserRemoval0(EzySocketUserRemoval removal) { + EzyUser user = removal.getUser(); + try { + EzyConstant reason = removal.getReason(); + EzyZoneContext zoneContext = removal.getZoneContext(); EzyUserRemovedEvent event = newUserRemovedEvent(user, reason); removeUserFromApps(zoneContext, event); notifyUserRemovedToPlugins(zoneContext, event); - } - finally { + } + finally { user.destroy(); } - logger.debug("user {} has destroyed", user); - } - - protected void notifyUserRemovedToPlugins(EzyZoneContext context, EzyUserRemovedEvent event) { + logger.debug("user {} has destroyed", user); + } + + protected void notifyUserRemovedToPlugins(EzyZoneContext context, EzyUserRemovedEvent event) { try { context.broadcastPlugins(EzyEventType.USER_REMOVED, event, true); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandlingLoopHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandlingLoopHandler.java index 613991467..f989d3b9b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandlingLoopHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalHandlingLoopHandler.java @@ -2,9 +2,9 @@ public class EzySocketUserRemovalHandlingLoopHandler extends EzySocketEventLoopOneHandler { - @Override - protected final String getThreadName() { - return "user-removal-handler"; - } - + @Override + protected final String getThreadName() { + return "user-removal-handler"; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalQueue.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalQueue.java index ad8dd1cc2..4b779fce3 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalQueue.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketUserRemovalQueue.java @@ -4,14 +4,14 @@ public interface EzySocketUserRemovalQueue { int size(); - void clear(); - - boolean isEmpty(); - - boolean add(EzySocketUserRemoval removal); - - void remove(EzySocketUserRemoval removal); - - EzySocketUserRemoval take() throws InterruptedException; - + void clear(); + + boolean isEmpty(); + + boolean add(EzySocketUserRemoval removal); + + void remove(EzySocketUserRemoval removal); + + EzySocketUserRemoval take() throws InterruptedException; + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWriter.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWriter.java index 6bb1d1022..5ae9cb0d1 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWriter.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWriter.java @@ -11,65 +11,65 @@ public class EzySocketWriter implements EzySessionTicketsQueueAware { @Setter - protected EzySessionTicketsQueue sessionTicketsQueue; + protected EzySessionTicketsQueue sessionTicketsQueue; @Setter protected EzySocketWriterGroupFetcher writerGroupFetcher; - - @Override + + @Override public void handleEvent() { - processSessionTicketsQueue0(); - } - - @Override + processSessionTicketsQueue0(); + } + + @Override public void destroy() { processWithLogException(() -> sessionTicketsQueue.clear()); } - - private void processSessionTicketsQueue0() { - try { - EzySession session = sessionTicketsQueue.take(); - processSessionQueue(session); - } - catch (InterruptedException e) { - logger.info("socket-writer thread interrupted: {}", Thread.currentThread()); - } - catch(Throwable throwable) { - logger.warn("problems in socket-writer, thread: {}", Thread.currentThread(), throwable); - } - } - - private void processSessionQueue(EzySession session) throws Exception { - EzySocketWriterGroup group = getWriterGroup(session); - if(group == null) - return; - EzyPacketQueue queue = session.getPacketQueue(); - synchronized (queue) { - boolean emptyQueue = processSessionQueue(group, queue); - if(!emptyQueue) { - sessionTicketsQueue.add(session); - } + + private void processSessionTicketsQueue0() { + try { + EzySession session = sessionTicketsQueue.take(); + processSessionQueue(session); + } + catch (InterruptedException e) { + logger.info("socket-writer thread interrupted: {}", Thread.currentThread()); + } + catch(Throwable throwable) { + logger.warn("problems in socket-writer, thread: {}", Thread.currentThread(), throwable); + } + } + + private void processSessionQueue(EzySession session) throws Exception { + EzySocketWriterGroup group = getWriterGroup(session); + if(group == null) + return; + EzyPacketQueue queue = session.getPacketQueue(); + synchronized (queue) { + boolean emptyQueue = processSessionQueue(group, queue); + if(!emptyQueue) { + sessionTicketsQueue.add(session); + } } - } - - private boolean processSessionQueue(EzySocketWriterGroup group, EzyPacketQueue queue) - throws Exception { - if(!queue.isEmpty()) { - EzyPacket packet = queue.peek(); - Object writeBuffer = getWriteBuffer(); - group.firePacketSend(packet, writeBuffer); - if(packet.isReleased()) - queue.take(); - return queue.isEmpty(); - } - return true; - } - - protected Object getWriteBuffer() { - return null; - } - - protected EzySocketWriterGroup getWriterGroup(EzySession session) { + } + + private boolean processSessionQueue(EzySocketWriterGroup group, EzyPacketQueue queue) + throws Exception { + if(!queue.isEmpty()) { + EzyPacket packet = queue.peek(); + Object writeBuffer = getWriteBuffer(); + group.firePacketSend(packet, writeBuffer); + if(packet.isReleased()) + queue.take(); + return queue.isEmpty(); + } + return true; + } + + protected Object getWriteBuffer() { + return null; + } + + protected EzySocketWriterGroup getWriterGroup(EzySession session) { return writerGroupFetcher.getWriterGroup(session); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWritingLoopHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWritingLoopHandler.java index fbd92a053..2504d95e8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWritingLoopHandler.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySocketWritingLoopHandler.java @@ -2,9 +2,9 @@ public class EzySocketWritingLoopHandler extends EzySocketEventLoopMultiHandler { - @Override - protected String getThreadName() { - return "socket-writer"; - } - + @Override + protected String getThreadName() { + return "socket-writer"; + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfigLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfigLoader.java index 4a594e3c0..b281cd417 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfigLoader.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfigLoader.java @@ -27,12 +27,12 @@ protected EzyPropertiesFileReader newPropertiesReader() { .build(); } - protected String getParentFolder(String filePath) { - return Paths.get(filePath).getParent().toString(); - } - - protected String getPath(String first, String... more) { + protected String getParentFolder(String filePath) { + return Paths.get(filePath).getParent().toString(); + } + + protected String getPath(String first, String... more) { return Paths.get(first, more).toString(); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactory.java index 6f73eab58..5c71d15f2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactory.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactory.java @@ -108,7 +108,7 @@ protected String getAlgorithm(EzySslConfig config) { } protected String getDefaultAlgorithm() { - return KeyManagerFactory.getDefaultAlgorithm(); + return KeyManagerFactory.getDefaultAlgorithm(); } protected EzyInputStreamLoader newInputStreamLoader() { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyEventControllers.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyEventControllers.java index 3719c1693..a1a544576 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyEventControllers.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyEventControllers.java @@ -8,10 +8,10 @@ public interface EzyEventControllers extends EzyDestroyable { - @SuppressWarnings("rawtypes") - List getControllers(EzyConstant eventType); - - @SuppressWarnings("rawtypes") - void addController(EzyConstant eventType, EzyEventController controller); - + @SuppressWarnings("rawtypes") + List getControllers(EzyConstant eventType); + + @SuppressWarnings("rawtypes") + void addController(EzyConstant eventType, EzyEventController controller); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerControllers.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerControllers.java index 3580bb619..de2555693 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerControllers.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerControllers.java @@ -8,11 +8,11 @@ @SuppressWarnings("rawtypes") public interface EzyServerControllers { - EzyController getController(EzyConstant cmd); - - EzyInterceptor getInterceptor(EzyConstant cmd); - - EzyInterceptor getStreamingInterceptor(); - - EzyStreamingController getStreamingController(); + EzyController getController(EzyConstant cmd); + + EzyInterceptor getInterceptor(EzyConstant cmd); + + EzyInterceptor getStreamingInterceptor(); + + EzyStreamingController getStreamingController(); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySessionManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySessionManager.java index 7bc563047..92680e34b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySessionManager.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySessionManager.java @@ -24,66 +24,66 @@ public interface EzySessionManager { */ boolean containsSession(long id); - /** + /** * Get session by id * * @param id the id * @return the session mapped to the id */ EzySession getSession(long id); - - /** - * Add session to disconnect queue - * - * @param session the session - * @param reason the reason - */ - void removeSession(S session, EzyConstant reason); - - /** - * clear session - * - * @param session the session - */ - void clearSession(S session); - - /** + + /** + * Add session to disconnect queue + * + * @param session the session + * @param reason the reason + */ + void removeSession(S session, EzyConstant reason); + + /** + * clear session + * + * @param session the session + */ + void clearSession(S session); + + /** * Get all sessions * * @return all sessions */ List getAllSessions(); - - /** - * Get all alive sessions - * - * @return all alive sessions - */ - List getAliveSessions(); - - /** + + /** + * Get all alive sessions + * + * @return all alive sessions + */ + List getAliveSessions(); + + /** * Get logged in sessions * * @return all logged in sessions */ - List getLoggedInSessions(); - - /** - * @return all sessions count - */ - int getAllSessionCount(); - - /** - * @return alive sessions count - */ - int getAliveSessionCount(); - - /** - * @return logged in session count - */ - int getLoggedInSessionCount(); - - /** + List getLoggedInSessions(); + + /** + * @return all sessions count + */ + int getAllSessionCount(); + + /** + * @return alive sessions count + */ + int getAliveSessionCount(); + + /** + * @return logged in session count + */ + int getLoggedInSessionCount(); + + /** * Provide session from pool and map the session to channel * * @param channel the channel @@ -107,5 +107,5 @@ public interface EzySessionManager { default void removeSession(S session) { removeSession(session, EzyDisconnectReason.UNKNOWN); } - + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleSessionManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleSessionManager.java index c74e9fef7..cc345f774 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleSessionManager.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleSessionManager.java @@ -16,78 +16,78 @@ import com.tvd12.ezyfoxserver.socket.EzyChannel; public class EzySimpleSessionManager - extends EzyObjectProvider - implements EzySessionManager { - + extends EzyObjectProvider + implements EzySessionManager { + protected final int maxSessions; - protected final EzySessionTokenGenerator tokenGenerator; - protected final ConcurrentHashMap loggedInSession = new ConcurrentHashMap<>(); - protected final ConcurrentHashMap sessionsById = new ConcurrentHashMap<>(); - protected final ConcurrentHashMap sessionsByConnection = new ConcurrentHashMap<>(); - - protected static final AtomicInteger COUNTER = new AtomicInteger(0); - - protected EzySimpleSessionManager(Builder builder) { - super(builder); - this.maxSessions = builder.maxSessions; - this.tokenGenerator = builder.tokenGenerator; - } - - @Override - public void addLoggedInSession(S session) { - loggedInSession.put(session.getId(), session); - } - - @Override - public boolean containsSession(long id) { - return sessionsById.containsKey(id); - } - - @Override - public void removeSession(S session, EzyConstant reason) { - checkToRemoveSession(session, reason); - } - - @Override + protected final EzySessionTokenGenerator tokenGenerator; + protected final ConcurrentHashMap loggedInSession = new ConcurrentHashMap<>(); + protected final ConcurrentHashMap sessionsById = new ConcurrentHashMap<>(); + protected final ConcurrentHashMap sessionsByConnection = new ConcurrentHashMap<>(); + + protected static final AtomicInteger COUNTER = new AtomicInteger(0); + + protected EzySimpleSessionManager(Builder builder) { + super(builder); + this.maxSessions = builder.maxSessions; + this.tokenGenerator = builder.tokenGenerator; + } + + @Override + public void addLoggedInSession(S session) { + loggedInSession.put(session.getId(), session); + } + + @Override + public boolean containsSession(long id) { + return sessionsById.containsKey(id); + } + + @Override + public void removeSession(S session, EzyConstant reason) { + checkToRemoveSession(session, reason); + } + + @Override public void clearSession(S session) { - if(session != null) { - unmapSession(session); - logger.info(getRemoveSessionMessage(session)); - } + if(session != null) { + unmapSession(session); + logger.info(getRemoveSessionMessage(session)); + } + } + + private String getRemoveSessionMessage(S session) { + StringBuilder builder = new StringBuilder() + .append("remove session: ").append(session.getName()) + .append(", remain sessions = ").append(providedObjects.size()) + .append(", login sessions = ").append(loggedInSession.size()) + .append(", sessions by id = ").append(sessionsById.size()) + .append(", sessions by connection = ").append(sessionsByConnection.size()); + return builder.toString(); + } + + protected void checkToRemoveSession(S session, EzyConstant reason) { + if(shouldRemoveSession(session)) + session.disconnect(reason); + } + + protected boolean shouldRemoveSession(S session) { + if(session == null) + return false; + boolean contains = containsSession(session.getId()); + return contains; + } + + protected void unmapSession(S session) { + providedObjects.remove(session); + sessionsById.remove(session.getId()); + loggedInSession.remove(session.getId()); + EzyChannel channel = session.getChannel(); + Object connection = channel.getConnection(); + sessionsByConnection.remove(connection); } - - private String getRemoveSessionMessage(S session) { - StringBuilder builder = new StringBuilder() - .append("remove session: ").append(session.getName()) - .append(", remain sessions = ").append(providedObjects.size()) - .append(", login sessions = ").append(loggedInSession.size()) - .append(", sessions by id = ").append(sessionsById.size()) - .append(", sessions by connection = ").append(sessionsByConnection.size()); - return builder.toString(); - } - - protected void checkToRemoveSession(S session, EzyConstant reason) { - if(shouldRemoveSession(session)) - session.disconnect(reason); - } - - protected boolean shouldRemoveSession(S session) { - if(session == null) - return false; - boolean contains = containsSession(session.getId()); - return contains; - } - - protected void unmapSession(S session) { - providedObjects.remove(session); - sessionsById.remove(session.getId()); - loggedInSession.remove(session.getId()); - EzyChannel channel = session.getChannel(); - Object connection = channel.getConnection(); - sessionsByConnection.remove(connection); - } - - @Override + + @Override public S provideSession(EzyChannel channel) { S ss = provideSession(channel.getConnectionType()); ss.setChannel(channel); @@ -95,93 +95,93 @@ public S provideSession(EzyChannel channel) { logger.info("provide session: {}, sessions size = {}", ss.getName(), providedObjects.size()); return ss; } - - @SuppressWarnings("unchecked") + + @SuppressWarnings("unchecked") protected S provideSession(EzyConstant connectionType) { - checkMaxSessions(connectionType); - EzyAbstractSession session = (EzyAbstractSession)provideObject(); - session.setLoggedIn(false); - session.setName("Session#" + COUNTER.incrementAndGet()); - session.setConnectionType(connectionType); - session.setToken(newSessionToken()); - session.setCreationTime(System.currentTimeMillis()); - - session.setCreationTime(System.currentTimeMillis()); + checkMaxSessions(connectionType); + EzyAbstractSession session = (EzyAbstractSession)provideObject(); + session.setLoggedIn(false); + session.setName("Session#" + COUNTER.incrementAndGet()); + session.setConnectionType(connectionType); + session.setToken(newSessionToken()); + session.setCreationTime(System.currentTimeMillis()); + + session.setCreationTime(System.currentTimeMillis()); session.setLastActivityTime(System.currentTimeMillis()); session.setLastReadTime(System.currentTimeMillis()); session.setLastWriteTime(System.currentTimeMillis()); S complete = (S)session; sessionsById.put(complete.getId(), complete); - return complete; - } - - protected void checkMaxSessions(EzyConstant connectionType) { - int current = providedObjects.size(); - if(current >= maxSessions) - throw new EzyMaxSessionException(current, maxSessions); - } - - @Override - public EzySession getSession(long id) { - EzySession session = sessionsById.get(id); - return session; - } - - @Override + return complete; + } + + protected void checkMaxSessions(EzyConstant connectionType) { + int current = providedObjects.size(); + if(current >= maxSessions) + throw new EzyMaxSessionException(current, maxSessions); + } + + @Override + public EzySession getSession(long id) { + EzySession session = sessionsById.get(id); + return session; + } + + @Override public S getSession(Object connection) { S session = sessionsByConnection.get(connection); return session; } - - @Override - public List getAllSessions() { - List sessions = getProvidedObjects(); - return sessions; - } - - @Override - public List getAliveSessions() { - List sessions = new ArrayList<>(sessionsById.values()); - return sessions; - }; - - @Override - public List getLoggedInSessions() { - List sessions = new ArrayList<>(loggedInSession.values()); - return sessions; - } - - @Override - public int getAllSessionCount() { - int size = providedObjects.size(); - return size; - } - - @Override - public int getAliveSessionCount() { - int size = sessionsById.size(); - return size; - } - - @Override - public int getLoggedInSessionCount() { - int size = loggedInSession.size(); - return size; - } - - @Override - public void start() throws Exception { - super.start(); - logger.debug("start session manager"); - } - - @Override - protected void removeStaleObjects(List buffer) { - checkAndRemoveSessions(buffer); - } - - protected void checkAndRemoveSessions(List sessions) { - List idleSessions = new ArrayList<>(); + + @Override + public List getAllSessions() { + List sessions = getProvidedObjects(); + return sessions; + } + + @Override + public List getAliveSessions() { + List sessions = new ArrayList<>(sessionsById.values()); + return sessions; + }; + + @Override + public List getLoggedInSessions() { + List sessions = new ArrayList<>(loggedInSession.values()); + return sessions; + } + + @Override + public int getAllSessionCount() { + int size = providedObjects.size(); + return size; + } + + @Override + public int getAliveSessionCount() { + int size = sessionsById.size(); + return size; + } + + @Override + public int getLoggedInSessionCount() { + int size = loggedInSession.size(); + return size; + } + + @Override + public void start() throws Exception { + super.start(); + logger.debug("start session manager"); + } + + @Override + protected void removeStaleObjects(List buffer) { + checkAndRemoveSessions(buffer); + } + + protected void checkAndRemoveSessions(List sessions) { + List idleSessions = new ArrayList<>(); List unloggedInSessions = new ArrayList<>(); for(S session : sessions) { boolean unloggedIn = isUnloggedInSession(session); @@ -198,65 +198,65 @@ protected void checkAndRemoveSessions(List sessions) { removeSession(session, EzyDisconnectReason.IDLE); for(S session : unloggedInSessions) removeSession(session, EzyDisconnectReason.NOT_LOGGED_IN); - } - - protected boolean isIdleSession(S session) { - boolean answer = session.isIdle(); - return answer; - } - - protected boolean isUnloggedInSession(EzySession session) { - if(session.isLoggedIn()) - return false; - if(!session.isActivated()) - return false; - long remainTime = getSessionRemainWaitingTime(session); - boolean answer = remainTime <= 0; - return answer; - } - - protected long getSessionRemainWaitingTime(EzySession session) { - long maxWaitingTime = session.getMaxWaitingTime(); - long creationTime = session.getCreationTime(); - long remain = EzyTimes.getRemainTime(maxWaitingTime, creationTime); - return remain; - } - - protected String newSessionToken() { - String token = tokenGenerator.generate(); - return token; - } - - @Override - public void destroy() { - super.destroy(); - this.loggedInSession.clear(); - this.sessionsById.clear(); - } - - public abstract static class Builder - extends EzyObjectProvider.Builder> { - - protected int maxSessions = 999999; - protected EzySessionTokenGenerator tokenGenerator; - - @Override - protected String getValidationThreadPoolName() { - return "session-manager"; - } - - public Builder maxSessions(int maxSessions) { - this.maxSessions = maxSessions; - return this; - } - - public Builder tokenGenerator(EzySessionTokenGenerator generator) { - this.tokenGenerator = generator; - return this; - } - - public abstract EzySimpleSessionManager build(); - - } + } + + protected boolean isIdleSession(S session) { + boolean answer = session.isIdle(); + return answer; + } + + protected boolean isUnloggedInSession(EzySession session) { + if(session.isLoggedIn()) + return false; + if(!session.isActivated()) + return false; + long remainTime = getSessionRemainWaitingTime(session); + boolean answer = remainTime <= 0; + return answer; + } + + protected long getSessionRemainWaitingTime(EzySession session) { + long maxWaitingTime = session.getMaxWaitingTime(); + long creationTime = session.getCreationTime(); + long remain = EzyTimes.getRemainTime(maxWaitingTime, creationTime); + return remain; + } + + protected String newSessionToken() { + String token = tokenGenerator.generate(); + return token; + } + + @Override + public void destroy() { + super.destroy(); + this.loggedInSession.clear(); + this.sessionsById.clear(); + } + + public abstract static class Builder + extends EzyObjectProvider.Builder> { + + protected int maxSessions = 999999; + protected EzySessionTokenGenerator tokenGenerator; + + @Override + protected String getValidationThreadPoolName() { + return "session-manager"; + } + + public Builder maxSessions(int maxSessions) { + this.maxSessions = maxSessions; + return this; + } + + public Builder tokenGenerator(EzySessionTokenGenerator generator) { + this.tokenGenerator = generator; + return this; + } + + public abstract EzySimpleSessionManager build(); + + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySynchronizedUserManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySynchronizedUserManager.java index 8177840e4..e43d46859 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySynchronizedUserManager.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySynchronizedUserManager.java @@ -9,7 +9,7 @@ public class EzySynchronizedUserManager extends EzyAbstractUserManager { - @Getter + @Getter protected final Object synchronizedLock = new Object(); public EzySynchronizedUserManager(int maxUser) { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserManager.java index 6bfb84d25..5b2c470b7 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserManager.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserManager.java @@ -10,122 +10,122 @@ public interface EzyUserManager extends EzyDestroyable { EzyUser addUser(EzyUser user); - /** - * Get user by id - * - * @param userId the user id - * @return the user - */ - EzyUser getUser(long userId); - - /** - * Get user by id - * - * @param username the user name - * @return the user - */ - EzyUser getUser(String username); - - /** - * Get users as list - * - * @return The users as list - */ - List getUserList(); - - /** - * Get count of users - * - * @return count of users - */ - int getUserCount(); - - /** - * Get max users count - * - * @return the max users count - */ - int getMaxUsers(); - - /** - * available to add user or not - * - * @return available to add user or not - */ - boolean available(); - - /** - * Check whether contains user or not - * - * @param userId the user id - * @return true or false - */ - boolean containsUser(long userId); - - /** - * Check whether contains user or not - * - * @param username the user name - * @return true or false - */ - boolean containsUser(String username); - - /** - * Remove user - * - * @param user the user - * @return the current user - */ - EzyUser removeUser(EzyUser user); - - /** - * Get lock mapped to username - * - * @param username the username - * @return the lock - */ - Lock getLock(String username); - - /** - * Remove lock mapped to username - * - * @param username the username - */ - void removeLock(String username); - - /** - * clear all user - */ - void clear(); - - /** - * Check whether contains user or not - * - * @param user the user - * @return true or false - */ - default boolean containsUser(EzyUser user) { - return containsUser(user.getName()); - } - - /** - * Remove user by id - * - * @param userId the user id - * @return the current user - */ - default EzyUser removeUser(long userId) { - return removeUser(getUser(userId)); - } - - /** - * Remove user byte name - * - * @param username the user name - * @return the current user - */ - default EzyUser removeUser(String username) { - return removeUser(getUser(username)); - } - + /** + * Get user by id + * + * @param userId the user id + * @return the user + */ + EzyUser getUser(long userId); + + /** + * Get user by id + * + * @param username the user name + * @return the user + */ + EzyUser getUser(String username); + + /** + * Get users as list + * + * @return The users as list + */ + List getUserList(); + + /** + * Get count of users + * + * @return count of users + */ + int getUserCount(); + + /** + * Get max users count + * + * @return the max users count + */ + int getMaxUsers(); + + /** + * available to add user or not + * + * @return available to add user or not + */ + boolean available(); + + /** + * Check whether contains user or not + * + * @param userId the user id + * @return true or false + */ + boolean containsUser(long userId); + + /** + * Check whether contains user or not + * + * @param username the user name + * @return true or false + */ + boolean containsUser(String username); + + /** + * Remove user + * + * @param user the user + * @return the current user + */ + EzyUser removeUser(EzyUser user); + + /** + * Get lock mapped to username + * + * @param username the username + * @return the lock + */ + Lock getLock(String username); + + /** + * Remove lock mapped to username + * + * @param username the username + */ + void removeLock(String username); + + /** + * clear all user + */ + void clear(); + + /** + * Check whether contains user or not + * + * @param user the user + * @return true or false + */ + default boolean containsUser(EzyUser user) { + return containsUser(user.getName()); + } + + /** + * Remove user by id + * + * @param userId the user id + * @return the current user + */ + default EzyUser removeUser(long userId) { + return removeUser(getUser(userId)); + } + + /** + * Remove user byte name + * + * @param username the user name + * @return the current user + */ + default EzyUser removeUser(String username) { + return removeUser(getUser(username)); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyZoneUserManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyZoneUserManager.java index 239216b7d..1c378587c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyZoneUserManager.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyZoneUserManager.java @@ -6,51 +6,51 @@ public interface EzyZoneUserManager extends EzyUserManager { - /** - * Add user - * - * @param session the session - * @param user the user - */ - void addUser(EzySession session, EzyUser user); - - /** + /** + * Add user + * + * @param session the session + * @param user the user + */ + void addUser(EzySession session, EzyUser user); + + /** * Add user * * @param session the session * @param user the user */ void bind(EzySession session, EzyUser user); - - /** - * Get user by id - * - * @param session the user session - * @return the user - */ - EzyUser getUser(EzySession session); - - /** - * Check whether contains user or not - * - * @param session the user session - * @return true or false - */ - boolean containsUser(EzySession session); - - /** - * Unmap session has mapped to user - * - * @param session the session - */ - void unmapSessionUser(EzySession session, EzyConstant reason); - - /** - * Remove user - * - * @param user the user - * @param reason the reason - */ - void removeUser(EzyUser user, EzyConstant reason); - + + /** + * Get user by id + * + * @param session the user session + * @return the user + */ + EzyUser getUser(EzySession session); + + /** + * Check whether contains user or not + * + * @param session the user session + * @return true or false + */ + boolean containsUser(EzySession session); + + /** + * Unmap session has mapped to user + * + * @param session the session + */ + void unmapSessionUser(EzySession session, EzyConstant reason); + + /** + * Remove user + * + * @param user the user + * @param reason the reason + */ + void removeUser(EzyUser user, EzyConstant reason); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventControllersImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventControllersImpl.java index 43758b921..c50aaa9fd 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventControllersImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventControllersImpl.java @@ -16,42 +16,42 @@ public class EzyEventControllersImpl implements EzyEventControllers { - @SuppressWarnings("rawtypes") - protected final Map> controllers - = new ConcurrentHashMap<>(); - - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes") + protected final Map> controllers + = new ConcurrentHashMap<>(); + + @SuppressWarnings("rawtypes") public static EzyEventControllers create(EzyEventControllersSetting setting) { - EzyEventControllers controllers = new EzyEventControllersImpl(); + EzyEventControllers controllers = new EzyEventControllersImpl(); for(EzyEventControllerSetting item : setting.getEventControllers()) { EzyEventType eventType = EzyEventType.valueOf(item.getEventType()); EzyEventController controller = EzyClasses.newInstance(item.getController()); controllers.addController(eventType, controller); } return controllers; - } - - @SuppressWarnings("rawtypes") - @Override - public void addController(EzyConstant eventType, EzyEventController controller) { - controllers.compute(eventType, (k, v) -> { - List list = v != null - ? new ArrayList<>(v) - : new ArrayList<>(); - list.add(controller); - return list; - }); - } - - @SuppressWarnings("rawtypes") - @Override - public List getControllers(EzyConstant eventType) { - return controllers.getOrDefault(eventType, Collections.emptyList()); - } - - @Override - public void destroy() { - controllers.clear(); - } - + } + + @SuppressWarnings("rawtypes") + @Override + public void addController(EzyConstant eventType, EzyEventController controller) { + controllers.compute(eventType, (k, v) -> { + List list = v != null + ? new ArrayList<>(v) + : new ArrayList<>(); + list.add(controller); + return list; + }); + } + + @SuppressWarnings("rawtypes") + @Override + public List getControllers(EzyConstant eventType) { + return controllers.getOrDefault(eventType, Collections.emptyList()); + } + + @Override + public void destroy() { + controllers.clear(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerControllersImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerControllersImpl.java index 43329a490..47f41f261 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerControllersImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerControllersImpl.java @@ -30,63 +30,63 @@ public class EzyServerControllersImpl implements EzyServerControllers { protected final EzyInterceptor streamingInterceptor; @Getter protected final EzyStreamingController streamingController; - protected final Map controllers; - protected final Map interceptors; - - protected EzyServerControllersImpl(Builder builder) { - this.controllers = builder.newControllers(); - this.interceptors = builder.newInterceptors(); - this.streamingInterceptor = new EzyRawBytesInterceptor(); - this.streamingController = new EzySimpleStreamingController(); - } - - @Override - public EzyController getController(EzyConstant cmd) { - EzyController controller = controllers.get(cmd); - return controller; - } - - @Override - public EzyInterceptor getInterceptor(EzyConstant cmd) { - EzyInterceptor interceptor = interceptors.get(cmd); - return interceptor; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - - protected Map newControllers() { - Map answer = new ConcurrentHashMap<>(); - answer.put(EzyCommand.PING, new EzyPingController()); - answer.put(EzyCommand.HANDSHAKE, new EzyHandshakeController()); - answer.put(EzyCommand.LOGIN, new EzyLoginController()); - answer.put(EzyCommand.APP_ACCESS, new EzyAccessAppController()); - answer.put(EzyCommand.APP_REQUEST, new EzyRequestAppController()); - answer.put(EzyCommand.APP_EXIT, new EzyExitAppController()); - answer.put(EzyCommand.PLUGIN_INFO, new EzyPluginInfoController()); - answer.put(EzyCommand.PLUGIN_REQUEST, new EzyRequestPluginController()); - return answer; - } - - protected Map newInterceptors() { - Map answer = new ConcurrentHashMap<>(); - answer.put(EzyCommand.PING, EzyInterceptor.ALWAYS_PASS); - answer.put(EzyCommand.HANDSHAKE, EzyInterceptor.ALWAYS_PASS); - answer.put(EzyCommand.LOGIN, EzyInterceptor.ALWAYS_PASS); - answer.put(EzyCommand.APP_ACCESS, new EzyServerUserInterceptor<>()); - answer.put(EzyCommand.APP_REQUEST, new EzyServerUserInterceptor<>()); - answer.put(EzyCommand.APP_EXIT, new EzyServerUserInterceptor<>()); - answer.put(EzyCommand.PLUGIN_INFO, new EzyServerUserInterceptor<>()); - answer.put(EzyCommand.PLUGIN_REQUEST, new EzyServerUserInterceptor<>()); - return answer; - } - - public EzyServerControllers build() { - return new EzyServerControllersImpl(this); - } - } + protected final Map controllers; + protected final Map interceptors; + + protected EzyServerControllersImpl(Builder builder) { + this.controllers = builder.newControllers(); + this.interceptors = builder.newInterceptors(); + this.streamingInterceptor = new EzyRawBytesInterceptor(); + this.streamingController = new EzySimpleStreamingController(); + } + + @Override + public EzyController getController(EzyConstant cmd) { + EzyController controller = controllers.get(cmd); + return controller; + } + + @Override + public EzyInterceptor getInterceptor(EzyConstant cmd) { + EzyInterceptor interceptor = interceptors.get(cmd); + return interceptor; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + protected Map newControllers() { + Map answer = new ConcurrentHashMap<>(); + answer.put(EzyCommand.PING, new EzyPingController()); + answer.put(EzyCommand.HANDSHAKE, new EzyHandshakeController()); + answer.put(EzyCommand.LOGIN, new EzyLoginController()); + answer.put(EzyCommand.APP_ACCESS, new EzyAccessAppController()); + answer.put(EzyCommand.APP_REQUEST, new EzyRequestAppController()); + answer.put(EzyCommand.APP_EXIT, new EzyExitAppController()); + answer.put(EzyCommand.PLUGIN_INFO, new EzyPluginInfoController()); + answer.put(EzyCommand.PLUGIN_REQUEST, new EzyRequestPluginController()); + return answer; + } + + protected Map newInterceptors() { + Map answer = new ConcurrentHashMap<>(); + answer.put(EzyCommand.PING, EzyInterceptor.ALWAYS_PASS); + answer.put(EzyCommand.HANDSHAKE, EzyInterceptor.ALWAYS_PASS); + answer.put(EzyCommand.LOGIN, EzyInterceptor.ALWAYS_PASS); + answer.put(EzyCommand.APP_ACCESS, new EzyServerUserInterceptor<>()); + answer.put(EzyCommand.APP_REQUEST, new EzyServerUserInterceptor<>()); + answer.put(EzyCommand.APP_EXIT, new EzyServerUserInterceptor<>()); + answer.put(EzyCommand.PLUGIN_INFO, new EzyServerUserInterceptor<>()); + answer.put(EzyCommand.PLUGIN_REQUEST, new EzyServerUserInterceptor<>()); + return answer; + } + + public EzyServerControllers build() { + return new EzyServerControllersImpl(this); + } + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyZoneUserManagerImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyZoneUserManagerImpl.java index 0d9f9a88f..1e953d0e9 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyZoneUserManagerImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyZoneUserManagerImpl.java @@ -49,73 +49,73 @@ protected ScheduledExecutorService newIdleValidationService(long maxIdleTime) { return answer; } - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#addUser(com.tvd12.ezyfoxserver.mapping.entity.EzyUser) - */ - @Override - public void addUser(EzySession session, EzyUser user) { - checkMaxUsers(); - usersById.put(user.getId(), user); - usersByName.put(user.getName(), user); - usersBySession.put(session, user); - logger.info("zone: {} add user: {}, locks.size = {}, usersById.size = {}, usersByName.size = {}", zoneName, user, locks.size(), usersById.size(), usersByName.size()); - } - - @Override - public void bind(EzySession session, EzyUser user) { - usersBySession.put(session, user); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#getUser(com.tvd12.ezyfoxserver.mapping.entity.EzySession) - */ - @Override - public EzyUser getUser(EzySession session) { - return usersBySession.get(session); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#containsUser(com.tvd12.ezyfoxserver.mapping.entity.EzySession) - */ - @Override - public boolean containsUser(EzySession session) { - return usersBySession.containsKey(session); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyServerUserManager#unmapSessionUser(com.tvd12.ezyfoxserver.mapping.entity.EzySession) - */ - @Override - public void unmapSessionUser(EzySession session, EzyConstant reason) { - EzyUser user = usersBySession.remove(session); - if(user != null) { - user.removeSession(session); - logger.debug("zone: {} remove session {} from user {} by reason {}, user remain: {} sessions, usersBySession.size: {}", zoneName, session.getClientAddress(), user, reason, user.getSessionCount(), usersBySession.size()); - if(shouldRemoveUserNow(user)) - removeUser(user, reason); - } - } - - protected boolean shouldRemoveUserNow(EzyUser user) { - int sessionCount = user.getSessionCount(); - long maxIdleTime = user.getMaxIdleTime(); - boolean should = sessionCount <= 0 && maxIdleTime <= 0; - return should; - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyServerUserManager#removeUser(com.tvd12.ezyfoxserver.mapping.entity.EzyUser, com.tvd12.ezyfoxserver.mapping.constant.EzyUserRemoveReason) - */ - @Override - public void removeUser(EzyUser user, EzyConstant reason) { - String username = user.getName(); - Lock lock = locks.computeIfAbsent(username, EzyFunctions.NEW_REENTRANT_LOCK_FUNC); - lock.lock(); + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#addUser(com.tvd12.ezyfoxserver.mapping.entity.EzyUser) + */ + @Override + public void addUser(EzySession session, EzyUser user) { + checkMaxUsers(); + usersById.put(user.getId(), user); + usersByName.put(user.getName(), user); + usersBySession.put(session, user); + logger.info("zone: {} add user: {}, locks.size = {}, usersById.size = {}, usersByName.size = {}", zoneName, user, locks.size(), usersById.size(), usersByName.size()); + } + + @Override + public void bind(EzySession session, EzyUser user) { + usersBySession.put(session, user); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#getUser(com.tvd12.ezyfoxserver.mapping.entity.EzySession) + */ + @Override + public EzyUser getUser(EzySession session) { + return usersBySession.get(session); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#containsUser(com.tvd12.ezyfoxserver.mapping.entity.EzySession) + */ + @Override + public boolean containsUser(EzySession session) { + return usersBySession.containsKey(session); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyServerUserManager#unmapSessionUser(com.tvd12.ezyfoxserver.mapping.entity.EzySession) + */ + @Override + public void unmapSessionUser(EzySession session, EzyConstant reason) { + EzyUser user = usersBySession.remove(session); + if(user != null) { + user.removeSession(session); + logger.debug("zone: {} remove session {} from user {} by reason {}, user remain: {} sessions, usersBySession.size: {}", zoneName, session.getClientAddress(), user, reason, user.getSessionCount(), usersBySession.size()); + if(shouldRemoveUserNow(user)) + removeUser(user, reason); + } + } + + protected boolean shouldRemoveUserNow(EzyUser user) { + int sessionCount = user.getSessionCount(); + long maxIdleTime = user.getMaxIdleTime(); + boolean should = sessionCount <= 0 && maxIdleTime <= 0; + return should; + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyServerUserManager#removeUser(com.tvd12.ezyfoxserver.mapping.entity.EzyUser, com.tvd12.ezyfoxserver.mapping.constant.EzyUserRemoveReason) + */ + @Override + public void removeUser(EzyUser user, EzyConstant reason) { + String username = user.getName(); + Lock lock = locks.computeIfAbsent(username, EzyFunctions.NEW_REENTRANT_LOCK_FUNC); + lock.lock(); try { removeUser0(user, reason); } @@ -123,90 +123,90 @@ public void removeUser(EzyUser user, EzyConstant reason) { lock.unlock(); locks.remove(username); } - } - - private void removeUser0(EzyUser user, EzyConstant reason) { - logger.debug("zone: {} remove user: {} by reason: {}", zoneName, user, reason); - removeUser(user); + } + + private void removeUser0(EzyUser user, EzyConstant reason) { + logger.debug("zone: {} remove user: {} by reason: {}", zoneName, user, reason); + removeUser(user); delegateUserRemove(user, reason); - } - - @Override - public void start() throws Exception { - logger.debug("start user manager for zone: {}", zoneName); - startIdleValidationService(); - } - - protected void startIdleValidationService() { - if(idleValidationService != null) { - idleValidationService.scheduleAtFixedRate( - () -> validateIdleUsers(), - idleValidationDelay, - idleValidationInterval, TimeUnit.MILLISECONDS); - } - } - - protected void validateIdleUsers() { - List toRemoveUsers = new ArrayList<>(); - for(EzyUser user : getUserList()) { - if(isIdleUser(user)) - toRemoveUsers.add(user); - } - for(EzyUser user : toRemoveUsers) - removeUser(user, EzyDisconnectReason.IDLE); - } - - protected boolean isIdleUser(EzyUser user) { - boolean idle = user.isIdle(); - return idle; - } - - protected void delegateUserRemove(EzyUser user, EzyConstant reason) { - userDelegate.onUserRemoved(user, reason); - } - - @Override - public void destroy() { - super.destroy(); - this.usersBySession.clear(); - if(idleValidationService != null) - processWithLogException(() -> idleValidationService.shutdown()); - } - - @Override - protected String getMessagePrefix() { - return "zone: " + zoneName; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyAbstractUserManager.Builder { - - protected String zoneName; - protected long maxIdleTime; - protected EzyUserDelegate userDelegate; - protected long idleValidationInterval = 100; + } + + @Override + public void start() throws Exception { + logger.debug("start user manager for zone: {}", zoneName); + startIdleValidationService(); + } + + protected void startIdleValidationService() { + if(idleValidationService != null) { + idleValidationService.scheduleAtFixedRate( + () -> validateIdleUsers(), + idleValidationDelay, + idleValidationInterval, TimeUnit.MILLISECONDS); + } + } + + protected void validateIdleUsers() { + List toRemoveUsers = new ArrayList<>(); + for(EzyUser user : getUserList()) { + if(isIdleUser(user)) + toRemoveUsers.add(user); + } + for(EzyUser user : toRemoveUsers) + removeUser(user, EzyDisconnectReason.IDLE); + } + + protected boolean isIdleUser(EzyUser user) { + boolean idle = user.isIdle(); + return idle; + } + + protected void delegateUserRemove(EzyUser user, EzyConstant reason) { + userDelegate.onUserRemoved(user, reason); + } + + @Override + public void destroy() { + super.destroy(); + this.usersBySession.clear(); + if(idleValidationService != null) + processWithLogException(() -> idleValidationService.shutdown()); + } + + @Override + protected String getMessagePrefix() { + return "zone: " + zoneName; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyAbstractUserManager.Builder { + + protected String zoneName; + protected long maxIdleTime; + protected EzyUserDelegate userDelegate; + protected long idleValidationInterval = 100; protected long idleValidationDelay = 3 * 1000; protected int idleValidationThreadPoolSize = 1; - - public Builder zoneName(String zoneName) { - this.zoneName = zoneName; - return this; - } - - public Builder maxIdleTime(long maxIdletime) { - this.maxIdleTime = maxIdletime; - return this; - } - - public Builder userDelegate(EzyUserDelegate userDelegate) { - this.userDelegate = userDelegate; - return this; - } - - public Builder idleValidationDelay(long validationDelay) { + + public Builder zoneName(String zoneName) { + this.zoneName = zoneName; + return this; + } + + public Builder maxIdleTime(long maxIdletime) { + this.maxIdleTime = maxIdletime; + return this; + } + + public Builder userDelegate(EzyUserDelegate userDelegate) { + this.userDelegate = userDelegate; + return this; + } + + public Builder idleValidationDelay(long validationDelay) { this.idleValidationDelay = validationDelay; return this; } @@ -220,12 +220,12 @@ public Builder idleValidationThreadPoolSize(int threadPoolSize) { this.idleValidationThreadPoolSize = threadPoolSize; return this; } - - @Override - public EzyZoneUserManager build() { - return new EzyZoneUserManagerImpl(this); - } - - } - + + @Override + public EzyZoneUserManager build() { + return new EzyZoneUserManagerImpl(this); + } + + } + } diff --git a/ezyfox-server-core/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index b/ezyfox-server-core/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index index 5147c168f..53badd9e0 100644 --- a/ezyfox-server-core/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index +++ b/ezyfox-server-core/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index @@ -1,2 +1,2 @@ setting.EzySimpleSettings -setting.EzySimpleZoneSetting \ No newline at end of file +setting.EzySimpleZoneSetting diff --git a/ezyfox-server-core/src/main/resources/ezy-settings-1.0.0.xsd b/ezyfox-server-core/src/main/resources/ezy-settings-1.0.0.xsd index 89440e4b4..c85270838 100644 --- a/ezyfox-server-core/src/main/resources/ezy-settings-1.0.0.xsd +++ b/ezyfox-server-core/src/main/resources/ezy-settings-1.0.0.xsd @@ -1,211 +1,211 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + xmlns="http://www.tvd12.com/schema/ezyfox/settings" elementFormDefault="qualified" attributeFormDefault="unqualified"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ezyfox-server-core/src/main/resources/ezy-settings.xml b/ezyfox-server-core/src/main/resources/ezy-settings.xml index fdfd3f864..dabb8d716 100644 --- a/ezyfox-server-core/src/main/resources/ezy-settings.xml +++ b/ezyfox-server-core/src/main/resources/ezy-settings.xml @@ -1,96 +1,96 @@ - - localhost - 30000 - - - 1 - 8 - 8 - 8 - 8 - 2 - 3 - - - - true - - - - 3005 -
0.0.0.0
- true - true - true - 4096 - 8 - com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator -
- - - 2611 -
0.0.0.0
- true - 1024 - 8 - 5 -
- - - 2208 -
0.0.0.0
- true - 2812 - 2048 - 8 - true - false - - ssl-config.properties - com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader - com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder - - com.tvd12.ezyfox.codec.JacksonCodecCreator -
- - - - admin - admin - admin - - - - - 60 - 15 - - 20 - DISCONNECT_SESSION - - - - - - SERVER_READY - com.tvd12.ezyfoxserver.handler.ServerReadyHandler - - - - - - example - ezy-zone-settings.xml - true - - - + xsi:schemaLocation="http://www.tvd12.com/schema/ezyfox/settings + ezy-settings-1.0.0.xsd" + xmlns="http://www.tvd12.com/schema/ezyfox/settings" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + + localhost + 30000 + + + 1 + 8 + 8 + 8 + 8 + 2 + 3 + + + + true + + + + 3005 +
0.0.0.0
+ true + true + true + 4096 + 8 + com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator +
+ + + 2611 +
0.0.0.0
+ true + 1024 + 8 + 5 +
+ + + 2208 +
0.0.0.0
+ true + 2812 + 2048 + 8 + true + false + + ssl-config.properties + com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader + com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder + + com.tvd12.ezyfox.codec.JacksonCodecCreator +
+ + + + admin + admin + admin + + + + + 60 + 15 + + 20 + DISCONNECT_SESSION + + + + + + SERVER_READY + com.tvd12.ezyfoxserver.handler.ServerReadyHandler + + + + + + example + ezy-zone-settings.xml + true + + +
- \ No newline at end of file + diff --git a/ezyfox-server-core/src/main/resources/ezy-zone-settings-1.0.0.xsd b/ezyfox-server-core/src/main/resources/ezy-zone-settings-1.0.0.xsd index 4a36935a6..dd13b10f9 100644 --- a/ezyfox-server-core/src/main/resources/ezy-zone-settings-1.0.0.xsd +++ b/ezyfox-server-core/src/main/resources/ezy-zone-settings-1.0.0.xsd @@ -1,155 +1,155 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + xmlns="http://www.tvd12.com/schema/ezyfox/settings" elementFormDefault="qualified" attributeFormDefault="unqualified"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ezyfox-server-core/src/main/resources/ezy-zone-settings.xml b/ezyfox-server-core/src/main/resources/ezy-zone-settings.xml index f556bbaad..b250d3462 100644 --- a/ezyfox-server-core/src/main/resources/ezy-zone-settings.xml +++ b/ezyfox-server-core/src/main/resources/ezy-zone-settings.xml @@ -1,56 +1,56 @@ - - 10000 - - - true - Guest# - 15000 - true - 15 - ^[a-zA-Z0-9_.#]{3,64}$ - - - - true - - - - - SERVER_READY - com.tvd12.ezyfoxserver.zone.handler.ServerReadyHandler - - - - - - ezyfox-chat - com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader - 10000 - 30 - config.properties - - - - - - ezyfox-auth-plugin - -1 - com.tvd12.ezyfoxserver.plugin.auth.EzyAuthPluginEntryLoader - 30 - config.properties - - USER_LOGIN - USER_ADDED - USER_REMOVED - - - + xsi:schemaLocation="http://www.tvd12.com/schema/ezyfox/settings + ezy-zone-settings-1.0.0.xsd" + xmlns="http://www.tvd12.com/schema/ezyfox/settings" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + + 10000 + + + true + Guest# + 15000 + true + 15 + ^[a-zA-Z0-9_.#]{3,64}$ + + + + true + + + + + SERVER_READY + com.tvd12.ezyfoxserver.zone.handler.ServerReadyHandler + + + + + + ezyfox-chat + com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader + 10000 + 30 + config.properties + + + + + + ezyfox-auth-plugin + -1 + com.tvd12.ezyfoxserver.plugin.auth.EzyAuthPluginEntryLoader + 30 + config.properties + + USER_LOGIN + USER_ADDED + USER_REMOVED + + + - \ No newline at end of file + diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyAppsStarterTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyAppsStarterTest.java index 8bde25a22..dc0c5058a 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyAppsStarterTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyAppsStarterTest.java @@ -103,8 +103,8 @@ public void getClassLoaderErrorCaseTest() { @Test public void newAppEntryLoaderArgsNotNullTest() { - // given - Map loaders = new ConcurrentHashMap<>(); + // given + Map loaders = new ConcurrentHashMap<>(); EzySimpleZoneContext zoneContext = EzyZoneContextsTest.newDefaultZoneContext(); EzySimpleApplication app = new EzySimpleApplication(); EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); @@ -143,8 +143,8 @@ public void newAppEntryLoaderArgsNotNullTest() { @Test public void newAppEntryLoaderClassLoaderIsNull() { - // given - Map loaders = new ConcurrentHashMap<>(); + // given + Map loaders = new ConcurrentHashMap<>(); EzySimpleZoneContext zoneContext = EzyZoneContextsTest.newDefaultZoneContext(); EzySimpleApplication app = new EzySimpleApplication(); EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); @@ -179,14 +179,14 @@ public void newAppEntryLoaderClassLoaderIsNull() { } public static class InternalAppEntryLoader implements EzyAppEntryLoader { - - public InternalAppEntryLoader(String arg) { - System.out.println(arg); - } - @Override - public EzyAppEntry load() throws Exception { - return new EzyAppEntry() {}; - } + public InternalAppEntryLoader(String arg) { + System.out.println(arg); + } + + @Override + public EzyAppEntry load() throws Exception { + return new EzyAppEntry() {}; + } } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyLoaderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyLoaderTest.java index 7615d5811..e65e00903 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyLoaderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyLoaderTest.java @@ -30,43 +30,43 @@ public void test() throws Exception { @Test public void newAppClassLoaderNotEnableClassLoader() { - // given - InternalLoader sut = new InternalLoader(); - FieldUtil.setFieldValue(sut, "classLoader", Thread.currentThread().getContextClassLoader()); - - EzyConfig config = mock(EzyConfig.class); - when(config.isEnableAppClassLoader()).thenReturn(false); - FieldUtil.setFieldValue(sut, "config", config); - - // when - ClassLoader classLoader = MethodUtil.invokeMethod("newAppClassLoader", sut, new File("")); - - // then - Asserts.assertEquals(Thread.currentThread().getContextClassLoader(), classLoader); + // given + InternalLoader sut = new InternalLoader(); + FieldUtil.setFieldValue(sut, "classLoader", Thread.currentThread().getContextClassLoader()); + + EzyConfig config = mock(EzyConfig.class); + when(config.isEnableAppClassLoader()).thenReturn(false); + FieldUtil.setFieldValue(sut, "config", config); + + // when + ClassLoader classLoader = MethodUtil.invokeMethod("newAppClassLoader", sut, new File("")); + + // then + Asserts.assertEquals(Thread.currentThread().getContextClassLoader(), classLoader); } @Test public void getEntryFoldersEmptyTest() { - // given - InternalLoader sut = new InternalLoader(); - - EzyConfig config = mock(EzyConfig.class); - when(config.isEnableAppClassLoader()).thenReturn(false); - FieldUtil.setFieldValue(sut, "config", config); - - // when - File[] folders = MethodUtil.invokeMethod("getEntryFolders", sut); - - // then - Asserts.assertEquals(new File[0], folders); + // given + InternalLoader sut = new InternalLoader(); + + EzyConfig config = mock(EzyConfig.class); + when(config.isEnableAppClassLoader()).thenReturn(false); + FieldUtil.setFieldValue(sut, "config", config); + + // when + File[] folders = MethodUtil.invokeMethod("getEntryFolders", sut); + + // then + Asserts.assertEquals(new File[0], folders); } private static class InternalLoader extends EzyLoader { - @SuppressWarnings("rawtypes") - @Override - protected Builder createSessionManagerBuilder(EzySettings settings) { - return null; - } + @SuppressWarnings("rawtypes") + @Override + protected Builder createSessionManagerBuilder(EzySettings settings) { + return null; + } } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyPluginsStarterTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyPluginsStarterTest.java index 79c7ea4f1..61e15074d 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyPluginsStarterTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyPluginsStarterTest.java @@ -56,7 +56,7 @@ public void test2() { @Test public void newAppEntryLoaderArgsNotNullTest() { - // given + // given EzySimpleZoneContext zoneContext = EzyZoneContextsTest.newDefaultZoneContext(); EzySimplePlugin plugin = new EzySimplePlugin(); EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); @@ -91,14 +91,14 @@ public void newAppEntryLoaderArgsNotNullTest() { } public static class InternalPluginEntryLoader implements EzyPluginEntryLoader { - - public InternalPluginEntryLoader(String arg) { - System.out.println(arg); - } - @Override - public EzyPluginEntry load() throws Exception { - return new EzyPluginEntry() {}; - } + public InternalPluginEntryLoader(String arg) { + System.out.println(arg); + } + + @Override + public EzyPluginEntry load() throws Exception { + return new EzyPluginEntry() {}; + } } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyRunnerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyRunnerTest.java index 3f8cd89eb..579a82e5a 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyRunnerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyRunnerTest.java @@ -17,27 +17,27 @@ public void test() throws Exception { @Test public void testWithNoArg() throws Exception { try { - EzyRunner runner = new MyTestRunner() { - protected void validateArguments(String[] args) {}; + EzyRunner runner = new MyTestRunner() { + protected void validateArguments(String[] args) {}; }; runner.run(new String[0]); } catch (Exception e) { - e.printStackTrace(); - } + e.printStackTrace(); + } } @Test - public void test1() throws Exception { - try { - EzyRunner runner = new MyTestRunner(); - runner.run(new String[] {"test-data/settings/config.properties"}); - Asserts.assertNotNull(runner.getServerContext()); - } - catch (Exception e) { - e.printStackTrace(); - throw e; + public void test1() throws Exception { + try { + EzyRunner runner = new MyTestRunner(); + runner.run(new String[] {"test-data/settings/config.properties"}); + Asserts.assertNotNull(runner.getServerContext()); } - } + catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerBootstrapTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerBootstrapTest.java index 0b2716e46..ee214a2ec 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerBootstrapTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerBootstrapTest.java @@ -71,19 +71,19 @@ protected void startOtherBootstraps(Runnable callback) throws Exception { @Test public void commonTest() throws Exception { - // given - EzySimpleConfig config = new EzySimpleConfig(); - config.setPrintBanner(false); - - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setConfig(config); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyServerBootstrap sut = new EzyServerBootstrap() { + // given + EzySimpleConfig config = new EzySimpleConfig(); + config.setPrintBanner(false); + + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setConfig(config); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyServerBootstrap sut = new EzyServerBootstrap() { @Override protected void startOtherBootstraps(Runnable callback) throws Exception { callback.run(); @@ -94,9 +94,9 @@ protected void startOtherBootstraps(Runnable callback) throws Exception { // when ReflectMethodUtil.invokeMethod("printBanner", sut); EzyUdpSetting udpSetting = - (EzyUdpSetting) ReflectMethodUtil.invokeMethod("getUdpSetting", sut); + (EzyUdpSetting) ReflectMethodUtil.invokeMethod("getUdpSetting", sut); EzyThreadPoolSizeSetting threadPoolSizeSetting = - (EzyThreadPoolSizeSetting) ReflectMethodUtil.invokeMethod("getThreadPoolSizeSetting", sut); + (EzyThreadPoolSizeSetting) ReflectMethodUtil.invokeMethod("getThreadPoolSizeSetting", sut); // then Asserts.assertEquals(server.getSettings().getUdp(), udpSetting); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySettingsReaderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySettingsReaderTest.java index 8bd5add03..f6e430e75 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySettingsReaderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySettingsReaderTest.java @@ -12,20 +12,20 @@ public class EzySettingsReaderTest { - @Test - public void test() throws Exception { -// JAXBContext jaxbContext = JAXBContext.newInstance(EzyFoxSettings.class); - JAXBContext jaxbContext = JAXBContext.newInstance("com.tvd12.ezyfoxserver", getClass().getClassLoader()); - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - EzySimpleSettings settings = jaxbUnmarshaller - .unmarshal(new StreamSource(inputStream()), EzySimpleSettings.class).getValue(); - System.out.println(settings); - } - - private InputStream inputStream() { - return getClass().getClassLoader() - .getResourceAsStream("ezy-settings.xml"); - } - - + @Test + public void test() throws Exception { +// JAXBContext jaxbContext = JAXBContext.newInstance(EzyFoxSettings.class); + JAXBContext jaxbContext = JAXBContext.newInstance("com.tvd12.ezyfoxserver", getClass().getClassLoader()); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + EzySimpleSettings settings = jaxbUnmarshaller + .unmarshal(new StreamSource(inputStream()), EzySimpleSettings.class).getValue(); + System.out.println(settings); + } + + private InputStream inputStream() { + return getClass().getClassLoader() + .getResourceAsStream("ezy-settings.xml"); + } + + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleApplicationTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleApplicationTest.java index 3992c9b34..e4b5a5e73 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleApplicationTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleApplicationTest.java @@ -13,7 +13,7 @@ public class EzySimpleApplicationTest extends BaseTest { @Test public void test() { - EzySimpleApplication app = new EzySimpleApplication(); + EzySimpleApplication app = new EzySimpleApplication(); EzySimpleAppSetting setting = new EzySimpleAppSetting(); app.setSetting(setting); assert app.equals(app); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleZoneTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleZoneTest.java index cfbc6355d..e43a458fb 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleZoneTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySimpleZoneTest.java @@ -8,13 +8,13 @@ public class EzySimpleZoneTest extends BaseTest { - @Test - public void test() { - EzySimpleZone zone = new EzySimpleZone(); - EzySimpleZoneSetting setting = new EzySimpleZoneSetting(); - zone.setSetting(setting); - assert zone.equals(zone); - assert !zone.equals(new EzySimpleZone()); - } - + @Test + public void test() { + EzySimpleZone zone = new EzySimpleZone(); + EzySimpleZoneSetting setting = new EzySimpleZoneSetting(); + zone.setSetting(setting); + assert zone.equals(zone); + assert !zone.equals(new EzySimpleZone()); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyStarterTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyStarterTest.java index 5c757e55d..fa51b3a2a 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyStarterTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyStarterTest.java @@ -30,28 +30,28 @@ public void normalCaseTest() throws Exception { @Test public void notPrintSettings() { - // given - EzyStarter starter = new ExEzyStarter.Builder() + // given + EzyStarter starter = new ExEzyStarter.Builder() .build(); - - EzyConfig config = mock(EzyConfig.class); - when(config.isPrintSettings()).thenReturn(false); - - EzySimpleServer server = new EzySimpleServer(); - server.setConfig(config); - - EzySimpleSettings settings = new EzySimpleSettings(); - server.setSettings(settings); - - // when - MethodInvoker.create() - .object(starter) - .method("startEzyFox") - .param(EzyServer.class, server) - .call(); - - // then - verify(config, times(1)).isPrintSettings(); + + EzyConfig config = mock(EzyConfig.class); + when(config.isPrintSettings()).thenReturn(false); + + EzySimpleServer server = new EzySimpleServer(); + server.setConfig(config); + + EzySimpleSettings settings = new EzySimpleSettings(); + server.setSettings(settings); + + // when + MethodInvoker.create() + .object(starter) + .method("startEzyFox") + .param(EzyServer.class, server) + .call(); + + // then + verify(config, times(1)).isPrintSettings(); } public static class ExEzyStarter extends EzyStarter { diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestRunner.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestRunner.java index a1ccd9867..68fc84732 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestRunner.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestRunner.java @@ -5,9 +5,9 @@ public class MyTestRunner extends EzyRunner { - @Override - protected Builder newStarterBuilder() { - return MyTestStarter.builder(); - } - -} \ No newline at end of file + @Override + protected Builder newStarterBuilder() { + return MyTestStarter.builder(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrapBuilder.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrapBuilder.java index b2f5b0d95..a50a25676 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrapBuilder.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrapBuilder.java @@ -5,9 +5,9 @@ public class MyTestServerBootstrapBuilder extends EzyAbtractServerBootstrapBuilder { - @Override - protected EzyServerBootstrap newServerBootstrap() { - return new MyTestServerBootstrap(); - } - + @Override + protected EzyServerBootstrap newServerBootstrap() { + return new MyTestServerBootstrap(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionManager.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionManager.java index 2956f4500..c1cefcf72 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionManager.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionManager.java @@ -34,9 +34,9 @@ public MyTestSessionManager build() { @Override protected EzyObjectFactory newObjectFactory() { return new EzyAbstractSessionFactory() { - { - maxRequestPerSecond = new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond(); - } + { + maxRequestPerSecond = new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond(); + } @Override protected MyTestSession newSession() { return new MyTestSession(); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestStarter.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestStarter.java index 95c18677d..e68026863 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestStarter.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestStarter.java @@ -12,34 +12,34 @@ public class MyTestStarter extends EzyStarter { - protected MyTestStarter(Builder builder) { - super(builder); - } - - @Override - protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { - return new MyTestServerBootstrapBuilder(); - } - - @SuppressWarnings({ "rawtypes" }) + protected MyTestStarter(Builder builder) { + super(builder); + } + + @Override + protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { + return new MyTestServerBootstrapBuilder(); + } + + @SuppressWarnings({ "rawtypes" }) @Override protected EzySimpleSessionManager.Builder newSessionManagerBuilder(EzySettings settings) { return new ExSessionManager.SBuilder(); } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyStarter.Builder { - @Override - public EzyStarter build() { - return new MyTestStarter(this); - } - } - - public static class ExSessionManager extends EzySimpleSessionManager { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyStarter.Builder { + @Override + public EzyStarter build() { + return new MyTestStarter(this); + } + } + + public static class ExSessionManager extends EzySimpleSessionManager { protected ExSessionManager(SBuilder builder) { super(builder); @@ -62,10 +62,10 @@ public ExSession newProduct() { }; } } - - } - - public static class ExSession extends EzyAbstractSession { + + } + + public static class ExSession extends EzyAbstractSession { private static final long serialVersionUID = 2019546923661465393L; @Override @@ -85,7 +85,7 @@ public void close() { @Override public void disconnect(EzyConstant disconnectReason) { } - - } + + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/Performance3Test.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/Performance3Test.java index eb740a372..e2efb16a6 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/Performance3Test.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/Performance3Test.java @@ -13,24 +13,24 @@ public class Performance3Test extends BaseTest { - @SuppressWarnings("unused") - public static void main(String args[]) { - System.out.println("\n========= begin =========\n"); - long start = System.currentTimeMillis(); - ConcurrentHashMap strs = new ConcurrentHashMap<>(); - strs.put(EzyCommand.class, EzyObject.class); - strs.put(EzyObject.class, EzyObject.class); - strs.put(EzyArray.class, EzyObject.class); - strs.put(EzySimpleAppSetting.class, EzyObject.class); - strs.put(EzySimpleServer.class, EzyObject.class); - strs.put(EzyLoggable.class, EzyObject.class); - strs.put(EzyClasses.class, EzyObject.class); - for(int i = 0 ; i < 10000000 ; ++i) { - Object abc = strs.get(EzyLoggable.class); - } - long end = System.currentTimeMillis(); - System.out.println("time = " + (end - start)); - System.out.println("\n========= end =========\n"); - } - + @SuppressWarnings("unused") + public static void main(String args[]) { + System.out.println("\n========= begin =========\n"); + long start = System.currentTimeMillis(); + ConcurrentHashMap strs = new ConcurrentHashMap<>(); + strs.put(EzyCommand.class, EzyObject.class); + strs.put(EzyObject.class, EzyObject.class); + strs.put(EzyArray.class, EzyObject.class); + strs.put(EzySimpleAppSetting.class, EzyObject.class); + strs.put(EzySimpleServer.class, EzyObject.class); + strs.put(EzyLoggable.class, EzyObject.class); + strs.put(EzyClasses.class, EzyObject.class); + for(int i = 0 ; i < 10000000 ; ++i) { + Object abc = strs.get(EzyLoggable.class); + } + long end = System.currentTimeMillis(); + System.out.println("time = " + (end - start)); + System.out.println("\n========= end =========\n"); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyAbstractResponseApiTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyAbstractResponseApiTest.java index 27224be43..ff6730733 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyAbstractResponseApiTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyAbstractResponseApiTest.java @@ -17,73 +17,73 @@ public class EzyAbstractResponseApiTest { - @Test - public void secureResponseNoRecipients() { - // given - EzyPackage packet = mock(EzyPackage.class); - when(packet.getRecipients(EzyConnectionType.SOCKET)).thenReturn(Collections.emptyList()); - - InternalResponseApi sut = new InternalResponseApi(); - - // when - MethodInvoker.create() - .object(sut) - .method("secureResponse") - .param(EzyPackage.class, packet) - .param(boolean.class, true) - .invoke(); - - // then - verify(packet, times(1)).getRecipients(EzyConnectionType.SOCKET); - } - - @Test - public void dataToMessageContentTest() { - // given - EzyArray data = EzyEntityFactory.EMPTY_ARRAY; - - InternalResponseApi sut = new InternalResponseApi(); - - // when - Throwable e = Asserts.assertThrows(() -> - MethodInvoker.create() - .object(sut) - .method("dataToMessageContent") - .param(EzyArray.class, data) - .invoke() - ); - - // then - Asserts.assertEquals(UnsupportedOperationException.class, e.getCause().getCause().getClass()); - } - - @Test - public void encrypteMessageContentTest() { - // given - byte[] messageContent = new byte[0]; - byte[] encryptionKey = new byte[0]; - - InternalResponseApi sut = new InternalResponseApi(); - - // when - Throwable e = Asserts.assertThrows(() -> - MethodUtil.invokeMethod("encrypteMessageContent", sut, messageContent, encryptionKey)); - - // then - Asserts.assertEquals(UnsupportedOperationException.class, e.getCause().getCause().getClass()); - } - - private static class InternalResponseApi extends EzyAbstractResponseApi { - - @Override - protected EzyConstant getConnectionType() { - return EzyConnectionType.SOCKET; - } - - @Override - protected Object encodeData(EzyArray data) throws Exception { - return null; - } - - } + @Test + public void secureResponseNoRecipients() { + // given + EzyPackage packet = mock(EzyPackage.class); + when(packet.getRecipients(EzyConnectionType.SOCKET)).thenReturn(Collections.emptyList()); + + InternalResponseApi sut = new InternalResponseApi(); + + // when + MethodInvoker.create() + .object(sut) + .method("secureResponse") + .param(EzyPackage.class, packet) + .param(boolean.class, true) + .invoke(); + + // then + verify(packet, times(1)).getRecipients(EzyConnectionType.SOCKET); + } + + @Test + public void dataToMessageContentTest() { + // given + EzyArray data = EzyEntityFactory.EMPTY_ARRAY; + + InternalResponseApi sut = new InternalResponseApi(); + + // when + Throwable e = Asserts.assertThrows(() -> + MethodInvoker.create() + .object(sut) + .method("dataToMessageContent") + .param(EzyArray.class, data) + .invoke() + ); + + // then + Asserts.assertEquals(UnsupportedOperationException.class, e.getCause().getCause().getClass()); + } + + @Test + public void encrypteMessageContentTest() { + // given + byte[] messageContent = new byte[0]; + byte[] encryptionKey = new byte[0]; + + InternalResponseApi sut = new InternalResponseApi(); + + // when + Throwable e = Asserts.assertThrows(() -> + MethodUtil.invokeMethod("encrypteMessageContent", sut, messageContent, encryptionKey)); + + // then + Asserts.assertEquals(UnsupportedOperationException.class, e.getCause().getCause().getClass()); + } + + private static class InternalResponseApi extends EzyAbstractResponseApi { + + @Override + protected EzyConstant getConnectionType() { + return EzyConnectionType.SOCKET; + } + + @Override + protected Object encodeData(EzyArray data) throws Exception { + return null; + } + + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzySocketResponseApiTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzySocketResponseApiTest.java index dd9d065c0..d03b61bbc 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzySocketResponseApiTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzySocketResponseApiTest.java @@ -21,99 +21,99 @@ import com.tvd12.test.util.RandomUtil; public class EzySocketResponseApiTest { - - @Test - public void normalResponseTest() throws Exception { - // given - EzyArray data = EzyEntityFactory.EMPTY_ARRAY; - EzyObjectToByteEncoder encoder = mock(EzyObjectToByteEncoder.class); - byte[] bytes = RandomUtil.randomShortByteArray(); - when(encoder.encode(data)).thenReturn(bytes); - EzySocketResponseApi sut = new EzySocketResponseApi(encoder); - - EzySimplePackage pack = new EzySimplePackage(); + + @Test + public void normalResponseTest() throws Exception { + // given + EzyArray data = EzyEntityFactory.EMPTY_ARRAY; + EzyObjectToByteEncoder encoder = mock(EzyObjectToByteEncoder.class); + byte[] bytes = RandomUtil.randomShortByteArray(); + when(encoder.encode(data)).thenReturn(bytes); + EzySocketResponseApi sut = new EzySocketResponseApi(encoder); + + EzySimplePackage pack = new EzySimplePackage(); pack.setData(data); pack.setEncrypted(false); pack.setTransportType(EzyTransportType.TCP); int sessionCount = RandomUtil.randomSmallInt() + 1; List sessions = RandomUtil.randomList(sessionCount, () -> { - EzySession session = mock(EzySession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - return session; + EzySession session = mock(EzySession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + return session; }); pack.addRecipients(sessions); - - - // when - sut.response(pack); - - // then - verify(encoder, times(1)).encode(data); - verify(encoder, times(0)).toMessageContent(data); - verify(encoder, times(0)).encryptMessageContent(any(byte[].class), any(byte[].class)); - } - - - @Test - public void secureResponseTest() throws Exception { - // given - EzyArray data = EzyEntityFactory.EMPTY_ARRAY; - byte[] bytes = RandomUtil.randomShortByteArray(); - EzyObjectToByteEncoder encoder = mock(EzyObjectToByteEncoder.class); - when(encoder.toMessageContent(data)).thenReturn(bytes); - EzySocketResponseApi sut = new EzySocketResponseApi(encoder); - - EzySimplePackage pack = new EzySimplePackage(); + + + // when + sut.response(pack); + + // then + verify(encoder, times(1)).encode(data); + verify(encoder, times(0)).toMessageContent(data); + verify(encoder, times(0)).encryptMessageContent(any(byte[].class), any(byte[].class)); + } + + + @Test + public void secureResponseTest() throws Exception { + // given + EzyArray data = EzyEntityFactory.EMPTY_ARRAY; + byte[] bytes = RandomUtil.randomShortByteArray(); + EzyObjectToByteEncoder encoder = mock(EzyObjectToByteEncoder.class); + when(encoder.toMessageContent(data)).thenReturn(bytes); + EzySocketResponseApi sut = new EzySocketResponseApi(encoder); + + EzySimplePackage pack = new EzySimplePackage(); pack.setData(data); pack.setEncrypted(true); pack.setTransportType(EzyTransportType.TCP); int sessionCount = RandomUtil.randomSmallInt() + 1; List sessions = RandomUtil.randomList(sessionCount, () -> { - EzySession session = mock(EzySession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - return session; + EzySession session = mock(EzySession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + return session; }); pack.addRecipients(sessions); - - - // when - sut.response(pack); - - // then - verify(encoder, times(1)).toMessageContent(data); - verify(encoder, times(sessionCount)).encryptMessageContent(any(byte[].class), any(byte[].class)); - } - - @Test - public void secureResponseImmediateTest() throws Exception { - // given - EzyArray data = EzyEntityFactory.EMPTY_ARRAY; - byte[] bytes = RandomUtil.randomShortByteArray(); - EzyObjectToByteEncoder encoder = mock(EzyObjectToByteEncoder.class); - when(encoder.toMessageContent(data)).thenReturn(bytes); - EzySocketResponseApi sut = new EzySocketResponseApi(encoder); - - EzySimplePackage pack = new EzySimplePackage(); + + + // when + sut.response(pack); + + // then + verify(encoder, times(1)).toMessageContent(data); + verify(encoder, times(sessionCount)).encryptMessageContent(any(byte[].class), any(byte[].class)); + } + + @Test + public void secureResponseImmediateTest() throws Exception { + // given + EzyArray data = EzyEntityFactory.EMPTY_ARRAY; + byte[] bytes = RandomUtil.randomShortByteArray(); + EzyObjectToByteEncoder encoder = mock(EzyObjectToByteEncoder.class); + when(encoder.toMessageContent(data)).thenReturn(bytes); + EzySocketResponseApi sut = new EzySocketResponseApi(encoder); + + EzySimplePackage pack = new EzySimplePackage(); pack.setData(data); pack.setEncrypted(true); pack.setTransportType(EzyTransportType.TCP); int sessionCount = RandomUtil.randomSmallInt() + 1; List sessions = RandomUtil.randomList(sessionCount, () -> { - EzySession session = mock(EzySession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - return session; + EzySession session = mock(EzySession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + return session; }); pack.addRecipients(sessions); - - - // when - sut.response(pack, true); - - // then - verify(encoder, times(1)).toMessageContent(data); - verify(encoder, times(sessionCount)).encryptMessageContent(any(byte[].class), any(byte[].class)); - } + + + // when + sut.response(pack, true); + + // then + verify(encoder, times(1)).toMessageContent(data); + verify(encoder, times(sessionCount)).encryptMessageContent(any(byte[].class), any(byte[].class)); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyWsResponseApiTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyWsResponseApiTest.java index a0a35e60b..a17eb801e 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyWsResponseApiTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/api/EzyWsResponseApiTest.java @@ -22,34 +22,34 @@ public class EzyWsResponseApiTest { - @Test - public void responseTest() throws Exception { - // given - EzyObjectToStringEncoder encoder = mock(EzyObjectToStringEncoder.class); - EzyWsResponseApi sut = new EzyWsResponseApi(encoder); - - EzyArray data = EzyEntityFactory.EMPTY_ARRAY; - EzySimplePackage pack = new EzySimplePackage(); + @Test + public void responseTest() throws Exception { + // given + EzyObjectToStringEncoder encoder = mock(EzyObjectToStringEncoder.class); + EzyWsResponseApi sut = new EzyWsResponseApi(encoder); + + EzyArray data = EzyEntityFactory.EMPTY_ARRAY; + EzySimplePackage pack = new EzySimplePackage(); pack.setData(data); pack.setEncrypted(true); pack.setTransportType(EzyTransportType.TCP); int sessionCount = RandomUtil.randomSmallInt() + 1; List sessions = RandomUtil.randomList(sessionCount, () -> { - EzySession session = mock(EzySession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); - return session; + EzySession session = mock(EzySession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); + return session; }); pack.addRecipients(sessions); - - - // when - sut.response(pack); - - // then - verify(encoder, times(1)).encode(data, String.class); - verify(encoder, times(0)).toMessageContent(data); - verify(encoder, times(0)).encryptMessageContent(any(byte[].class), any(byte[].class)); - } - + + + // when + sut.response(pack); + + // then + verify(encoder, times(1)).encode(data, String.class); + verify(encoder, times(0)).toMessageContent(data); + verify(encoder, times(0)).encryptMessageContent(any(byte[].class), any(byte[].class)); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/builder/EzyAbtractServerBootstrapBuilderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/builder/EzyAbtractServerBootstrapBuilderTest.java index ee2da7732..a6ad5d610 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/builder/EzyAbtractServerBootstrapBuilderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/builder/EzyAbtractServerBootstrapBuilderTest.java @@ -54,44 +54,44 @@ public void test() { @Test public void commonTest() { - // given - EzySimpleServer server = newServer(); + // given + EzySimpleServer server = newServer(); MyTestServerBootstrapBuilder builder = (MyTestServerBootstrapBuilder) new MyTestServerBootstrapBuilder() .server(server); - - // when + + // when EzyUdpSetting udpSetting = - (EzyUdpSetting) ReflectMethodUtil.invokeMethod("getUdpSetting", builder); + (EzyUdpSetting) ReflectMethodUtil.invokeMethod("getUdpSetting", builder); EzyThreadPoolSizeSetting threadPoolSizeSetting = - (EzyThreadPoolSizeSetting) ReflectMethodUtil.invokeMethod("getThreadPoolSizeSetting", builder); - - // then + (EzyThreadPoolSizeSetting) ReflectMethodUtil.invokeMethod("getThreadPoolSizeSetting", builder); + + // then Asserts.assertEquals(server.getSettings().getUdp(), udpSetting); Asserts.assertEquals(server.getSettings().getThreadPoolSize(), threadPoolSizeSetting); } @Test public void newSslContextTest() { - // given - EzySimpleServer server = newServer(); - EzySimpleWebSocketSetting webSocketSetting = - (EzySimpleWebSocketSetting)server.getSettings().getWebsocket(); - webSocketSetting.setSslActive(true); - - MyTestServerBootstrapBuilder builder = - (MyTestServerBootstrapBuilder) new MyTestServerBootstrapBuilder() - .server(server); - - EzySimpleSslConfigSetting setting = new EzySimpleSslConfigSetting(); + // given + EzySimpleServer server = newServer(); + EzySimpleWebSocketSetting webSocketSetting = + (EzySimpleWebSocketSetting)server.getSettings().getWebsocket(); + webSocketSetting.setSslActive(true); + + MyTestServerBootstrapBuilder builder = + (MyTestServerBootstrapBuilder) new MyTestServerBootstrapBuilder() + .server(server); + + EzySimpleSslConfigSetting setting = new EzySimpleSslConfigSetting(); + + // when + SSLContext sslContext = MethodInvoker.create() + .object(builder) + .method("newSslContext") + .param(EzySslConfigSetting.class, setting) + .invoke(SSLContext.class); - // when - SSLContext sslContext = MethodInvoker.create() - .object(builder) - .method("newSslContext") - .param(EzySslConfigSetting.class, setting) - .invoke(SSLContext.class); - - Asserts.assertNotNull(sslContext); + Asserts.assertNotNull(sslContext); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAbstractResponseTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAbstractResponseTest.java index 95047f2ac..3f79b8e15 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAbstractResponseTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAbstractResponseTest.java @@ -14,48 +14,48 @@ public class EzyAbstractResponseTest { - @Test - public void encryptedTest() { - // given - EzyZoneChildContext context = mock(EzyZoneChildContext.class); - InternalResponse sut = new InternalResponse(context); - - // when - sut.encrypted(); - - // then - Asserts.assertTrue(FieldUtil.getFieldValue(sut, "encrypted")); - } - - @Test - public void encryptedSetTest() { - // given - EzyZoneChildContext context = mock(EzyZoneChildContext.class); - InternalResponse sut = new InternalResponse(context); - - // when - sut.encrypted(true); - - // then - Asserts.assertTrue(FieldUtil.getFieldValue(sut, "encrypted")); - } - - @SuppressWarnings("rawtypes") - private static class InternalResponse extends EzyAbstractResponse { - - @SuppressWarnings("unchecked") - public InternalResponse(EzyZoneChildContext context) { - super(context); - } - - @Override - protected EzyUserManager getUserManager(EzyZoneChildContext context) { - return null; - } - - @Override - protected void sendData(EzyData data, EzyTransportType transportType) { - } - - } + @Test + public void encryptedTest() { + // given + EzyZoneChildContext context = mock(EzyZoneChildContext.class); + InternalResponse sut = new InternalResponse(context); + + // when + sut.encrypted(); + + // then + Asserts.assertTrue(FieldUtil.getFieldValue(sut, "encrypted")); + } + + @Test + public void encryptedSetTest() { + // given + EzyZoneChildContext context = mock(EzyZoneChildContext.class); + InternalResponse sut = new InternalResponse(context); + + // when + sut.encrypted(true); + + // then + Asserts.assertTrue(FieldUtil.getFieldValue(sut, "encrypted")); + } + + @SuppressWarnings("rawtypes") + private static class InternalResponse extends EzyAbstractResponse { + + @SuppressWarnings("unchecked") + public InternalResponse(EzyZoneChildContext context) { + super(context); + } + + @Override + protected EzyUserManager getUserManager(EzyZoneChildContext context) { + return null; + } + + @Override + protected void sendData(EzyData data, EzyTransportType transportType) { + } + + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyPluginSetupImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyPluginSetupImplTest.java index c4cdea752..d17f811df 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyPluginSetupImplTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyPluginSetupImplTest.java @@ -27,22 +27,22 @@ public void handle(EzyPluginContext ctx, EzyUserRequestPluginEvent event) { } @SuppressWarnings("rawtypes") - @Test + @Test public void addEventControllerTest() { - // given - EzySimplePlugin plugin = new EzySimplePlugin(); - - EzyEventControllers eventControllers = mock(EzyEventControllers.class); - plugin.setEventControllers(eventControllers); - - EzyPluginSetupImpl sut = new EzyPluginSetupImpl(plugin); - EzyEventController controller = mock(EzyEventController.class); - - - // when - sut.addEventController(EzyEventType.SERVER_INITIALIZING, controller); - - // then - verify(eventControllers, times(1)).addController(EzyEventType.SERVER_INITIALIZING, controller); + // given + EzySimplePlugin plugin = new EzySimplePlugin(); + + EzyEventControllers eventControllers = mock(EzyEventControllers.class); + plugin.setEventControllers(eventControllers); + + EzyPluginSetupImpl sut = new EzyPluginSetupImpl(plugin); + EzyEventController controller = mock(EzyEventController.class); + + + // when + sut.addEventController(EzyEventType.SERVER_INITIALIZING, controller); + + // then + verify(eventControllers, times(1)).addController(EzyEventType.SERVER_INITIALIZING, controller); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzySendResponseImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzySendResponseImplTest.java index 48b092a2c..ddb8cd97e 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzySendResponseImplTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzySendResponseImplTest.java @@ -42,7 +42,7 @@ public void responseOneSuccessCaseTest() { @Test public void responseOneSuccessButNotDebug() throws Exception { - // given + // given EzySimpleSettings settings = new EzySimpleSettings(); settings.setDebug(false); EzyResponseApi responseApi = spy(EzyAbstractResponseApi.class); @@ -62,7 +62,7 @@ public void responseOneSuccessButNotDebug() throws Exception { @Test public void responseOneSuccessButIsPong() throws Exception { - // given + // given EzySimpleSettings settings = new EzySimpleSettings(); settings.setDebug(true); EzyResponseApi responseApi = spy(EzyAbstractResponseApi.class); @@ -97,7 +97,7 @@ public void responseOneExceptionCase() throws Exception { @Test public void responseMultiSuccessCase() throws Exception { - // when + // when EzySimpleSettings settings = new EzySimpleSettings(); settings.setDebug(true); EzyResponseApi responseApi = mock(EzyResponseApi.class); @@ -118,7 +118,7 @@ public void responseMultiSuccessCase() throws Exception { @Test public void responseMultiSuccessCaseButNotDebug() throws Exception { - // when + // when EzySimpleSettings settings = new EzySimpleSettings(); settings.setDebug(false); EzyResponseApi responseApi = mock(EzyResponseApi.class); @@ -139,7 +139,7 @@ public void responseMultiSuccessCaseButNotDebug() throws Exception { @Test public void responseMultiSuccessCaseButIsPong() throws Exception { - // when + // when EzySimpleSettings settings = new EzySimpleSettings(); settings.setDebug(true); EzyResponseApi responseApi = mock(EzyResponseApi.class); @@ -160,7 +160,7 @@ public void responseMultiSuccessCaseButIsPong() throws Exception { @Test public void responseMultiErrorTest() throws Exception { - // given + // given EzySimpleSettings settings = new EzySimpleSettings(); settings.setDebug(true); EzyResponseApi responseApi = mock(EzyResponseApi.class); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyConfigTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyConfigTest.java index b00263dcf..cd5a9f911 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyConfigTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyConfigTest.java @@ -18,17 +18,17 @@ public void test() { @Test public void getEzyfoxHomeTest() { - // given - EzySimpleConfig sut = EzySimpleConfig.defaultConfig(); - sut.setEzyfoxHome(null); - sut.setLoggerConfigFile(null); - - // when - String home = sut.getEzyfoxHome(); - - // then - Asserts.assertEquals("", home); - System.out.println(sut.toMap()); + // given + EzySimpleConfig sut = EzySimpleConfig.defaultConfig(); + sut.setEzyfoxHome(null); + sut.setLoggerConfigFile(null); + + // when + String home = sut.getEzyfoxHome(); + + // then + Asserts.assertEquals("", home); + System.out.println(sut.toMap()); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzySimpleConfigLoaderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzySimpleConfigLoaderTest.java index 3085c28d5..c0c8a2fc7 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzySimpleConfigLoaderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzySimpleConfigLoaderTest.java @@ -9,16 +9,16 @@ public class EzySimpleConfigLoaderTest { - @Test - public void loadFilePathNullTest() { - // given - EzySimpleConfigLoader sut = new EzySimpleConfigLoader(); - - // when - EzyConfig config = sut.load(null); - - // then - Asserts.assertEquals(EzySimpleConfig.defaultConfig(), config); - } - + @Test + public void loadFilePathNullTest() { + // given + EzySimpleConfigLoader sut = new EzySimpleConfigLoader(); + + // when + EzyConfig config = sut.load(null); + + // then + Asserts.assertEquals(EzySimpleConfig.defaultConfig(), config); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyAccessAppErrorTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyAccessAppErrorTest.java index 3531e2c4e..86000942c 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyAccessAppErrorTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyAccessAppErrorTest.java @@ -6,9 +6,9 @@ public class EzyAccessAppErrorTest { - @Test - public void test() { - System.out.println(EzyAccessAppError.MAXIMUM_USER.getName()); - } - + @Test + public void test() { + System.out.println(EzyAccessAppError.MAXIMUM_USER.getName()); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyMaxRequestPerSecondActionTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyMaxRequestPerSecondActionTest.java index cbeda642d..76f805e55 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyMaxRequestPerSecondActionTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyMaxRequestPerSecondActionTest.java @@ -7,10 +7,10 @@ public class EzyMaxRequestPerSecondActionTest extends BaseTest { - @Test - public void test() { - assert EzyMaxRequestPerSecondAction.DROP_REQUEST.getId() == 1; - System.out.print(EzyMaxRequestPerSecondAction.DISCONNECT_SESSION.getName()); - } - + @Test + public void test() { + assert EzyMaxRequestPerSecondAction.DROP_REQUEST.getId() == 1; + System.out.print(EzyMaxRequestPerSecondAction.DISCONNECT_SESSION.getName()); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzySessionErrorTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzySessionErrorTest.java index 04c13ff54..5a15f0864 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzySessionErrorTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzySessionErrorTest.java @@ -6,9 +6,9 @@ public class EzySessionErrorTest { - @Test - public void test() { - System.out.println(EzySessionError.MAX_REQUEST_PER_SECOND.getName()); - } - + @Test + public void test() { + System.out.println(EzySessionError.MAX_REQUEST_PER_SECOND.getName()); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyTransportTypeTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyTransportTypeTest.java index 886e1aa81..7bb7dd641 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyTransportTypeTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyTransportTypeTest.java @@ -7,10 +7,10 @@ public class EzyTransportTypeTest extends BaseTest { - @Test - public void test() { - assert EzyTransportType.TCP.getId() == 1; - System.out.println(EzyTransportType.UDP.getName()); - } - + @Test + public void test() { + assert EzyTransportType.TCP.getId() == 1; + System.out.println(EzyTransportType.UDP.getName()); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzyAbstractContextTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzyAbstractContextTest.java index 2080532b0..aab08d0a6 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzyAbstractContextTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzyAbstractContextTest.java @@ -9,41 +9,41 @@ public class EzyAbstractContextTest { - @Test - public void destroyTest() { - // given - A a = new A(); - B b = new B(); - InternalContext sut = new InternalContext(); - sut.init(); - sut.setProperty("a", a); - sut.setProperty("b", b); - - // when - sut.destroy(); - - // then - Asserts.assertTrue(a.stopped); - Asserts.assertTrue(b.destroy); - } - - private static class A implements EzyStoppable { - private boolean stopped; - - @Override - public void stop() { - this.stopped = true; - } - } - - public static class B implements EzyDestroyable { - private boolean destroy; - - @Override - public void destroy() { - this.destroy = true; - } - } - - private static class InternalContext extends EzyAbstractContext {} + @Test + public void destroyTest() { + // given + A a = new A(); + B b = new B(); + InternalContext sut = new InternalContext(); + sut.init(); + sut.setProperty("a", a); + sut.setProperty("b", b); + + // when + sut.destroy(); + + // then + Asserts.assertTrue(a.stopped); + Asserts.assertTrue(b.destroy); + } + + private static class A implements EzyStoppable { + private boolean stopped; + + @Override + public void stop() { + this.stopped = true; + } + } + + public static class B implements EzyDestroyable { + private boolean destroy; + + @Override + public void destroy() { + this.destroy = true; + } + } + + private static class InternalContext extends EzyAbstractContext {} } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleAppContextTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleAppContextTest.java index d98f6c096..704f6232a 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleAppContextTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleAppContextTest.java @@ -74,22 +74,22 @@ public void test() { @Test public void sendMultiTest() { - // given - EzyData data = mock(EzyData.class); - EzySession recipient = mock(EzySession.class); - List recipients = Arrays.asList(recipient); - boolean encrypted = RandomUtil.randomBoolean(); - - EzyAppSendResponse sendResponse = mock(EzyAppSendResponse.class); - doNothing().when(sendResponse).execute(data, recipients, encrypted, EzyTransportType.TCP); - - EzySimpleAppContext sut = new EzySimpleAppContext(); - FieldUtil.setFieldValue(sut, "sendResponse", sendResponse); - - // when - sut.send(data, recipients, encrypted, EzyTransportType.TCP); - - // then - verify(sendResponse, times(1)).execute(data, recipients, encrypted, EzyTransportType.TCP); + // given + EzyData data = mock(EzyData.class); + EzySession recipient = mock(EzySession.class); + List recipients = Arrays.asList(recipient); + boolean encrypted = RandomUtil.randomBoolean(); + + EzyAppSendResponse sendResponse = mock(EzyAppSendResponse.class); + doNothing().when(sendResponse).execute(data, recipients, encrypted, EzyTransportType.TCP); + + EzySimpleAppContext sut = new EzySimpleAppContext(); + FieldUtil.setFieldValue(sut, "sendResponse", sendResponse); + + // when + sut.send(data, recipients, encrypted, EzyTransportType.TCP); + + // then + verify(sendResponse, times(1)).execute(data, recipients, encrypted, EzyTransportType.TCP); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimplePluginContextTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimplePluginContextTest.java index 13625dc15..1f148c6bb 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimplePluginContextTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimplePluginContextTest.java @@ -63,22 +63,22 @@ public void test() { @Test public void sendMultiTest() { - // given - EzyData data = mock(EzyData.class); - EzySession recipient = mock(EzySession.class); - List recipients = Arrays.asList(recipient); - boolean encrypted = RandomUtil.randomBoolean(); - - EzyPluginSendResponse sendResponse = mock(EzyPluginSendResponse.class); - doNothing().when(sendResponse).execute(data, recipients, encrypted, EzyTransportType.TCP); - - EzySimplePluginContext sut = new EzySimplePluginContext(); - FieldUtil.setFieldValue(sut, "sendResponse", sendResponse); - - // when - sut.send(data, recipients, encrypted, EzyTransportType.TCP); - - // then - verify(sendResponse, times(1)).execute(data, recipients, encrypted, EzyTransportType.TCP); + // given + EzyData data = mock(EzyData.class); + EzySession recipient = mock(EzySession.class); + List recipients = Arrays.asList(recipient); + boolean encrypted = RandomUtil.randomBoolean(); + + EzyPluginSendResponse sendResponse = mock(EzyPluginSendResponse.class); + doNothing().when(sendResponse).execute(data, recipients, encrypted, EzyTransportType.TCP); + + EzySimplePluginContext sut = new EzySimplePluginContext(); + FieldUtil.setFieldValue(sut, "sendResponse", sendResponse); + + // when + sut.send(data, recipients, encrypted, EzyTransportType.TCP); + + // then + verify(sendResponse, times(1)).execute(data, recipients, encrypted, EzyTransportType.TCP); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleServerContextTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleServerContextTest.java index 04a91c49d..e5335a23b 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleServerContextTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleServerContextTest.java @@ -157,21 +157,21 @@ public void test5() { @Test public void sendNowTest() { - // given - EzyResponse response = mock(EzyResponse.class); - EzySession recipient = mock(EzySession.class); - - EzySendResponse sendResponse = mock(EzySendResponse.class); - doNothing().when(sendResponse).execute(response, recipient, false, true, EzyTransportType.TCP); - - EzySimpleServerContext sut = new EzySimpleServerContext(); - FieldUtil.setFieldValue(sut, "sendResponse", sendResponse); - - // when - sut.sendNow(response, recipient); - - // then - verify(sendResponse, times(1)).execute(response, recipient, false, true, EzyTransportType.TCP); + // given + EzyResponse response = mock(EzyResponse.class); + EzySession recipient = mock(EzySession.class); + + EzySendResponse sendResponse = mock(EzySendResponse.class); + doNothing().when(sendResponse).execute(response, recipient, false, true, EzyTransportType.TCP); + + EzySimpleServerContext sut = new EzySimpleServerContext(); + FieldUtil.setFieldValue(sut, "sendResponse", sendResponse); + + // when + sut.sendNow(response, recipient); + + // then + verify(sendResponse, times(1)).execute(response, recipient, false, true, EzyTransportType.TCP); } public static class ExCommand implements EzyCommand { diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractPluginEventControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractPluginEventControllerTest.java index 40e3a80bc..c4a0e8291 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractPluginEventControllerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractPluginEventControllerTest.java @@ -6,14 +6,14 @@ public class EzyAbstractPluginEventControllerTest { - @SuppressWarnings("rawtypes") - @Test - public void newTest() { - new EzyAbstractPluginEventController() { + @SuppressWarnings("rawtypes") + @Test + public void newTest() { + new EzyAbstractPluginEventController() { - @Override - public void handle(Object ctx, Object event) { - } - }; - } + @Override + public void handle(Object ctx, Object event) { + } + }; + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractServerEventControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractServerEventControllerTest.java index d7a6e14e3..5f9455f05 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractServerEventControllerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractServerEventControllerTest.java @@ -7,13 +7,13 @@ public class EzyAbstractServerEventControllerTest { - @Test - public void newTest() { - new EzyAbstractServerEventController() { - @Override - public void handle(EzyServerContext ctx, Object event) { - } - - }; - } + @Test + public void newTest() { + new EzyAbstractServerEventController() { + @Override + public void handle(EzyServerContext ctx, Object event) { + } + + }; + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractZoneEventControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractZoneEventControllerTest.java index 7dc08f04f..7015a3466 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractZoneEventControllerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractZoneEventControllerTest.java @@ -7,13 +7,13 @@ public class EzyAbstractZoneEventControllerTest { - @Test - public void newTest() { - new EzyAbstractZoneEventController() { + @Test + public void newTest() { + new EzyAbstractZoneEventController() { - @Override - public void handle(EzyZoneContext ctx, Object event) { - } - }; - } + @Override + public void handle(EzyZoneContext ctx, Object event) { + } + }; + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeControllerTest.java index ab7205671..7159c6112 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeControllerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeControllerTest.java @@ -60,198 +60,198 @@ public void testDeserializeParamsPerformance() { @Test public void handleSocketSSLTest() throws Exception { - // given - EzyHandshakeController sut = new EzyHandshakeController(); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); - - EzyHandshakeParams params = mock(EzyHandshakeParams.class); - when(request.getParams()).thenReturn(params); - - EzySession session = spy(EzyAbstractSession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - when(request.getSession()).thenReturn(session); - - EzyServer server = mock(EzyServer.class); - EzySettings settings = mock(EzySettings.class); - EzySocketSetting socketSetting = mock(EzySocketSetting.class); - when(settings.getSocket()).thenReturn(socketSetting); - when(socketSetting.isSslActive()).thenReturn(true); - when(serverContext.getServer()).thenReturn(server); - when(server.getSettings()).thenReturn(settings); - - String clientId = RandomUtil.randomShortHexString(); - String clientType = RandomUtil.randomShortAlphabetString(); - String clientVersion = RandomUtil.randomShortAlphabetString(); - String reconnectToken = RandomUtil.randomShortHexString(); - KeyPair keyPair = EzyKeysGenerator.builder() - .build() - .generate(); - byte[] clientKey = keyPair.getPublic().getEncoded(); - when(params.getClientId()).thenReturn(clientId); - when(params.getClientKey()).thenReturn(clientKey); - when(params.getClientType()).thenReturn(clientType); - when(params.getClientVersion()).thenReturn(clientVersion); - when(params.getReconnectToken()).thenReturn(reconnectToken); - when(params.isEnableEncryption()).thenReturn(true); - - // when - sut.handle(serverContext, request); - - - // then - verify(session, times(1)).setClientId(clientId); - verify(session, times(1)).setClientKey(clientKey); - verify(session, times(1)).setClientType(clientType); - verify(session, times(1)).setClientVersion(clientVersion); - verify(session, times(1)).setSessionKey(any(byte[].class)); - Asserts.assertNotNull(session.getSessionKey()); + // given + EzyHandshakeController sut = new EzyHandshakeController(); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); + + EzyHandshakeParams params = mock(EzyHandshakeParams.class); + when(request.getParams()).thenReturn(params); + + EzySession session = spy(EzyAbstractSession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + when(request.getSession()).thenReturn(session); + + EzyServer server = mock(EzyServer.class); + EzySettings settings = mock(EzySettings.class); + EzySocketSetting socketSetting = mock(EzySocketSetting.class); + when(settings.getSocket()).thenReturn(socketSetting); + when(socketSetting.isSslActive()).thenReturn(true); + when(serverContext.getServer()).thenReturn(server); + when(server.getSettings()).thenReturn(settings); + + String clientId = RandomUtil.randomShortHexString(); + String clientType = RandomUtil.randomShortAlphabetString(); + String clientVersion = RandomUtil.randomShortAlphabetString(); + String reconnectToken = RandomUtil.randomShortHexString(); + KeyPair keyPair = EzyKeysGenerator.builder() + .build() + .generate(); + byte[] clientKey = keyPair.getPublic().getEncoded(); + when(params.getClientId()).thenReturn(clientId); + when(params.getClientKey()).thenReturn(clientKey); + when(params.getClientType()).thenReturn(clientType); + when(params.getClientVersion()).thenReturn(clientVersion); + when(params.getReconnectToken()).thenReturn(reconnectToken); + when(params.isEnableEncryption()).thenReturn(true); + + // when + sut.handle(serverContext, request); + + + // then + verify(session, times(1)).setClientId(clientId); + verify(session, times(1)).setClientKey(clientKey); + verify(session, times(1)).setClientType(clientType); + verify(session, times(1)).setClientVersion(clientVersion); + verify(session, times(1)).setSessionKey(any(byte[].class)); + Asserts.assertNotNull(session.getSessionKey()); } @Test public void handleSocketSSLButWebsocketTest() { - // given - EzyHandshakeController sut = new EzyHandshakeController(); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); - - EzyHandshakeParams params = mock(EzyHandshakeParams.class); - when(request.getParams()).thenReturn(params); - - EzySession session = spy(EzyAbstractSession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); - when(request.getSession()).thenReturn(session); - - // when - sut.handle(serverContext, request); - - - // then - Asserts.assertNull(session.getSessionKey()); + // given + EzyHandshakeController sut = new EzyHandshakeController(); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); + + EzyHandshakeParams params = mock(EzyHandshakeParams.class); + when(request.getParams()).thenReturn(params); + + EzySession session = spy(EzyAbstractSession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); + when(request.getSession()).thenReturn(session); + + // when + sut.handle(serverContext, request); + + + // then + Asserts.assertNull(session.getSessionKey()); } @Test public void handleSocketSSLButEventNoEncryptionTest() { - // given - EzyHandshakeController sut = new EzyHandshakeController(); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); - - EzyHandshakeParams params = mock(EzyHandshakeParams.class); - when(request.getParams()).thenReturn(params); - - EzySession session = spy(EzyAbstractSession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - when(request.getSession()).thenReturn(session); - - EzyServer server = mock(EzyServer.class); - EzySettings settings = mock(EzySettings.class); - EzySocketSetting socketSetting = mock(EzySocketSetting.class); - when(settings.getSocket()).thenReturn(socketSetting); - when(socketSetting.isSslActive()).thenReturn(true); - when(serverContext.getServer()).thenReturn(server); - when(server.getSettings()).thenReturn(settings); - - when(params.isEnableEncryption()).thenReturn(false); - - // when - sut.handle(serverContext, request); - - - // then - Asserts.assertNull(session.getSessionKey()); + // given + EzyHandshakeController sut = new EzyHandshakeController(); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); + + EzyHandshakeParams params = mock(EzyHandshakeParams.class); + when(request.getParams()).thenReturn(params); + + EzySession session = spy(EzyAbstractSession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + when(request.getSession()).thenReturn(session); + + EzyServer server = mock(EzyServer.class); + EzySettings settings = mock(EzySettings.class); + EzySocketSetting socketSetting = mock(EzySocketSetting.class); + when(settings.getSocket()).thenReturn(socketSetting); + when(socketSetting.isSslActive()).thenReturn(true); + when(serverContext.getServer()).thenReturn(server); + when(server.getSettings()).thenReturn(settings); + + when(params.isEnableEncryption()).thenReturn(false); + + // when + sut.handle(serverContext, request); + + + // then + Asserts.assertNull(session.getSessionKey()); } @Test public void handleSocketSSLButClientKeyEmptyTest() { - // given - EzyHandshakeController sut = new EzyHandshakeController(); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); - - EzyHandshakeParams params = mock(EzyHandshakeParams.class); - when(request.getParams()).thenReturn(params); - - EzySession session = spy(EzyAbstractSession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - when(request.getSession()).thenReturn(session); - - EzyServer server = mock(EzyServer.class); - EzySettings settings = mock(EzySettings.class); - EzySocketSetting socketSetting = mock(EzySocketSetting.class); - when(settings.getSocket()).thenReturn(socketSetting); - when(socketSetting.isSslActive()).thenReturn(true); - when(serverContext.getServer()).thenReturn(server); - when(server.getSettings()).thenReturn(settings); - - String clientId = RandomUtil.randomShortHexString(); - String clientType = RandomUtil.randomShortAlphabetString(); - String clientVersion = RandomUtil.randomShortAlphabetString(); - String reconnectToken = RandomUtil.randomShortHexString(); - byte[] clientKey = new byte[0]; - when(params.getClientId()).thenReturn(clientId); - when(params.getClientKey()).thenReturn(clientKey); - when(params.getClientType()).thenReturn(clientType); - when(params.getClientVersion()).thenReturn(clientVersion); - when(params.getReconnectToken()).thenReturn(reconnectToken); - when(params.isEnableEncryption()).thenReturn(true); - - // when - sut.handle(serverContext, request); - - - // then - verify(session, times(1)).setClientId(clientId); - verify(session, times(1)).setClientKey(clientKey); - verify(session, times(1)).setClientType(clientType); - verify(session, times(1)).setClientVersion(clientVersion); - verify(session, times(1)).setSessionKey(any(byte[].class)); + // given + EzyHandshakeController sut = new EzyHandshakeController(); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); + + EzyHandshakeParams params = mock(EzyHandshakeParams.class); + when(request.getParams()).thenReturn(params); + + EzySession session = spy(EzyAbstractSession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + when(request.getSession()).thenReturn(session); + + EzyServer server = mock(EzyServer.class); + EzySettings settings = mock(EzySettings.class); + EzySocketSetting socketSetting = mock(EzySocketSetting.class); + when(settings.getSocket()).thenReturn(socketSetting); + when(socketSetting.isSslActive()).thenReturn(true); + when(serverContext.getServer()).thenReturn(server); + when(server.getSettings()).thenReturn(settings); + + String clientId = RandomUtil.randomShortHexString(); + String clientType = RandomUtil.randomShortAlphabetString(); + String clientVersion = RandomUtil.randomShortAlphabetString(); + String reconnectToken = RandomUtil.randomShortHexString(); + byte[] clientKey = new byte[0]; + when(params.getClientId()).thenReturn(clientId); + when(params.getClientKey()).thenReturn(clientKey); + when(params.getClientType()).thenReturn(clientType); + when(params.getClientVersion()).thenReturn(clientVersion); + when(params.getReconnectToken()).thenReturn(reconnectToken); + when(params.isEnableEncryption()).thenReturn(true); + + // when + sut.handle(serverContext, request); + + + // then + verify(session, times(1)).setClientId(clientId); + verify(session, times(1)).setClientKey(clientKey); + verify(session, times(1)).setClientType(clientType); + verify(session, times(1)).setClientVersion(clientVersion); + verify(session, times(1)).setSessionKey(any(byte[].class)); } @Test public void handleSocketSSLButInvalidClientKeyEmptyTest() { - // given - EzyHandshakeController sut = new EzyHandshakeController(); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); - - EzyHandshakeParams params = mock(EzyHandshakeParams.class); - when(request.getParams()).thenReturn(params); - - EzySession session = spy(EzyAbstractSession.class); - when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - when(request.getSession()).thenReturn(session); - - EzyServer server = mock(EzyServer.class); - EzySettings settings = mock(EzySettings.class); - EzySocketSetting socketSetting = mock(EzySocketSetting.class); - when(settings.getSocket()).thenReturn(socketSetting); - when(socketSetting.isSslActive()).thenReturn(true); - when(serverContext.getServer()).thenReturn(server); - when(server.getSettings()).thenReturn(settings); - - String clientId = RandomUtil.randomShortHexString(); - String clientType = RandomUtil.randomShortAlphabetString(); - String clientVersion = RandomUtil.randomShortAlphabetString(); - String reconnectToken = RandomUtil.randomShortHexString(); - byte[] clientKey = new byte[] {1, 2, 3}; - when(params.getClientId()).thenReturn(clientId); - when(params.getClientKey()).thenReturn(clientKey); - when(params.getClientType()).thenReturn(clientType); - when(params.getClientVersion()).thenReturn(clientVersion); - when(params.getReconnectToken()).thenReturn(reconnectToken); - when(params.isEnableEncryption()).thenReturn(true); - - // when - sut.handle(serverContext, request); - - - // then - verify(session, times(1)).setClientId(clientId); - verify(session, times(1)).setClientKey(clientKey); - verify(session, times(1)).setClientType(clientType); - verify(session, times(1)).setClientVersion(clientVersion); - verify(session, times(1)).setSessionKey(any(byte[].class)); + // given + EzyHandshakeController sut = new EzyHandshakeController(); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyHandShakeRequest request = mock(EzyHandShakeRequest.class); + + EzyHandshakeParams params = mock(EzyHandshakeParams.class); + when(request.getParams()).thenReturn(params); + + EzySession session = spy(EzyAbstractSession.class); + when(session.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + when(request.getSession()).thenReturn(session); + + EzyServer server = mock(EzyServer.class); + EzySettings settings = mock(EzySettings.class); + EzySocketSetting socketSetting = mock(EzySocketSetting.class); + when(settings.getSocket()).thenReturn(socketSetting); + when(socketSetting.isSslActive()).thenReturn(true); + when(serverContext.getServer()).thenReturn(server); + when(server.getSettings()).thenReturn(settings); + + String clientId = RandomUtil.randomShortHexString(); + String clientType = RandomUtil.randomShortAlphabetString(); + String clientVersion = RandomUtil.randomShortAlphabetString(); + String reconnectToken = RandomUtil.randomShortHexString(); + byte[] clientKey = new byte[] {1, 2, 3}; + when(params.getClientId()).thenReturn(clientId); + when(params.getClientKey()).thenReturn(clientKey); + when(params.getClientType()).thenReturn(clientType); + when(params.getClientVersion()).thenReturn(clientVersion); + when(params.getReconnectToken()).thenReturn(reconnectToken); + when(params.isEnableEncryption()).thenReturn(true); + + // when + sut.handle(serverContext, request); + + + // then + verify(session, times(1)).setClientId(clientId); + verify(session, times(1)).setClientKey(clientKey); + verify(session, times(1)).setClientType(clientType); + verify(session, times(1)).setClientVersion(clientVersion); + verify(session, times(1)).setSessionKey(any(byte[].class)); } private EzyArray newHandShakeData() { diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginControllerTest.java index cdc6dc926..66442e6d7 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginControllerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginControllerTest.java @@ -299,8 +299,8 @@ public void testEzyMaxUserExceptionCase() { public void testExceptionCase() { EzyServerContext ctx = mock(EzyServerContext.class); doThrow(new IllegalStateException("server maintain")) - .when(ctx) - .send(any(EzyResponse.class), any(EzySession.class), any(boolean.class)); + .when(ctx) + .send(any(EzyResponse.class), any(EzySession.class), any(boolean.class)); EzyStatistics userStats = new EzySimpleStatistics(); EzySimpleServer server = new EzySimpleServer(); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginProcessorTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginProcessorTest.java index 2e847ff29..c0e5a3381 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginProcessorTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginProcessorTest.java @@ -26,344 +26,344 @@ public class EzyLoginProcessorTest { - @SuppressWarnings("rawtypes") - @Test - public void checkUsernameIsNull() { - // given - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - when(zoneContext.getZone()).thenReturn(zone); - - EzySimpleServer server = new EzySimpleServer(); - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyStatistics statistics = mock(EzyStatistics.class); - EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); - when(statistics.getUserStats()).thenReturn(userStatistics); - server.setStatistics(statistics); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); - - EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); - - // when - Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); - - // then - Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); - } - - @SuppressWarnings("rawtypes") - @Test - public void applyWithStreamingEnable() { - // given - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - zoneSetting.getStreaming().setEnable(true); - - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - when(zoneContext.getZone()).thenReturn(zone); - - EzySimpleServer server = new EzySimpleServer(); - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() - .build(); - zone.setUserManager(userManager); - - EzyStatistics statistics = mock(EzyStatistics.class); - EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); - when(statistics.getUserStats()).thenReturn(userStatistics); - server.setStatistics(statistics); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); - - EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); - EzyAbstractSession session = spy(EzyAbstractSession.class); - session.setDelegate(sessionDelegate); - - - EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); - when(event.getUsername()).thenReturn("monkey"); - when(event.getSession()).thenReturn(session); - when(event.isStreamingEnable()).thenReturn(true); - - // when - sut.apply(zoneContext, event); - - // then - Asserts.assertTrue(session.isStreamingEnable()); - } - - @SuppressWarnings("rawtypes") - @Test - public void applyWithStreamingDisableByEvent() { - // given - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - zoneSetting.getStreaming().setEnable(true); - - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - when(zoneContext.getZone()).thenReturn(zone); - - EzySimpleServer server = new EzySimpleServer(); - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() - .build(); - zone.setUserManager(userManager); - - EzyStatistics statistics = mock(EzyStatistics.class); - EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); - when(statistics.getUserStats()).thenReturn(userStatistics); - server.setStatistics(statistics); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); - - EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); - EzyAbstractSession session = spy(EzyAbstractSession.class); - session.setDelegate(sessionDelegate); - - - EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); - when(event.getUsername()).thenReturn("monkey"); - when(event.getSession()).thenReturn(session); - when(event.isStreamingEnable()).thenReturn(false); - - // when - sut.apply(zoneContext, event); - - // then - Asserts.assertFalse(session.isStreamingEnable()); - } - - @SuppressWarnings("rawtypes") - @Test - public void processUserSessionsMaxSessionPerUser() { - // given - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - zoneSetting.getUserManagement().setMaxSessionPerUser(1); - - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - when(zoneContext.getZone()).thenReturn(zone); - - EzySimpleServer server = new EzySimpleServer(); - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() - .build(); - EzyUser user = mock(EzyUser.class); - when(user.getName()).thenReturn("monkey"); - when(user.getSessionCount()).thenReturn(2); - userManager.addUser(user); - - zone.setUserManager(userManager); - - EzyStatistics statistics = mock(EzyStatistics.class); - EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); - when(statistics.getUserStats()).thenReturn(userStatistics); - server.setStatistics(statistics); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); - - EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); - EzyAbstractSession session = spy(EzyAbstractSession.class); - session.setDelegate(sessionDelegate); - - - EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); - when(event.getUsername()).thenReturn("monkey"); - when(event.getSession()).thenReturn(session); - - // when - Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); - - // then - Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); - } - - @SuppressWarnings("rawtypes") - @Test - public void processUserSessionsMaxSessionPerUserGreaterThan1() { - // given - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - zoneSetting.getUserManagement().setMaxSessionPerUser(2); - - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - when(zoneContext.getZone()).thenReturn(zone); - - EzySimpleServer server = new EzySimpleServer(); - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() - .build(); - EzyUser user = mock(EzyUser.class); - when(user.getName()).thenReturn("monkey"); - when(user.getSessionCount()).thenReturn(2); - userManager.addUser(user); - - zone.setUserManager(userManager); - - EzyStatistics statistics = mock(EzyStatistics.class); - EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); - when(statistics.getUserStats()).thenReturn(userStatistics); - server.setStatistics(statistics); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); - - EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); - EzyAbstractSession session = spy(EzyAbstractSession.class); - session.setDelegate(sessionDelegate); - - - EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); - when(event.getUsername()).thenReturn("monkey"); - when(event.getSession()).thenReturn(session); - - // when - Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); - - // then - Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); - } - - @SuppressWarnings("rawtypes") - @Test - public void processUserSessionsButNotAllowToChangeSession() { - // given - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - zoneSetting.getUserManagement().setMaxSessionPerUser(1); - zoneSetting.getUserManagement().setAllowChangeSession(false); - - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - when(zoneContext.getZone()).thenReturn(zone); - - EzySimpleServer server = new EzySimpleServer(); - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() - .build(); - EzyUser user = mock(EzyUser.class); - when(user.getName()).thenReturn("monkey"); - when(user.getSessionCount()).thenReturn(1); - userManager.addUser(user); - - zone.setUserManager(userManager); - - EzyStatistics statistics = mock(EzyStatistics.class); - EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); - when(statistics.getUserStats()).thenReturn(userStatistics); - server.setStatistics(statistics); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); - - EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); - EzyAbstractSession session = spy(EzyAbstractSession.class); - session.setDelegate(sessionDelegate); - - - EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); - when(event.getUsername()).thenReturn("monkey"); - when(event.getSession()).thenReturn(session); - - // when - Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); - - // then - Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); - } - - @SuppressWarnings("rawtypes") - @Test - public void processUserSessionsOk() { - // given - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - zoneSetting.getUserManagement().setMaxSessionPerUser(1); - zoneSetting.getUserManagement().setAllowChangeSession(true); - - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - when(zoneContext.getZone()).thenReturn(zone); - - EzySimpleServer server = new EzySimpleServer(); - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() - .build(); - EzyUser user = mock(EzyUser.class); - when(user.getName()).thenReturn("monkey"); - when(user.getSessionCount()).thenReturn(1); - userManager.addUser(user); - - zone.setUserManager(userManager); - - EzyStatistics statistics = mock(EzyStatistics.class); - EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); - when(statistics.getUserStats()).thenReturn(userStatistics); - server.setStatistics(statistics); - - EzyServerContext serverContext = mock(EzyServerContext.class); - when(serverContext.getServer()).thenReturn(server); - - EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); - - EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); - EzyAbstractSession session = spy(EzyAbstractSession.class); - session.setDelegate(sessionDelegate); - - - EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); - when(event.getUsername()).thenReturn("monkey"); - when(event.getSession()).thenReturn(session); - - // when - sut.apply(zoneContext, event); - - // then - Asserts.assertTrue(session.isLoggedIn()); - } + @SuppressWarnings("rawtypes") + @Test + public void checkUsernameIsNull() { + // given + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + when(zoneContext.getZone()).thenReturn(zone); + + EzySimpleServer server = new EzySimpleServer(); + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyStatistics statistics = mock(EzyStatistics.class); + EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); + when(statistics.getUserStats()).thenReturn(userStatistics); + server.setStatistics(statistics); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); + + EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); + + // when + Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); + + // then + Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); + } + + @SuppressWarnings("rawtypes") + @Test + public void applyWithStreamingEnable() { + // given + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + zoneSetting.getStreaming().setEnable(true); + + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + when(zoneContext.getZone()).thenReturn(zone); + + EzySimpleServer server = new EzySimpleServer(); + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() + .build(); + zone.setUserManager(userManager); + + EzyStatistics statistics = mock(EzyStatistics.class); + EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); + when(statistics.getUserStats()).thenReturn(userStatistics); + server.setStatistics(statistics); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); + + EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); + EzyAbstractSession session = spy(EzyAbstractSession.class); + session.setDelegate(sessionDelegate); + + + EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); + when(event.getUsername()).thenReturn("monkey"); + when(event.getSession()).thenReturn(session); + when(event.isStreamingEnable()).thenReturn(true); + + // when + sut.apply(zoneContext, event); + + // then + Asserts.assertTrue(session.isStreamingEnable()); + } + + @SuppressWarnings("rawtypes") + @Test + public void applyWithStreamingDisableByEvent() { + // given + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + zoneSetting.getStreaming().setEnable(true); + + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + when(zoneContext.getZone()).thenReturn(zone); + + EzySimpleServer server = new EzySimpleServer(); + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() + .build(); + zone.setUserManager(userManager); + + EzyStatistics statistics = mock(EzyStatistics.class); + EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); + when(statistics.getUserStats()).thenReturn(userStatistics); + server.setStatistics(statistics); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); + + EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); + EzyAbstractSession session = spy(EzyAbstractSession.class); + session.setDelegate(sessionDelegate); + + + EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); + when(event.getUsername()).thenReturn("monkey"); + when(event.getSession()).thenReturn(session); + when(event.isStreamingEnable()).thenReturn(false); + + // when + sut.apply(zoneContext, event); + + // then + Asserts.assertFalse(session.isStreamingEnable()); + } + + @SuppressWarnings("rawtypes") + @Test + public void processUserSessionsMaxSessionPerUser() { + // given + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + zoneSetting.getUserManagement().setMaxSessionPerUser(1); + + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + when(zoneContext.getZone()).thenReturn(zone); + + EzySimpleServer server = new EzySimpleServer(); + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() + .build(); + EzyUser user = mock(EzyUser.class); + when(user.getName()).thenReturn("monkey"); + when(user.getSessionCount()).thenReturn(2); + userManager.addUser(user); + + zone.setUserManager(userManager); + + EzyStatistics statistics = mock(EzyStatistics.class); + EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); + when(statistics.getUserStats()).thenReturn(userStatistics); + server.setStatistics(statistics); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); + + EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); + EzyAbstractSession session = spy(EzyAbstractSession.class); + session.setDelegate(sessionDelegate); + + + EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); + when(event.getUsername()).thenReturn("monkey"); + when(event.getSession()).thenReturn(session); + + // when + Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); + + // then + Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); + } + + @SuppressWarnings("rawtypes") + @Test + public void processUserSessionsMaxSessionPerUserGreaterThan1() { + // given + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + zoneSetting.getUserManagement().setMaxSessionPerUser(2); + + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + when(zoneContext.getZone()).thenReturn(zone); + + EzySimpleServer server = new EzySimpleServer(); + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() + .build(); + EzyUser user = mock(EzyUser.class); + when(user.getName()).thenReturn("monkey"); + when(user.getSessionCount()).thenReturn(2); + userManager.addUser(user); + + zone.setUserManager(userManager); + + EzyStatistics statistics = mock(EzyStatistics.class); + EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); + when(statistics.getUserStats()).thenReturn(userStatistics); + server.setStatistics(statistics); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); + + EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); + EzyAbstractSession session = spy(EzyAbstractSession.class); + session.setDelegate(sessionDelegate); + + + EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); + when(event.getUsername()).thenReturn("monkey"); + when(event.getSession()).thenReturn(session); + + // when + Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); + + // then + Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); + } + + @SuppressWarnings("rawtypes") + @Test + public void processUserSessionsButNotAllowToChangeSession() { + // given + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + zoneSetting.getUserManagement().setMaxSessionPerUser(1); + zoneSetting.getUserManagement().setAllowChangeSession(false); + + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + when(zoneContext.getZone()).thenReturn(zone); + + EzySimpleServer server = new EzySimpleServer(); + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() + .build(); + EzyUser user = mock(EzyUser.class); + when(user.getName()).thenReturn("monkey"); + when(user.getSessionCount()).thenReturn(1); + userManager.addUser(user); + + zone.setUserManager(userManager); + + EzyStatistics statistics = mock(EzyStatistics.class); + EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); + when(statistics.getUserStats()).thenReturn(userStatistics); + server.setStatistics(statistics); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); + + EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); + EzyAbstractSession session = spy(EzyAbstractSession.class); + session.setDelegate(sessionDelegate); + + + EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); + when(event.getUsername()).thenReturn("monkey"); + when(event.getSession()).thenReturn(session); + + // when + Throwable e = Asserts.assertThrows(() -> sut.apply(zoneContext, event)); + + // then + Asserts.assertEquals(EzyLoginErrorException.class, e.getClass()); + } + + @SuppressWarnings("rawtypes") + @Test + public void processUserSessionsOk() { + // given + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + zoneSetting.getUserManagement().setMaxSessionPerUser(1); + zoneSetting.getUserManagement().setAllowChangeSession(true); + + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + when(zoneContext.getZone()).thenReturn(zone); + + EzySimpleServer server = new EzySimpleServer(); + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyZoneUserManager userManager = EzyZoneUserManagerImpl.builder() + .build(); + EzyUser user = mock(EzyUser.class); + when(user.getName()).thenReturn("monkey"); + when(user.getSessionCount()).thenReturn(1); + userManager.addUser(user); + + zone.setUserManager(userManager); + + EzyStatistics statistics = mock(EzyStatistics.class); + EzyUserStatistics userStatistics = mock(EzyUserStatistics.class); + when(statistics.getUserStats()).thenReturn(userStatistics); + server.setStatistics(statistics); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getServer()).thenReturn(server); + + EzyLoginProcessor sut = new EzyLoginProcessor(serverContext); + + EzySessionDelegate sessionDelegate = mock(EzySessionDelegate.class); + EzyAbstractSession session = spy(EzyAbstractSession.class); + session.setDelegate(sessionDelegate); + + + EzyUserLoginEvent event = mock(EzyUserLoginEvent.class); + when(event.getUsername()).thenReturn("monkey"); + when(event.getSession()).thenReturn(session); + + // when + sut.apply(zoneContext, event); + + // then + Asserts.assertTrue(session.isLoggedIn()); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyAbstractSessionTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyAbstractSessionTest.java index 4a8aa9533..da98801a6 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyAbstractSessionTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyAbstractSessionTest.java @@ -187,53 +187,53 @@ public void test() { @Test public void addPacketToSessionQueueWithTicketsQueueIsNull() { - // given - EzyPacket packet = mock(EzyPacket.class); - MyTestSession session = new MyTestSession(); - session.setActivated(true); - - EzyPacketQueue packetQueue = mock(EzyPacketQueue.class); - when(packetQueue.isEmpty()).thenReturn(true); - when(packetQueue.add(packet)).thenReturn(true); - session.setPacketQueue(packetQueue); - - // when - session.send(packet); - - // then - Asserts.assertNull(session.getSessionTicketsQueue()); + // given + EzyPacket packet = mock(EzyPacket.class); + MyTestSession session = new MyTestSession(); + session.setActivated(true); + + EzyPacketQueue packetQueue = mock(EzyPacketQueue.class); + when(packetQueue.isEmpty()).thenReturn(true); + when(packetQueue.add(packet)).thenReturn(true); + session.setPacketQueue(packetQueue); + + // when + session.send(packet); + + // then + Asserts.assertNull(session.getSessionTicketsQueue()); } @Test public void addPacketToSessionQueueWithDroppedPacketsNowIsNull() { - // given - EzyPacket packet = mock(EzyPacket.class); - MyTestSession session = new MyTestSession(); - session.setActivated(true); - - EzyPacketQueue packetQueue = mock(EzyPacketQueue.class); - when(packetQueue.isEmpty()).thenReturn(true); - when(packetQueue.add(packet)).thenReturn(false); - session.setPacketQueue(packetQueue); - - // when - session.send(packet); - - // then - Asserts.assertNull(session.getDroppedPackets()); + // given + EzyPacket packet = mock(EzyPacket.class); + MyTestSession session = new MyTestSession(); + session.setActivated(true); + + EzyPacketQueue packetQueue = mock(EzyPacketQueue.class); + when(packetQueue.isEmpty()).thenReturn(true); + when(packetQueue.add(packet)).thenReturn(false); + session.setPacketQueue(packetQueue); + + // when + session.send(packet); + + // then + Asserts.assertNull(session.getDroppedPackets()); } @Test public void disconnectWithQueueIsNull() { - // given - PrivateSession session = new PrivateSession(); - - // when - session.disconnect(EzyDisconnectReason.ADMIN_BAN); - - // then - Asserts.assertNull(session.getDisconnectionQueue()); - Asserts.assertTrue(session.isDisconnectionRegistered()); + // given + PrivateSession session = new PrivateSession(); + + // when + session.disconnect(EzyDisconnectReason.ADMIN_BAN); + + // then + Asserts.assertNull(session.getDisconnectionQueue()); + Asserts.assertTrue(session.isDisconnectionRegistered()); } private static class PrivateSession extends EzyAbstractSession { diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzySimpleUserTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzySimpleUserTest.java index a8a17d5e1..6aaa703b1 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzySimpleUserTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzySimpleUserTest.java @@ -74,26 +74,26 @@ public void test() { @Test public void equalTest() { - // given - EzySimpleUser user1 = new EzySimpleUser(); - user1.setId(1L); - user1.setName("user"); - user1.setPassword("123456"); - user1.setZoneId(1); - user1.setMaxSessions(30); - user1.setStartIdleTime(System.currentTimeMillis()); - user1.setMaxIdleTime(100L); - user1.setDestroyed(false); - EzySimpleUser user2 = new EzySimpleUser(); - user2.setId(1L); - EzySimpleUser user3 = new EzySimpleUser(); - - // when - // then - Asserts.assertFalse(user1.equals(null)); - Asserts.assertTrue(user1.equals(user1)); - Asserts.assertTrue(user1.equals(user2)); - Asserts.assertFalse(user1.equals(user3)); - Asserts.assertFalse(user1.equals(new Object())); + // given + EzySimpleUser user1 = new EzySimpleUser(); + user1.setId(1L); + user1.setName("user"); + user1.setPassword("123456"); + user1.setZoneId(1); + user1.setMaxSessions(30); + user1.setStartIdleTime(System.currentTimeMillis()); + user1.setMaxIdleTime(100L); + user1.setDestroyed(false); + EzySimpleUser user2 = new EzySimpleUser(); + user2.setId(1L); + EzySimpleUser user3 = new EzySimpleUser(); + + // when + // then + Asserts.assertFalse(user1.equals(null)); + Asserts.assertTrue(user1.equals(user1)); + Asserts.assertTrue(user1.equals(user2)); + Asserts.assertFalse(user1.equals(user3)); + Asserts.assertFalse(user1.equals(new Object())); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryLoaderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryLoaderTest.java index b7902d2f5..36a150503 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryLoaderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryLoaderTest.java @@ -7,13 +7,13 @@ public class EzyAbstractPluginEntryLoaderTest { - @Test - public void newTest() { - new EzyAbstractPluginEntryLoader() { - @Override - public EzyPluginEntry load() throws Exception { - return null; - } - }; - } + @Test + public void newTest() { + new EzyAbstractPluginEntryLoader() { + @Override + public EzyPluginEntry load() throws Exception { + return null; + } + }; + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryTest.java index 937da7a4f..8b95bc0c3 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ext/EzyAbstractPluginEntryTest.java @@ -6,10 +6,10 @@ public class EzyAbstractPluginEntryTest { - @Test - public void newTest() { - EzyAbstractPluginEntry entry = new EzyAbstractPluginEntry() { - }; - entry.destroy(); - } + @Test + public void newTest() { + EzyAbstractPluginEntry entry = new EzyAbstractPluginEntry() { + }; + entry.destroy(); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzySimpleDataHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzySimpleDataHandlerTest.java index 719712e7e..a2f00dbf4 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzySimpleDataHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzySimpleDataHandlerTest.java @@ -612,49 +612,49 @@ public void closeSessionExceptionCase() throws Exception { } @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test + @Test public void processMaxRequestPerSecondDisconnect() { - // given - EzySession session = spy(EzyAbstractSession.class); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyServer server = mock(EzyServer.class); - EzySessionManager sessionManager = mock(EzySessionManager.class); - when(server.getSessionManager()).thenReturn(sessionManager); - when(serverContext.getServer()).thenReturn(server); - - - EzySessionManagementSetting sessionManagementSetting = - mock(EzySessionManagementSetting.class); - EzySessionManagementSetting.EzyMaxRequestPerSecond maxRequestPerSecond = - mock(EzySessionManagementSetting.EzyMaxRequestPerSecond.class); - when(maxRequestPerSecond.getAction()).thenReturn(EzyMaxRequestPerSecondAction.DISCONNECT_SESSION); - when(sessionManagementSetting.getSessionMaxRequestPerSecond()) - .thenReturn(maxRequestPerSecond); - - EzySettings settings = mock(EzySettings.class); - when(server.getSettings()).thenReturn(settings); - when(settings.getSessionManagement()).thenReturn(sessionManagementSetting); - - EzyLoggerSetting loggerSetting = mock(EzyLoggerSetting.class); - EzyLoggerSetting.EzyIgnoredCommandsSetting ignoredCommandsSetting = - mock(EzyLoggerSetting.EzyIgnoredCommandsSetting.class); - when(ignoredCommandsSetting.getCommands()).thenReturn(Collections.emptySet()); - when(loggerSetting.getIgnoredCommands()).thenReturn(ignoredCommandsSetting); - when(settings.getLogger()).thenReturn(loggerSetting); - - MyTestDataHandler sut = new MyTestDataHandler(serverContext, session); - - // when - sut.processMaxRequestPerSecond(); - - // then - verify(sessionManager, times(1)).removeSession(session, EzyDisconnectReason.MAX_REQUEST_PER_SECOND);; + // given + EzySession session = spy(EzyAbstractSession.class); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyServer server = mock(EzyServer.class); + EzySessionManager sessionManager = mock(EzySessionManager.class); + when(server.getSessionManager()).thenReturn(sessionManager); + when(serverContext.getServer()).thenReturn(server); + + + EzySessionManagementSetting sessionManagementSetting = + mock(EzySessionManagementSetting.class); + EzySessionManagementSetting.EzyMaxRequestPerSecond maxRequestPerSecond = + mock(EzySessionManagementSetting.EzyMaxRequestPerSecond.class); + when(maxRequestPerSecond.getAction()).thenReturn(EzyMaxRequestPerSecondAction.DISCONNECT_SESSION); + when(sessionManagementSetting.getSessionMaxRequestPerSecond()) + .thenReturn(maxRequestPerSecond); + + EzySettings settings = mock(EzySettings.class); + when(server.getSettings()).thenReturn(settings); + when(settings.getSessionManagement()).thenReturn(sessionManagementSetting); + + EzyLoggerSetting loggerSetting = mock(EzyLoggerSetting.class); + EzyLoggerSetting.EzyIgnoredCommandsSetting ignoredCommandsSetting = + mock(EzyLoggerSetting.EzyIgnoredCommandsSetting.class); + when(ignoredCommandsSetting.getCommands()).thenReturn(Collections.emptySet()); + when(loggerSetting.getIgnoredCommands()).thenReturn(ignoredCommandsSetting); + when(settings.getLogger()).thenReturn(loggerSetting); + + MyTestDataHandler sut = new MyTestDataHandler(serverContext, session); + + // when + sut.processMaxRequestPerSecond(); + + // then + verify(sessionManager, times(1)).removeSession(session, EzyDisconnectReason.MAX_REQUEST_PER_SECOND);; } @Test public void dataReceivedValidateStateFalse() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); sut.destroy(); @@ -669,7 +669,7 @@ public void dataReceivedValidateStateFalse() throws Exception { @Test public void dataReceivedValidateSessionIsNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "session", null); @@ -684,7 +684,7 @@ public void dataReceivedValidateSessionIsNull() throws Exception { @Test public void dataReceivedValidateSessionInActive() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); EzySession session = FieldUtil.getFieldValue(sut, "session"); session.setActivated(false); @@ -700,7 +700,7 @@ public void dataReceivedValidateSessionInActive() throws Exception { @Test public void streamingReceivedValidateStateFalse() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); sut.destroy(); @@ -713,7 +713,7 @@ public void streamingReceivedValidateStateFalse() throws Exception { @Test public void streamingReceivedValidateSessionIsNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "session", null); @@ -726,10 +726,10 @@ public void streamingReceivedValidateSessionIsNull() throws Exception { @Test public void processMaxRequestPerSecondActionDiffDisconnection() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); EzySessionManagementSetting.EzyMaxRequestPerSecond maxRequestPerSecond = - FieldUtil.getFieldValue(sut, "maxRequestPerSecond"); + FieldUtil.getFieldValue(sut, "maxRequestPerSecond"); when(maxRequestPerSecond.getAction()).thenReturn(EzyMaxRequestPerSecondAction.DROP_REQUEST); // when @@ -741,7 +741,7 @@ public void processMaxRequestPerSecondActionDiffDisconnection() throws Exception @Test public void processMaxRequestPerSecondWithSessionManagerIsNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "sessionManager", null); @@ -754,18 +754,18 @@ public void processMaxRequestPerSecondWithSessionManagerIsNull() throws Exceptio @Test public void debugLogReceivedDataIsNotDebug() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); EzySettings settings = FieldUtil.getFieldValue(sut, "settings"); when(settings.isDebug()).thenReturn(false); // when MethodInvoker.create() - .object(sut) - .method("debugLogReceivedData") - .param(EzyConstant.class, EzyCommand.APP_ACCESS) - .param(EzyArray.class, EzyEntityFactory.EMPTY_ARRAY) - .call(); + .object(sut) + .method("debugLogReceivedData") + .param(EzyConstant.class, EzyCommand.APP_ACCESS) + .param(EzyArray.class, EzyEntityFactory.EMPTY_ARRAY) + .call(); // then verify(settings, times(1)).isDebug(); @@ -773,18 +773,18 @@ public void debugLogReceivedDataIsNotDebug() throws Exception { @Test public void debugLogReceivedDataUnloggableCommandsIsPing() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); EzySettings settings = FieldUtil.getFieldValue(sut, "settings"); when(settings.isDebug()).thenReturn(true); // when MethodInvoker.create() - .object(sut) - .method("debugLogReceivedData") - .param(EzyConstant.class, EzyCommand.PING) - .param(EzyArray.class, EzyEntityFactory.EMPTY_ARRAY) - .call(); + .object(sut) + .method("debugLogReceivedData") + .param(EzyConstant.class, EzyCommand.PING) + .param(EzyArray.class, EzyEntityFactory.EMPTY_ARRAY) + .call(); // then verify(settings, times(1)).isDebug(); @@ -792,7 +792,7 @@ public void debugLogReceivedDataUnloggableCommandsIsPing() throws Exception { @Test public void exceptionCaughtHandlerNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); Throwable e = new Exception("just test"); @@ -803,7 +803,7 @@ public void exceptionCaughtHandlerNull() throws Exception { @Test public void removeSessionWithSessionManagerIsNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "sessionManager", null); @@ -816,16 +816,16 @@ public void removeSessionWithSessionManagerIsNull() throws Exception { @Test public void notifySessionRemovedZoneContextIsNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "zoneContext", null); // when MethodInvoker.create() - .object(sut) - .method("notifySessionRemoved") - .param(EzyConstant.class, EzyDisconnectReason.ADMIN_BAN) - .invoke(); + .object(sut) + .method("notifySessionRemoved") + .param(EzyConstant.class, EzyDisconnectReason.ADMIN_BAN) + .invoke(); // then Asserts.assertNull(FieldUtil.getFieldValue(sut, "zoneContext")); @@ -833,16 +833,16 @@ public void notifySessionRemovedZoneContextIsNull() throws Exception { @Test public void notifyAppsSessionRemovedUserNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "user", null); // when MethodInvoker.create() - .object(sut) - .method("notifyAppsSessionRemoved") - .param(EzyEvent.class, mock(EzyEvent.class)) - .invoke(); + .object(sut) + .method("notifyAppsSessionRemoved") + .param(EzyEvent.class, mock(EzyEvent.class)) + .invoke(); // then Asserts.assertNull(FieldUtil.getFieldValue(sut, "user")); @@ -850,16 +850,16 @@ public void notifyAppsSessionRemovedUserNull() throws Exception { @Test public void responseContextIsNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "context", null); // when MethodInvoker.create() - .object(sut) - .method("response") - .param(EzyResponse.class, mock(EzyResponse.class)) - .invoke(); + .object(sut) + .method("response") + .param(EzyResponse.class, mock(EzyResponse.class)) + .invoke(); // then Asserts.assertNull(FieldUtil.getFieldValue(sut, "context")); @@ -867,7 +867,7 @@ public void responseContextIsNull() throws Exception { @Test public void exceptionCaughtSessionManagerIsNull() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); Throwable e = new EzyMaxRequestSizeException("just test"); FieldUtil.setFieldValue(sut, "sessionManager", null); @@ -880,8 +880,8 @@ public void exceptionCaughtSessionManagerIsNull() throws Exception { } @SuppressWarnings("rawtypes") - private MyTestDataHandler createHandler() { - int zoneId = 1; + private MyTestDataHandler createHandler() { + int zoneId = 1; EzyServerContext serverContext = mock(EzyServerContext.class); EzyZoneContext zoneContext = mock(EzyZoneContext.class); EzyZone zone = mock(EzyZone.class); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzyUserDataHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzyUserDataHandlerTest.java index 6c15b9f51..de34ae01f 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzyUserDataHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzyUserDataHandlerTest.java @@ -34,26 +34,26 @@ public class EzyUserDataHandlerTest { - @Test + @Test public void checkToUnmapUserTest() throws Exception { - // given + // given MyTestDataHandler sut = createHandler(); FieldUtil.setFieldValue(sut, "user", null); // when MethodInvoker.create() - .object(sut) - .method("checkToUnmapUser") - .param(EzyConstant.class, mock(EzyConstant.class)) - .invoke(); + .object(sut) + .method("checkToUnmapUser") + .param(EzyConstant.class, mock(EzyConstant.class)) + .invoke(); // then Asserts.assertNull(FieldUtil.getFieldValue(sut, "user")); } - - @SuppressWarnings("rawtypes") - private MyTestDataHandler createHandler() { - int zoneId = 1; + + @SuppressWarnings("rawtypes") + private MyTestDataHandler createHandler() { + int zoneId = 1; EzyServerContext serverContext = mock(EzyServerContext.class); EzyZoneContext zoneContext = mock(EzyZoneContext.class); EzyZone zone = mock(EzyZone.class); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyEventControllerSettingBuilderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyEventControllerSettingBuilderTest.java index 1730151ed..031e59c06 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyEventControllerSettingBuilderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyEventControllerSettingBuilderTest.java @@ -12,25 +12,25 @@ public class EzyEventControllerSettingBuilderTest { - @Test - public void test() { - // given - EzyEventControllerSettingBuilder sut = new EzyEventControllerSettingBuilder() - .controller(A.class) - .eventType(EzyEventType.SERVER_READY); - - // when - EzyEventControllerSetting eventController = sut.build(); - - // then - Asserts.assertEquals(A.class.getName(), eventController.getController()); - Asserts.assertEquals(EzyEventType.SERVER_READY.toString(), eventController.getEventType());; - } - - private static class A implements EzyEventController { - @Override - public void handle(EzyServerContext ctx, EzyEvent event) { - } - } - + @Test + public void test() { + // given + EzyEventControllerSettingBuilder sut = new EzyEventControllerSettingBuilder() + .controller(A.class) + .eventType(EzyEventType.SERVER_READY); + + // when + EzyEventControllerSetting eventController = sut.build(); + + // then + Asserts.assertEquals(A.class.getName(), eventController.getController()); + Asserts.assertEquals(EzyEventType.SERVER_READY.toString(), eventController.getEventType());; + } + + private static class A implements EzyEventController { + @Override + public void handle(EzyServerContext ctx, EzyEvent event) { + } + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAdminsSettingTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAdminsSettingTest.java index ce01ff6ed..49654dfef 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAdminsSettingTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAdminsSettingTest.java @@ -36,16 +36,16 @@ public void test() { @Test public void setItemUsernameNull() { - // given - EzySimpleAdminSetting item = new EzySimpleAdminSetting(); - item.setUsername(""); - EzySimpleAdminsSetting sut = new EzySimpleAdminsSetting(); - - // when - sut.setItem(item); - - // then - Asserts.assertNull(sut.getAdminByName("")); + // given + EzySimpleAdminSetting item = new EzySimpleAdminSetting(); + item.setUsername(""); + EzySimpleAdminsSetting sut = new EzySimpleAdminsSetting(); + + // when + sut.setItem(item); + + // then + Asserts.assertNull(sut.getAdminByName("")); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAppSettingTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAppSettingTest.java index 587e79023..db114bcbb 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAppSettingTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleAppSettingTest.java @@ -25,16 +25,16 @@ public void test() { @Test public void configFileIsNull() { - // given - EzySimpleAppSetting sut = new EzySimpleAppSetting(); - sut.setConfigFile(null); - - // when - String configFile = sut.getConfigFile(true); - - // then - Asserts.assertNull(configFile); - System.out.println(sut.toMap()); + // given + EzySimpleAppSetting sut = new EzySimpleAppSetting(); + sut.setConfigFile(null); + + // when + String configFile = sut.getConfigFile(true); + + // then + Asserts.assertNull(configFile); + System.out.println(sut.toMap()); } @Test diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleZoneSettingTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleZoneSettingTest.java index c9116410a..76be46ea3 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleZoneSettingTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySimpleZoneSettingTest.java @@ -47,14 +47,14 @@ public void test() { @Test public void configFileIsNull() { - // given - EzySimpleZoneSetting sut = new EzySimpleZoneSetting(); - - // when - String configFile = sut.getConfigFile(); - - // then - Asserts.assertNull(configFile); - System.out.println(sut.toMap()); + // given + EzySimpleZoneSetting sut = new EzySimpleZoneSetting(); + + // when + String configFile = sut.getConfigFile(); + + // then + Asserts.assertNull(configFile); + System.out.println(sut.toMap()); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySslConfigSettingBuilderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySslConfigSettingBuilderTest.java index 28cc73979..f63717c11 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySslConfigSettingBuilderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySslConfigSettingBuilderTest.java @@ -9,26 +9,26 @@ public class EzySslConfigSettingBuilderTest { - @Test - public void test() { - // given - String file = RandomUtil.randomShortAlphabetString(); - String loader = RandomUtil.randomShortAlphabetString(); - String contextFactoryBuilder = RandomUtil.randomShortAlphabetString(); - EzySslConfigSettingBuilder sut = new EzySslConfigSettingBuilder() - .file(file) - .loader(loader) - .contextFactoryBuilder(contextFactoryBuilder); - - // when - EzySimpleSslConfigSetting setting = sut.build(); - - // then - EzySimpleSslConfigSetting expectation = new EzySimpleSslConfigSetting(); - expectation.setFile(file); - expectation.setLoader(loader); - expectation.setContextFactoryBuilder(contextFactoryBuilder); - Asserts.assertEquals(expectation, setting); - } - + @Test + public void test() { + // given + String file = RandomUtil.randomShortAlphabetString(); + String loader = RandomUtil.randomShortAlphabetString(); + String contextFactoryBuilder = RandomUtil.randomShortAlphabetString(); + EzySslConfigSettingBuilder sut = new EzySslConfigSettingBuilder() + .file(file) + .loader(loader) + .contextFactoryBuilder(contextFactoryBuilder); + + // when + EzySimpleSslConfigSetting setting = sut.build(); + + // then + EzySimpleSslConfigSetting expectation = new EzySimpleSslConfigSetting(); + expectation.setFile(file); + expectation.setLoader(loader); + expectation.setContextFactoryBuilder(contextFactoryBuilder); + Asserts.assertEquals(expectation, setting); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyWebSocketSettingBuilderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyWebSocketSettingBuilderTest.java index d63326680..f6fedbcd4 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyWebSocketSettingBuilderTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyWebSocketSettingBuilderTest.java @@ -7,17 +7,17 @@ import com.tvd12.test.assertion.Asserts; public class EzyWebSocketSettingBuilderTest { - - @Test - public void test() { - // given - EzyWebSocketSettingBuilder sut = new EzyWebSocketSettingBuilder() - .managementEnable(true); - - // when - EzySimpleWebSocketSetting setting = sut.build(); - - // then - Asserts.assertEquals(true, setting.isManagementEnable()); - } + + @Test + public void test() { + // given + EzyWebSocketSettingBuilder sut = new EzyWebSocketSettingBuilder() + .managementEnable(true); + + // when + EzySimpleWebSocketSetting setting = sut.build(); + + // then + Asserts.assertEquals(true, setting.isManagementEnable()); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSessionTicketsQueueTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSessionTicketsQueueTest.java index 3340bb9e2..fa7a239d6 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSessionTicketsQueueTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSessionTicketsQueueTest.java @@ -48,28 +48,28 @@ public void test() { @Test public void takeInactiveSession() throws Exception { - // given - EzyBlockingSessionTicketsQueue sut = new EzyBlockingSessionTicketsQueue(); - - MySession session = new MySession(); - session.setActivated(false); - sut.add(session); - - Thread newThread = new Thread(() -> { - // when - EzySession takeSession; - try { - takeSession = sut.take(); - } catch (InterruptedException e) { - return; - } - - // then - Asserts.assertEquals(session, takeSession); - }); - newThread.start(); - Thread.sleep(300L); - newThread.interrupt(); + // given + EzyBlockingSessionTicketsQueue sut = new EzyBlockingSessionTicketsQueue(); + + MySession session = new MySession(); + session.setActivated(false); + sut.add(session); + + Thread newThread = new Thread(() -> { + // when + EzySession takeSession; + try { + takeSession = sut.take(); + } catch (InterruptedException e) { + return; + } + + // then + Asserts.assertEquals(session, takeSession); + }); + newThread.start(); + Thread.sleep(300L); + newThread.interrupt(); } public static class MySession extends EzyAbstractSession { diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSocketUserRemovalQueueTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSocketUserRemovalQueueTest.java index 493dc6295..e8328ed8f 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSocketUserRemovalQueueTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyBlockingSocketUserRemovalQueueTest.java @@ -23,11 +23,11 @@ public void test() { assert queue.size() == 0; try { - queue.add(removal); - System.out.println(queue.take()); + queue.add(removal); + System.out.println(queue.take()); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyNonBlockingPacketQueueTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyNonBlockingPacketQueueTest.java index 9fc13f0f8..3e7ef5ba1 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyNonBlockingPacketQueueTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzyNonBlockingPacketQueueTest.java @@ -35,30 +35,30 @@ public void test2() { @Test public void clearTest() { - // given - EzyNonBlockingRequestQueue sut = new EzyNonBlockingRequestQueue(); - EzySocketRequest socketRequest = mock(EzySocketRequest.class); - sut.add(socketRequest); - - // when - sut.clear(); - - // then - Asserts.assertTrue(sut.isEmpty()); + // given + EzyNonBlockingRequestQueue sut = new EzyNonBlockingRequestQueue(); + EzySocketRequest socketRequest = mock(EzySocketRequest.class); + sut.add(socketRequest); + + // when + sut.clear(); + + // then + Asserts.assertTrue(sut.isEmpty()); } @Test public void isFullTest() { - // given - EzyNonBlockingRequestQueue sut = new EzyNonBlockingRequestQueue(0); - EzySocketRequest socketRequest = mock(EzySocketRequest.class); - - // when - boolean result = sut.add(socketRequest); - - // then - Asserts.assertTrue(sut.isFull()); - Asserts.assertFalse(result); + // given + EzyNonBlockingRequestQueue sut = new EzyNonBlockingRequestQueue(0); + EzySocketRequest socketRequest = mock(EzySocketRequest.class); + + // when + boolean result = sut.add(socketRequest); + + // then + Asserts.assertTrue(sut.isFull()); + Asserts.assertFalse(result); } public static class Packet extends EzySimplePacket { diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySessionTicketsRequestQueuesTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySessionTicketsRequestQueuesTest.java index 266221f05..46b9b54a2 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySessionTicketsRequestQueuesTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySessionTicketsRequestQueuesTest.java @@ -19,50 +19,50 @@ public class EzySessionTicketsRequestQueuesTest { - @Test - public void addSystemRequest() { - // given - EzySession session = mock(EzySession.class); - EzyArray data = EzyEntityArrays.newArray( - EzyCommand.APP_ACCESS.getId(), - EzyEmptyObject.getInstance()); - EzySocketRequest socketRequest = new EzySimpleSocketRequest(session, data); - - EzyRequestQueue queue = mock(EzyRequestQueue.class); - when(queue.isEmpty()).thenReturn(false); - when(queue.add(socketRequest)).thenReturn(false); - when(session.getSystemRequestQueue()).thenReturn(queue); - - EzySessionTicketsRequestQueues sut = new EzySessionTicketsRequestQueues(); - - // when - boolean result = sut.addRequest(socketRequest); - - // then - Asserts.assertFalse(result); - Asserts.assertTrue(sut.getSystemQueue().isEmpty()); - } - - @Test - public void addSystemRequestWithEmptyQueue() { - // given - EzySession session = mock(EzySession.class); - EzyArray data = EzyEntityArrays.newArray( - EzyCommand.APP_ACCESS.getId(), - EzyEmptyObject.getInstance()); - EzySocketRequest socketRequest = new EzySimpleSocketRequest(session, data); - - EzyRequestQueue queue = mock(EzyRequestQueue.class); - when(queue.isEmpty()).thenReturn(true); - when(session.getSystemRequestQueue()).thenReturn(queue); - - EzySessionTicketsRequestQueues sut = new EzySessionTicketsRequestQueues(); - - // when - boolean result = sut.addRequest(socketRequest); - - // then - Asserts.assertFalse(result); - Asserts.assertTrue(sut.getSystemQueue().isEmpty()); - } + @Test + public void addSystemRequest() { + // given + EzySession session = mock(EzySession.class); + EzyArray data = EzyEntityArrays.newArray( + EzyCommand.APP_ACCESS.getId(), + EzyEmptyObject.getInstance()); + EzySocketRequest socketRequest = new EzySimpleSocketRequest(session, data); + + EzyRequestQueue queue = mock(EzyRequestQueue.class); + when(queue.isEmpty()).thenReturn(false); + when(queue.add(socketRequest)).thenReturn(false); + when(session.getSystemRequestQueue()).thenReturn(queue); + + EzySessionTicketsRequestQueues sut = new EzySessionTicketsRequestQueues(); + + // when + boolean result = sut.addRequest(socketRequest); + + // then + Asserts.assertFalse(result); + Asserts.assertTrue(sut.getSystemQueue().isEmpty()); + } + + @Test + public void addSystemRequestWithEmptyQueue() { + // given + EzySession session = mock(EzySession.class); + EzyArray data = EzyEntityArrays.newArray( + EzyCommand.APP_ACCESS.getId(), + EzyEmptyObject.getInstance()); + EzySocketRequest socketRequest = new EzySimpleSocketRequest(session, data); + + EzyRequestQueue queue = mock(EzyRequestQueue.class); + when(queue.isEmpty()).thenReturn(true); + when(session.getSystemRequestQueue()).thenReturn(queue); + + EzySessionTicketsRequestQueues sut = new EzySessionTicketsRequestQueues(); + + // when + boolean result = sut.addRequest(socketRequest); + + // then + Asserts.assertFalse(result); + Asserts.assertTrue(sut.getSystemQueue().isEmpty()); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleBytesPackageTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleBytesPackageTest.java index b9c072c0d..efdac26ad 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleBytesPackageTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleBytesPackageTest.java @@ -7,12 +7,12 @@ import com.tvd12.test.base.BaseTest; public class EzySimpleBytesPackageTest extends BaseTest { - - @Test - public void test() { - EzySimpleBytesPackage pack = new EzySimpleBytesPackage(); - pack.setTransportType(EzyTransportType.TCP); - assert pack.getTransportType() == EzyTransportType.TCP; - } + + @Test + public void test() { + EzySimpleBytesPackage pack = new EzySimpleBytesPackage(); + pack.setTransportType(EzyTransportType.TCP); + assert pack.getTransportType() == EzyTransportType.TCP; + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimplePackageTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimplePackageTest.java index 8b74a8fca..5c2b5c44e 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimplePackageTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimplePackageTest.java @@ -7,12 +7,12 @@ import com.tvd12.test.base.BaseTest; public class EzySimplePackageTest extends BaseTest { - - @Test - public void test() { - EzySimplePackage pack = new EzySimplePackage(); - pack.setTransportType(EzyTransportType.TCP); - assert pack.getTransportType() == EzyTransportType.TCP; - } + + @Test + public void test() { + EzySimplePackage pack = new EzySimplePackage(); + pack.setTransportType(EzyTransportType.TCP); + assert pack.getTransportType() == EzyTransportType.TCP; + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleSocketRequestTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleSocketRequestTest.java index 6aa22020b..36e046092 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleSocketRequestTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySimpleSocketRequestTest.java @@ -13,15 +13,15 @@ public class EzySimpleSocketRequestTest extends BaseTest { - @Test - public void test() { - EzyAbstractSession session = spy(EzyAbstractSession.class); - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.APP_ACCESS.getId()) - .build(); - EzySimpleSocketRequest request = new EzySimpleSocketRequest(session, data); - - assert request.isSystemRequest(); - } - + @Test + public void test() { + EzyAbstractSession session = spy(EzyAbstractSession.class); + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.APP_ACCESS.getId()) + .build(); + EzySimpleSocketRequest request = new EzySimpleSocketRequest(session, data); + + assert request.isSystemRequest(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketDisconnectionHandlingLoopHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketDisconnectionHandlingLoopHandlerTest.java index d86655622..fe14aa562 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketDisconnectionHandlingLoopHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketDisconnectionHandlingLoopHandlerTest.java @@ -7,13 +7,13 @@ public class EzySocketDisconnectionHandlingLoopHandlerTest { - @Test - public void test() { - EzySocketDisconnectionHandlingLoopHandler handler = new EzySocketDisconnectionHandlingLoopHandler(); - MethodInvoker.create() - .object(handler) - .method("getThreadName") - .invoke(); - } - + @Test + public void test() { + EzySocketDisconnectionHandlingLoopHandler handler = new EzySocketDisconnectionHandlingLoopHandler(); + MethodInvoker.create() + .object(handler) + .method("getThreadName") + .invoke(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlerTest.java index 67b30d489..0c3c58138 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlerTest.java @@ -11,32 +11,32 @@ public class EzySocketExtensionRequestHandlerTest { - @Test - public void test() { - EzySocketExtensionRequestHandler handler = new EzySocketExtensionRequestHandler(); - MethodInvoker.create() - .object(handler) - .method("getRequestType") - .invoke(); - } - - @Test - public void getRequestQueueTest() { - // given - EzySocketExtensionRequestHandler sut = new EzySocketExtensionRequestHandler(); - - EzySession session = mock(EzySession.class); - EzyRequestQueue requestQueue = mock(EzyRequestQueue.class); - when(session.getExtensionRequestQueue()).thenReturn(requestQueue); - - // when - EzyRequestQueue result = MethodInvoker.create() - .object(sut) - .method("getRequestQueue") - .param(EzySession.class, session) - .call(); - - // then - Asserts.assertEquals(requestQueue, result); - } + @Test + public void test() { + EzySocketExtensionRequestHandler handler = new EzySocketExtensionRequestHandler(); + MethodInvoker.create() + .object(handler) + .method("getRequestType") + .invoke(); + } + + @Test + public void getRequestQueueTest() { + // given + EzySocketExtensionRequestHandler sut = new EzySocketExtensionRequestHandler(); + + EzySession session = mock(EzySession.class); + EzyRequestQueue requestQueue = mock(EzyRequestQueue.class); + when(session.getExtensionRequestQueue()).thenReturn(requestQueue); + + // when + EzyRequestQueue result = MethodInvoker.create() + .object(sut) + .method("getRequestQueue") + .param(EzySession.class, session) + .call(); + + // then + Asserts.assertEquals(requestQueue, result); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlingLoopHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlingLoopHandlerTest.java index 43ba3c6e1..f2dc8df0f 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlingLoopHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketExtensionRequestHandlingLoopHandlerTest.java @@ -7,13 +7,13 @@ public class EzySocketExtensionRequestHandlingLoopHandlerTest { - @Test - public void test() { - EzySocketExtensionRequestHandlingLoopHandler handler = new EzySocketExtensionRequestHandlingLoopHandler(); - MethodInvoker.create() - .object(handler) - .method("getRequestType") - .invoke(); - } - + @Test + public void test() { + EzySocketExtensionRequestHandlingLoopHandler handler = new EzySocketExtensionRequestHandlingLoopHandler(); + MethodInvoker.create() + .object(handler) + .method("getRequestType") + .invoke(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketRequestHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketRequestHandlerTest.java index 8b11c0315..c20a1b5b3 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketRequestHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketRequestHandlerTest.java @@ -114,7 +114,7 @@ public void processRequestQueue0InterrupTest() throws Exception { @Test public void processRequestQueue0RemainTest() { - // given + // given ExEzySocketRequestHandler handler = new ExEzySocketRequestHandler(); EzySocketDataHandlerGroup handlerGroup = mock(EzySocketDataHandlerGroup.class); @@ -152,7 +152,7 @@ protected String getRequestType() { @Override protected EzyRequestQueue getRequestQueue(EzySession session) { - return session.getExtensionRequestQueue(); + return session.getExtensionRequestQueue(); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketStreamHandlingLoopHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketStreamHandlingLoopHandlerTest.java index a65af18c1..5c583d25b 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketStreamHandlingLoopHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketStreamHandlingLoopHandlerTest.java @@ -7,13 +7,13 @@ public class EzySocketStreamHandlingLoopHandlerTest { - @Test - public void test() { - EzySocketStreamHandlingLoopHandler handler = new EzySocketStreamHandlingLoopHandler(); - MethodInvoker.create() - .object(handler) - .method("getThreadName") - .invoke(); - } - + @Test + public void test() { + EzySocketStreamHandlingLoopHandler handler = new EzySocketStreamHandlingLoopHandler(); + MethodInvoker.create() + .object(handler) + .method("getThreadName") + .invoke(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlerTest.java index f774c0da4..15c05f4aa 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlerTest.java @@ -13,32 +13,32 @@ public class EzySocketSystemRequestHandlerTest { - @Test - public void test() { - EzySocketSystemRequestHandler handler = new EzySocketSystemRequestHandler(); - MethodInvoker.create() - .object(handler) - .method("getRequestType") - .invoke(); - } - - @Test - public void getRequestQueueTest() { - // given - EzySocketSystemRequestHandler sut = new EzySocketSystemRequestHandler(); - - EzySession session = mock(EzySession.class); - EzyRequestQueue requestQueue = mock(EzyRequestQueue.class); - when(session.getSystemRequestQueue()).thenReturn(requestQueue); - - // when - EzyRequestQueue result = MethodInvoker.create() - .object(sut) - .method("getRequestQueue") - .param(EzySession.class, session) - .call(); - - // then - Asserts.assertEquals(requestQueue, result); - } + @Test + public void test() { + EzySocketSystemRequestHandler handler = new EzySocketSystemRequestHandler(); + MethodInvoker.create() + .object(handler) + .method("getRequestType") + .invoke(); + } + + @Test + public void getRequestQueueTest() { + // given + EzySocketSystemRequestHandler sut = new EzySocketSystemRequestHandler(); + + EzySession session = mock(EzySession.class); + EzyRequestQueue requestQueue = mock(EzyRequestQueue.class); + when(session.getSystemRequestQueue()).thenReturn(requestQueue); + + // when + EzyRequestQueue result = MethodInvoker.create() + .object(sut) + .method("getRequestQueue") + .param(EzySession.class, session) + .call(); + + // then + Asserts.assertEquals(requestQueue, result); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlingLoopHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlingLoopHandlerTest.java index 10f6cdd60..a828a5a91 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlingLoopHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketSystemRequestHandlingLoopHandlerTest.java @@ -7,13 +7,13 @@ public class EzySocketSystemRequestHandlingLoopHandlerTest { - @Test - public void test() { - EzySocketSystemRequestHandlingLoopHandler handler = new EzySocketSystemRequestHandlingLoopHandler(); - MethodInvoker.create() - .object(handler) - .method("getRequestType") - .invoke(); - } - + @Test + public void test() { + EzySocketSystemRequestHandlingLoopHandler handler = new EzySocketSystemRequestHandlingLoopHandler(); + MethodInvoker.create() + .object(handler) + .method("getRequestType") + .invoke(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketUserRemovalHandlingLoopHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketUserRemovalHandlingLoopHandlerTest.java index 328477b4c..f9a6b3229 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketUserRemovalHandlingLoopHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketUserRemovalHandlingLoopHandlerTest.java @@ -7,13 +7,13 @@ public class EzySocketUserRemovalHandlingLoopHandlerTest { - @Test - public void test() { - EzySocketUserRemovalHandlingLoopHandler handler = new EzySocketUserRemovalHandlingLoopHandler(); - MethodInvoker.create() - .object(handler) - .method("getThreadName") - .invoke(); - } - + @Test + public void test() { + EzySocketUserRemovalHandlingLoopHandler handler = new EzySocketUserRemovalHandlingLoopHandler(); + MethodInvoker.create() + .object(handler) + .method("getThreadName") + .invoke(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketWritingLoopHandlerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketWritingLoopHandlerTest.java index d8b1f31c9..b453844e1 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketWritingLoopHandlerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/socket/EzySocketWritingLoopHandlerTest.java @@ -7,13 +7,13 @@ public class EzySocketWritingLoopHandlerTest { - @Test - public void test() { - EzySocketWritingLoopHandler handler = new EzySocketWritingLoopHandler(); - MethodInvoker.create() - .object(handler) - .method("getThreadName") - .invoke(); - } - + @Test + public void test() { + EzySocketWritingLoopHandler handler = new EzySocketWritingLoopHandler(); + MethodInvoker.create() + .object(handler) + .method("getThreadName") + .invoke(); + } + } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySimpleSslContextFactoryTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySimpleSslContextFactoryTest.java index 375794d20..1dbdc65a9 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySimpleSslContextFactoryTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySimpleSslContextFactoryTest.java @@ -35,22 +35,22 @@ public String getAlgorithm(EzySslConfig config) { @Test public void getAlgorithmTest() { - // given - EzySimpleSslContextFactory sut = new EzySimpleSslContextFactory() { - protected String getDefaultAlgorithm() { - return null; - }; - }; - EzySslConfig sslConfig = mock(EzySslConfig.class); - - // when - String algorithm = MethodInvoker.create() - .object(sut) - .method("getAlgorithm") - .param(EzySslConfig.class, sslConfig) - .call(); - - // then - Asserts.assertEquals("SunX509", algorithm); + // given + EzySimpleSslContextFactory sut = new EzySimpleSslContextFactory() { + protected String getDefaultAlgorithm() { + return null; + }; + }; + EzySslConfig sslConfig = mock(EzySslConfig.class); + + // when + String algorithm = MethodInvoker.create() + .object(sut) + .method("getAlgorithm") + .param(EzySslConfig.class, sslConfig) + .call(); + + // then + Asserts.assertEquals("SunX509", algorithm); } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzySimpleSessionManagerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzySimpleSessionManagerTest.java index 06b3b52bb..04121c7df 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzySimpleSessionManagerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzySimpleSessionManagerTest.java @@ -109,73 +109,73 @@ public String generate() { assertEquals(manager.getAllSessions(), Lists.newArrayList(session, session2)); } - @Test + @Test public void clearNullSessionTest() { - // given - MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() + // given + MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() .build(); - - // when - // then - manager.clearSession(null); + + // when + // then + manager.clearSession(null); } - - @Test + + @Test public void checkMaxSessionsTest() { - // given - MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() - .maxSessions(0) + // given + MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() + .maxSessions(0) .build(); - // when - Throwable e = Asserts.assertThrows(() -> - manager.provideSession(EzyConnectionType.SOCKET) - ); - - // then - Asserts.assertEquals(EzyMaxSessionException.class, e.getClass()); + // when + Throwable e = Asserts.assertThrows(() -> + manager.provideSession(EzyConnectionType.SOCKET) + ); + + // then + Asserts.assertEquals(EzyMaxSessionException.class, e.getClass()); } - - @Test - public void isUnloggedInSessionTrueTest() { - // given - MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() + + @Test + public void isUnloggedInSessionTrueTest() { + // given + MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() .build(); - EzySession session = mock(EzySession.class); - when(session.isLoggedIn()).thenReturn(false); - when(session.isActivated()).thenReturn(true); - when(session.getMaxWaitingTime()).thenReturn(0L); - when(session.getCreationTime()).thenReturn(System.currentTimeMillis() + 1); - - // when - Boolean result = MethodInvoker.create() - .object(manager) - .method("isUnloggedInSession") - .param(EzySession.class, session) - .invoke(Boolean.class); - - // then - Asserts.assertTrue(result); - } - - @Test - public void isUnloggedInSessionFalseTest() { - // given - MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() + EzySession session = mock(EzySession.class); + when(session.isLoggedIn()).thenReturn(false); + when(session.isActivated()).thenReturn(true); + when(session.getMaxWaitingTime()).thenReturn(0L); + when(session.getCreationTime()).thenReturn(System.currentTimeMillis() + 1); + + // when + Boolean result = MethodInvoker.create() + .object(manager) + .method("isUnloggedInSession") + .param(EzySession.class, session) + .invoke(Boolean.class); + + // then + Asserts.assertTrue(result); + } + + @Test + public void isUnloggedInSessionFalseTest() { + // given + MyTestSessionManager manager = (MyTestSessionManager) new MyTestSessionManager.Builder() .build(); - EzySession session = mock(EzySession.class); - when(session.isLoggedIn()).thenReturn(false); - when(session.isActivated()).thenReturn(true); - when(session.getMaxWaitingTime()).thenReturn(1000L); - when(session.getCreationTime()).thenReturn(System.currentTimeMillis() - 100L); - - // when - Boolean result = MethodInvoker.create() - .object(manager) - .method("isUnloggedInSession") - .param(EzySession.class, session) - .invoke(Boolean.class); - - // then - Asserts.assertFalse(result); - } + EzySession session = mock(EzySession.class); + when(session.isLoggedIn()).thenReturn(false); + when(session.isActivated()).thenReturn(true); + when(session.getMaxWaitingTime()).thenReturn(1000L); + when(session.getCreationTime()).thenReturn(System.currentTimeMillis() - 100L); + + // when + Boolean result = MethodInvoker.create() + .object(manager) + .method("isUnloggedInSession") + .param(EzySession.class, session) + .invoke(Boolean.class); + + // then + Asserts.assertFalse(result); + } } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyZoneUserManagerImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyZoneUserManagerImplTest.java index 138b2419f..04a5601a1 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyZoneUserManagerImplTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyZoneUserManagerImplTest.java @@ -79,77 +79,77 @@ public void test() throws Exception { @Test public void unmapSessionUserWithUserIsNull() { - // given - EzyZoneUserManagerImpl sut = newZoneUserManager(); - EzySession session = mock(EzySession.class); - - // when - sut.unmapSessionUser(session, mock(EzyConstant.class)); - - // then - Asserts.assertNull(sut.getUser(session)); + // given + EzyZoneUserManagerImpl sut = newZoneUserManager(); + EzySession session = mock(EzySession.class); + + // when + sut.unmapSessionUser(session, mock(EzyConstant.class)); + + // then + Asserts.assertNull(sut.getUser(session)); } @Test public void unmapSessionUserWithSessionCountGreaterThan1() { - // given - EzyZoneUserManagerImpl sut = newZoneUserManager(); - EzySession session = mock(EzySession.class); - - EzyUser user = mock(EzyUser.class); - when(user.getSessionCount()).thenReturn(1); - - Map usersBySession = FieldUtil.getFieldValue(sut, "usersBySession"); - usersBySession.put(session, user); - - // when - sut.unmapSessionUser(session, mock(EzyConstant.class)); - - // then - Asserts.assertNull(sut.getUser(session)); + // given + EzyZoneUserManagerImpl sut = newZoneUserManager(); + EzySession session = mock(EzySession.class); + + EzyUser user = mock(EzyUser.class); + when(user.getSessionCount()).thenReturn(1); + + Map usersBySession = FieldUtil.getFieldValue(sut, "usersBySession"); + usersBySession.put(session, user); + + // when + sut.unmapSessionUser(session, mock(EzyConstant.class)); + + // then + Asserts.assertNull(sut.getUser(session)); } @Test public void unmapSessionUserWithmaxIdleTimeGreaterThan0() { - // given - EzyZoneUserManagerImpl sut = newZoneUserManager(); - EzySession session = mock(EzySession.class); - - EzyUser user = mock(EzyUser.class); - when(user.getMaxIdleTime()).thenReturn(1000L); - - Map usersBySession = FieldUtil.getFieldValue(sut, "usersBySession"); - usersBySession.put(session, user); - - // when - sut.unmapSessionUser(session, mock(EzyConstant.class)); - - // then - Asserts.assertNull(sut.getUser(session)); + // given + EzyZoneUserManagerImpl sut = newZoneUserManager(); + EzySession session = mock(EzySession.class); + + EzyUser user = mock(EzyUser.class); + when(user.getMaxIdleTime()).thenReturn(1000L); + + Map usersBySession = FieldUtil.getFieldValue(sut, "usersBySession"); + usersBySession.put(session, user); + + // when + sut.unmapSessionUser(session, mock(EzyConstant.class)); + + // then + Asserts.assertNull(sut.getUser(session)); } @Test public void startIdleValidationServiceWithIdleValidationService() { - // given - EzyZoneUserManagerImpl sut = newZoneUserManager(); - - // when - MethodUtil.invokeMethod("startIdleValidationService", sut); - - // then - Asserts.assertNull(FieldUtil.getFieldValue(sut, "idleValidationService")); + // given + EzyZoneUserManagerImpl sut = newZoneUserManager(); + + // when + MethodUtil.invokeMethod("startIdleValidationService", sut); + + // then + Asserts.assertNull(FieldUtil.getFieldValue(sut, "idleValidationService")); } @Test public void destroyWithIdleValidationService() { - // given - EzyZoneUserManagerImpl sut = newZoneUserManager(); - - // when - sut.destroy(); - - // then - Asserts.assertNull(FieldUtil.getFieldValue(sut, "idleValidationService")); + // given + EzyZoneUserManagerImpl sut = newZoneUserManager(); + + // when + sut.destroy(); + + // then + Asserts.assertNull(FieldUtil.getFieldValue(sut, "idleValidationService")); } private EzySimpleUser newAndAddIdleUser(String username, EzyZoneUserManagerImpl manager) { @@ -165,7 +165,7 @@ private EzySimpleUser newAndAddIdleUser(String username, EzyZoneUserManagerImpl } private EzyZoneUserManagerImpl newZoneUserManager() { - EzyServerContext serverContext = mock(EzyServerContext.class); + EzyServerContext serverContext = mock(EzyServerContext.class); EzyZoneContext zoneContext = mock(EzyZoneContext.class); when(serverContext.getZoneContext(1)).thenReturn(zoneContext); TestBlockingSocketUserRemovalQueue queue = new TestBlockingSocketUserRemovalQueue(); diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/V121SessionManagerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/V121SessionManagerTest.java index 0fec66af9..66f06b18e 100644 --- a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/V121SessionManagerTest.java +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/V121SessionManagerTest.java @@ -18,101 +18,101 @@ public class V121SessionManagerTest { - @Test - public void inspectTest() throws Exception { - // given - EzySocketDisconnectionQueue disconnectionQueue = - new EzyBlockingSocketDisconnectionQueue(); - SessionManager sut = (SessionManager) new SessionManager.Builder() - .validationInterval(100) - .validationDelay(100) - .objectFactory(() -> new Session(disconnectionQueue)) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyChannel channel1 = mock(EzyChannel.class); - when(channel1.getConnection()).thenReturn(new Object()); - EzyChannel channel2 = mock(EzyChannel.class); - when(channel2.getConnection()).thenReturn(new Object()); - EzyChannel channel3 = mock(EzyChannel.class); - when(channel3.getConnection()).thenReturn(new Object()); - - Session session1 = sut.provideSession(channel1); - session1.setLoggedIn(true); - session1.setLastReadTime(System.currentTimeMillis()); - Session session2 = sut.provideSession(channel2); - session2.setLoggedIn(true); - session2.setLastReadTime(System.currentTimeMillis()); - Session session3 = sut.provideSession(channel3); - session3.setLoggedIn(true); - session3.setLastReadTime(System.currentTimeMillis()); - - Thread[] threads = new Thread[10]; - for(int i = 0 ; i < threads.length ; ++i) { - threads[i] = new Thread(() -> { - long start = System.currentTimeMillis(); - long elapsedTime = 0; - while(elapsedTime < 100) { - EzyChannel channel = mock(EzyChannel.class); - when(channel.getConnection()).thenReturn(new Object()); - sut.provideSession(channel); - elapsedTime = System.currentTimeMillis() - start; - } - }); - } - - Thread disconnectionThread = new Thread(() -> { - while(true) { - try { - EzySocketDisconnection item = disconnectionQueue.take(); - sut.clearSession((Session) item.getSession()); - } - catch (Exception e) { - e.printStackTrace(); - } - } - }); - disconnectionThread.start(); - - // when - sut.start(); - - for(int i = 0 ; i < threads.length ; ++i) { - threads[i].start(); - } - Thread.sleep(1000); - disconnectionThread.interrupt(); - - - // then - Asserts.assertEquals(3, sut.getAllSessionCount()); - sut.destroy(); - } - - private static class Session extends EzyAbstractSession { - private static final long serialVersionUID = -3368343048551431719L; - - private static final AtomicLong ID_GENTOR = new AtomicLong(); - - private Session(EzySocketDisconnectionQueue disconnectionQueue) { - this.maxWaitingTime = 100; - this.id = ID_GENTOR.incrementAndGet(); - this.activated = true; - this.disconnectionQueue = disconnectionQueue; - } - } - - private static class SessionManager extends EzySimpleSessionManager { - - private SessionManager(Builder builder) { - super(builder); - } - - private static class Builder extends EzySimpleSessionManager.Builder { - - @Override - public SessionManager build() { - return new SessionManager(this); - } - } - } + @Test + public void inspectTest() throws Exception { + // given + EzySocketDisconnectionQueue disconnectionQueue = + new EzyBlockingSocketDisconnectionQueue(); + SessionManager sut = (SessionManager) new SessionManager.Builder() + .validationInterval(100) + .validationDelay(100) + .objectFactory(() -> new Session(disconnectionQueue)) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyChannel channel1 = mock(EzyChannel.class); + when(channel1.getConnection()).thenReturn(new Object()); + EzyChannel channel2 = mock(EzyChannel.class); + when(channel2.getConnection()).thenReturn(new Object()); + EzyChannel channel3 = mock(EzyChannel.class); + when(channel3.getConnection()).thenReturn(new Object()); + + Session session1 = sut.provideSession(channel1); + session1.setLoggedIn(true); + session1.setLastReadTime(System.currentTimeMillis()); + Session session2 = sut.provideSession(channel2); + session2.setLoggedIn(true); + session2.setLastReadTime(System.currentTimeMillis()); + Session session3 = sut.provideSession(channel3); + session3.setLoggedIn(true); + session3.setLastReadTime(System.currentTimeMillis()); + + Thread[] threads = new Thread[10]; + for(int i = 0 ; i < threads.length ; ++i) { + threads[i] = new Thread(() -> { + long start = System.currentTimeMillis(); + long elapsedTime = 0; + while(elapsedTime < 100) { + EzyChannel channel = mock(EzyChannel.class); + when(channel.getConnection()).thenReturn(new Object()); + sut.provideSession(channel); + elapsedTime = System.currentTimeMillis() - start; + } + }); + } + + Thread disconnectionThread = new Thread(() -> { + while(true) { + try { + EzySocketDisconnection item = disconnectionQueue.take(); + sut.clearSession((Session) item.getSession()); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); + disconnectionThread.start(); + + // when + sut.start(); + + for(int i = 0 ; i < threads.length ; ++i) { + threads[i].start(); + } + Thread.sleep(1000); + disconnectionThread.interrupt(); + + + // then + Asserts.assertEquals(3, sut.getAllSessionCount()); + sut.destroy(); + } + + private static class Session extends EzyAbstractSession { + private static final long serialVersionUID = -3368343048551431719L; + + private static final AtomicLong ID_GENTOR = new AtomicLong(); + + private Session(EzySocketDisconnectionQueue disconnectionQueue) { + this.maxWaitingTime = 100; + this.id = ID_GENTOR.incrementAndGet(); + this.activated = true; + this.disconnectionQueue = disconnectionQueue; + } + } + + private static class SessionManager extends EzySimpleSessionManager { + + private SessionManager(Builder builder) { + super(builder); + } + + private static class Builder extends EzySimpleSessionManager.Builder { + + @Override + public SessionManager build() { + return new SessionManager(this); + } + } + } } diff --git a/ezyfox-server-core/src/test/resources/AllTests.tng.xml b/ezyfox-server-core/src/test/resources/AllTests.tng.xml index 1b4790c8d..e41ff01c7 100644 --- a/ezyfox-server-core/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-core/src/test/resources/AllTests.tng.xml @@ -1,165 +1,165 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ezyfox-server-core/src/test/resources/ezy-settings-1.0.0.xsd b/ezyfox-server-core/src/test/resources/ezy-settings-1.0.0.xsd index 258fda9c8..f62a5447c 100644 --- a/ezyfox-server-core/src/test/resources/ezy-settings-1.0.0.xsd +++ b/ezyfox-server-core/src/test/resources/ezy-settings-1.0.0.xsd @@ -1,178 +1,178 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + xmlns="http://www.tvd12.com/schema/ezyfox/settings" elementFormDefault="qualified" attributeFormDefault="unqualified"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ezyfox-server-core/src/test/resources/ezy-settings.xml b/ezyfox-server-core/src/test/resources/ezy-settings.xml index 1f566e7e5..6f01ad51b 100644 --- a/ezyfox-server-core/src/test/resources/ezy-settings.xml +++ b/ezyfox-server-core/src/test/resources/ezy-settings.xml @@ -1,72 +1,72 @@ - - localhost - 30000 - - - true - - - - 3005 -
0.0.0.0
- true - 65536 - com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator -
- - - 2208 -
0.0.0.0
- true - 2812 - 65536 - false - - ssl-config.properties - com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader - com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder - - com.tvd12.ezyfoxserver.netty.codec.JacksonWsCodecCreator -
- - - - admin - admin - admin - - - - - 15000 - 30000 - - 20 - DISCONNECT_SESSION - - - - - - SERVER_READY - com.tvd12.ezyfoxserver.handler.ServerReadyHandler - - - - - - example - ezy-zone-settings.xml - true - - - + xsi:schemaLocation="http://www.tvd12.com/schema/ezyfox/settings + ezy-settings-1.0.0.xsd" + xmlns="http://www.tvd12.com/schema/ezyfox/settings" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + + localhost + 30000 + + + true + + + + 3005 +
0.0.0.0
+ true + 65536 + com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator +
+ + + 2208 +
0.0.0.0
+ true + 2812 + 65536 + false + + ssl-config.properties + com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader + com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder + + com.tvd12.ezyfoxserver.netty.codec.JacksonWsCodecCreator +
+ + + + admin + admin + admin + + + + + 15000 + 30000 + + 20 + DISCONNECT_SESSION + + + + + + SERVER_READY + com.tvd12.ezyfoxserver.handler.ServerReadyHandler + + + + + + example + ezy-zone-settings.xml + true + + +
- \ No newline at end of file + diff --git a/ezyfox-server-core/src/test/resources/ezy-zone-settings-1.0.0.xsd b/ezyfox-server-core/src/test/resources/ezy-zone-settings-1.0.0.xsd index f807a35f7..c3def13fc 100644 --- a/ezyfox-server-core/src/test/resources/ezy-zone-settings-1.0.0.xsd +++ b/ezyfox-server-core/src/test/resources/ezy-zone-settings-1.0.0.xsd @@ -1,151 +1,151 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + xmlns="http://www.tvd12.com/schema/ezyfox/settings" elementFormDefault="qualified" attributeFormDefault="unqualified"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ezyfox-server-core/src/test/resources/ezy-zone-settings.xml b/ezyfox-server-core/src/test/resources/ezy-zone-settings.xml index 4f54fac18..87c5aece3 100644 --- a/ezyfox-server-core/src/test/resources/ezy-zone-settings.xml +++ b/ezyfox-server-core/src/test/resources/ezy-zone-settings.xml @@ -1,56 +1,56 @@ - - 10000 - - - true - Guest# - 15000 - true - 15 - ^[a-zA-Z0-9_.#]{3,36}$ - - - - true - - - - - SERVER_READY - com.tvd12.ezyfoxserver.zone.handler.ServerReadyHandler - - - - - - ezyfox-chat - com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader - 10000 - 30 - config.properties - - - - - - ezyfox-auth-plugin - -1 - com.tvd12.ezyfoxserver.plugin.auth.EzyAuthPluginEntryLoader - 30 - config.properties - - USER_LOGIN - USER_ADDED - USER_REMOVED - - - + xsi:schemaLocation="http://www.tvd12.com/schema/ezyfox/settings + ezy-zone-settings-1.0.0.xsd" + xmlns="http://www.tvd12.com/schema/ezyfox/settings" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + + 10000 + + + true + Guest# + 15000 + true + 15 + ^[a-zA-Z0-9_.#]{3,36}$ + + + + true + + + + + SERVER_READY + com.tvd12.ezyfoxserver.zone.handler.ServerReadyHandler + + + + + + ezyfox-chat + com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader + 10000 + 30 + config.properties + + + + + + ezyfox-auth-plugin + -1 + com.tvd12.ezyfoxserver.plugin.auth.EzyAuthPluginEntryLoader + 30 + config.properties + + USER_LOGIN + USER_ADDED + USER_REMOVED + + + - \ No newline at end of file + diff --git a/ezyfox-server-core/src/test/resources/html/ws-index.html b/ezyfox-server-core/src/test/resources/html/ws-index.html index 67c9278d8..8c4aa2ffa 100644 --- a/ezyfox-server-core/src/test/resources/html/ws-index.html +++ b/ezyfox-server-core/src/test/resources/html/ws-index.html @@ -40,14 +40,14 @@ ws.onopen = function () { log('connected'); var rq = [ - 11, - [ - "clientKey", - "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJp80uI4ivZhcstEGxc0crz3Oe9ybHVI3DsqYOFUeh+Qv1mKr/OD8H328gc+s0Zf1i90FNs/kOeU+whq/sW3PNcCAwEAAQ==", - "reconnectToken#1", - "JAVA", - "1.0.0" - ] + 11, + [ + "clientKey", + "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJp80uI4ivZhcstEGxc0crz3Oe9ybHVI3DsqYOFUeh+Qv1mKr/OD8H328gc+s0Zf1i90FNs/kOeU+whq/sW3PNcCAwEAAQ==", + "reconnectToken#1", + "JAVA", + "1.0.0" + ] ]; ws.send(JSON.stringify(rq)); log("has sent handshake"); @@ -119,4 +119,4 @@ - \ No newline at end of file + diff --git a/ezyfox-server-core/src/test/resources/html/wss-index.html b/ezyfox-server-core/src/test/resources/html/wss-index.html index c2093cbcf..296dc21ae 100644 --- a/ezyfox-server-core/src/test/resources/html/wss-index.html +++ b/ezyfox-server-core/src/test/resources/html/wss-index.html @@ -107,4 +107,4 @@ - \ No newline at end of file + diff --git a/ezyfox-server-core/src/test/resources/index.html b/ezyfox-server-core/src/test/resources/index.html index 1575593e7..7a7371050 100644 --- a/ezyfox-server-core/src/test/resources/index.html +++ b/ezyfox-server-core/src/test/resources/index.html @@ -110,4 +110,4 @@ - \ No newline at end of file + diff --git a/ezyfox-server-core/test-data/settings/config.properties b/ezyfox-server-core/test-data/settings/config.properties index b068ab657..e7462422f 100644 --- a/ezyfox-server-core/test-data/settings/config.properties +++ b/ezyfox-server-core/test-data/settings/config.properties @@ -1,3 +1,3 @@ ezyfox.home=test-data ezyfox.version=1.0.0 -logger.config.file=logback.groovy \ No newline at end of file +logger.config.file=logback.groovy diff --git a/ezyfox-server-core/test-data/settings/ezy-settings-1.0.0.xsd b/ezyfox-server-core/test-data/settings/ezy-settings-1.0.0.xsd index 4a956b2bd..3c3f3dcd4 100644 --- a/ezyfox-server-core/test-data/settings/ezy-settings-1.0.0.xsd +++ b/ezyfox-server-core/test-data/settings/ezy-settings-1.0.0.xsd @@ -1,142 +1,142 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + xmlns="http://www.tvd12.com/schema/ezyfox/settings" elementFormDefault="qualified" attributeFormDefault="unqualified"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ezyfox-server-core/test-data/settings/ezy-settings.xml b/ezyfox-server-core/test-data/settings/ezy-settings.xml index 4b77e1b3a..ab1783966 100644 --- a/ezyfox-server-core/test-data/settings/ezy-settings.xml +++ b/ezyfox-server-core/test-data/settings/ezy-settings.xml @@ -1,66 +1,66 @@ - - 30000 - - - 3005 -
0.0.0.0
- true - 65536 - com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator -
- - - 2208 -
0.0.0.0
- true - 2812 - 65536 - false - - ssl-config.properties - com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader - com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder - - com.tvd12.ezyfoxserver.netty.codec.JacksonWsCodecCreator -
- - - - admin - admin - admin - - - - - true - 15000 - 30000 - - 20 - DISCONNECT_SESSION - - - - - - example - ezy-zone-settings.xml - true - - - example2 - ezy-zone-settings.xml - false - - - + xsi:schemaLocation="http://www.tvd12.com/schema/ezyfox/settings + ezy-settings-1.0.0.xsd" + xmlns="http://www.tvd12.com/schema/ezyfox/settings" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + + 30000 + + + 3005 +
0.0.0.0
+ true + 65536 + com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator +
+ + + 2208 +
0.0.0.0
+ true + 2812 + 65536 + false + + ssl-config.properties + com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader + com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder + + com.tvd12.ezyfoxserver.netty.codec.JacksonWsCodecCreator +
+ + + + admin + admin + admin + + + + + true + 15000 + 30000 + + 20 + DISCONNECT_SESSION + + + + + + example + ezy-zone-settings.xml + true + + + example2 + ezy-zone-settings.xml + false + + +
- \ No newline at end of file + diff --git a/ezyfox-server-core/test-data/settings/logback.groovy b/ezyfox-server-core/test-data/settings/logback.groovy index b637e0925..b36c7c9d9 100644 --- a/ezyfox-server-core/test-data/settings/logback.groovy +++ b/ezyfox-server-core/test-data/settings/logback.groovy @@ -23,4 +23,4 @@ appender("stdout", ConsoleAppender) { //pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%M %L - %msg%n" } } -root(DEBUG, ["stdout"]) \ No newline at end of file +root(DEBUG, ["stdout"]) diff --git a/ezyfox-server-core/test-data/settings/ssl-config.properties b/ezyfox-server-core/test-data/settings/ssl-config.properties index 9aba8b865..d9ee24dc5 100644 --- a/ezyfox-server-core/test-data/settings/ssl-config.properties +++ b/ezyfox-server-core/test-data/settings/ssl-config.properties @@ -1,3 +1,3 @@ ssl.key_store=ssl/ssl-key-store.txt ssl.keystore_password=ssl/ssl-keystore-password.txt -ssl.certificate_password=ssl/ssl-certificate-password.txt \ No newline at end of file +ssl.certificate_password=ssl/ssl-certificate-password.txt diff --git a/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings-1.0.0.xsd b/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings-1.0.0.xsd index 902bb35ca..3c41b7b2f 100644 --- a/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings-1.0.0.xsd +++ b/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings-1.0.0.xsd @@ -1,112 +1,112 @@ + xmlns="http://www.tvd12.com/schema/ezyfox/settings" elementFormDefault="qualified" attributeFormDefault="unqualified"> - - - - - - - - - - + + + + + + + + + + - - - - - - + + + + + + - - - - - + + + + + - - - - - - - - - - + + + + + + + + + + - - - - - + + + + + - - - - - - - - - - - + + + + + + + + + + + - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + - - - - - - - - - + + + + + - - - + + + + + + + - - - + + + + + + + + + - - - - - + + + - \ No newline at end of file + + + + + + + + + + + diff --git a/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings.xml b/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings.xml index 66643bb7a..eb7980519 100644 --- a/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings.xml +++ b/ezyfox-server-core/test-data/settings/zones/ezy-zone-settings.xml @@ -1,44 +1,44 @@ - - 10000 - - - true - Guest# - 15000 - 15 - ^[a-z0-9_.]{3,36}$ - - - - - ezyfox-chat - com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader - 10000 - 30 - config.properties - - - - - - ezyfox-auth-plugin - -1 - com.tvd12.ezyfoxserver.plugin.auth.EzyAuthPluginEntryLoader - 30 - config.properties - - USER_LOGIN - USER_ADDED - USER_REMOVED - - - + xsi:schemaLocation="http://www.tvd12.com/schema/ezyfox/settings + ezy-zone-settings-1.0.0.xsd" + xmlns="http://www.tvd12.com/schema/ezyfox/settings" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + + 10000 + + + true + Guest# + 15000 + 15 + ^[a-z0-9_.]{3,36}$ + + + + + ezyfox-chat + com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader + 10000 + 30 + config.properties + + + + + + ezyfox-auth-plugin + -1 + com.tvd12.ezyfoxserver.plugin.auth.EzyAuthPluginEntryLoader + 30 + config.properties + + USER_LOGIN + USER_ADDED + USER_REMOVED + + + - \ No newline at end of file + diff --git a/ezyfox-server-core/test-data1/settings/config.properties b/ezyfox-server-core/test-data1/settings/config.properties index bbfa129df..ee49d0e51 100644 --- a/ezyfox-server-core/test-data1/settings/config.properties +++ b/ezyfox-server-core/test-data1/settings/config.properties @@ -1,2 +1,2 @@ ezyfox.version=1.0.0 -logger.config.file=logback.groovy \ No newline at end of file +logger.config.file=logback.groovy diff --git a/ezyfox-server-embedded/pom.xml b/ezyfox-server-embedded/pom.xml index 4351992cb..e354a986e 100755 --- a/ezyfox-server-embedded/pom.xml +++ b/ezyfox-server-embedded/pom.xml @@ -1,38 +1,38 @@ - 4.0.0 - - com.tvd12 - ezyfox-server - 1.2.3 - - ezyfox-server-embedded + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + com.tvd12 + ezyfox-server + 1.2.3 + + ezyfox-server-embedded - ezyfox-server-embedded - https://youngmonkeys.org/project/ezyfox-sever/ - - - - com.tvd12 - ezyfox-server-nio - ${project.version} - - - com.tvd12 - ezyfox-server-support - ${project.version} - - - com.tvd12 - ezyfox-msgpack - ${project.version} - - - com.tvd12 - ezyfox-jackson - ${project.version} - - + ezyfox-server-embedded + https://youngmonkeys.org/project/ezyfox-sever/ + + + + com.tvd12 + ezyfox-server-nio + ${project.version} + + + com.tvd12 + ezyfox-server-support + ${project.version} + + + com.tvd12 + ezyfox-msgpack + ${project.version} + + + com.tvd12 + ezyfox-jackson + ${project.version} + + diff --git a/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedRunner.java b/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedRunner.java index 252838396..d9fca6581 100644 --- a/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedRunner.java +++ b/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedRunner.java @@ -8,48 +8,48 @@ public class EzyEmbeddedRunner extends EzyRunner { - protected final EzyConfig config; - protected final EzySettings settings; - - protected EzyEmbeddedRunner(Builder builder) { - this.config = builder.config; - this.settings = builder.settings; - } - - @Override - protected void validateArguments(String[] args) {} - - @Override - protected EzyStarter.Builder newStarterBuilder() { - return EzyEmbeddedStarter.builder() - .config(config) - .settings(settings); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - - protected EzyConfig config; - protected EzySettings settings; - - public Builder config(EzyConfig config) { - this.config = config; - return this; - } - - public Builder settings(EzySettings settings) { - this.settings = settings; - return this; - } - - @Override - public EzyEmbeddedRunner build() { - return new EzyEmbeddedRunner(this); - } - - } - + protected final EzyConfig config; + protected final EzySettings settings; + + protected EzyEmbeddedRunner(Builder builder) { + this.config = builder.config; + this.settings = builder.settings; + } + + @Override + protected void validateArguments(String[] args) {} + + @Override + protected EzyStarter.Builder newStarterBuilder() { + return EzyEmbeddedStarter.builder() + .config(config) + .settings(settings); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected EzyConfig config; + protected EzySettings settings; + + public Builder config(EzyConfig config) { + this.config = config; + return this; + } + + public Builder settings(EzySettings settings) { + this.settings = settings; + return this; + } + + @Override + public EzyEmbeddedRunner build() { + return new EzyEmbeddedRunner(this); + } + + } + } diff --git a/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedServer.java b/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedServer.java index 1ed7d7e69..aafbd5600 100644 --- a/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedServer.java +++ b/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedServer.java @@ -10,65 +10,65 @@ public class EzyEmbeddedServer implements EzyStoppable { - protected final EzyConfig config; - protected final String configFile; - protected final EzySettings settings; - protected EzyServerContext serverContext; - - protected EzyEmbeddedServer(Builder builder) { - this.config = builder.config; - this.settings = builder.settings; - this.configFile = builder.configFile; - } - - public EzyServerContext start() throws Exception { - EzyRunner runner = EzyEmbeddedRunner.builder() - .config(config) - .settings(settings) - .build(); - runner.run(new String[] {configFile}); - serverContext = runner.getServerContext(); - return serverContext; - } - - @Override - public void stop() { - if(serverContext != null) - ((EzyDestroyable)serverContext).destroy(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - - protected EzyConfig config; - protected String configFile; - protected EzySettings settings; - - public Builder config(EzyConfig config) { - this.config = config; - return this; - } - - public Builder configFile(String configFile) { - this.configFile = configFile; - return this; - } - - public Builder settings(EzySettings settings) { - this.settings = settings; - return this; - } - - @Override - public EzyEmbeddedServer build() { - if(settings == null) - throw new IllegalStateException("settings can not be null"); - return new EzyEmbeddedServer(this); - } - - } - + protected final EzyConfig config; + protected final String configFile; + protected final EzySettings settings; + protected EzyServerContext serverContext; + + protected EzyEmbeddedServer(Builder builder) { + this.config = builder.config; + this.settings = builder.settings; + this.configFile = builder.configFile; + } + + public EzyServerContext start() throws Exception { + EzyRunner runner = EzyEmbeddedRunner.builder() + .config(config) + .settings(settings) + .build(); + runner.run(new String[] {configFile}); + serverContext = runner.getServerContext(); + return serverContext; + } + + @Override + public void stop() { + if(serverContext != null) + ((EzyDestroyable)serverContext).destroy(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected EzyConfig config; + protected String configFile; + protected EzySettings settings; + + public Builder config(EzyConfig config) { + this.config = config; + return this; + } + + public Builder configFile(String configFile) { + this.configFile = configFile; + return this; + } + + public Builder settings(EzySettings settings) { + this.settings = settings; + return this; + } + + @Override + public EzyEmbeddedServer build() { + if(settings == null) + throw new IllegalStateException("settings can not be null"); + return new EzyEmbeddedServer(this); + } + + } + } diff --git a/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedStarter.java b/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedStarter.java index 4755bec34..e3f90a040 100644 --- a/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedStarter.java +++ b/ezyfox-server-embedded/src/main/java/com/tvd12/ezyfoxserver/embedded/EzyEmbeddedStarter.java @@ -8,28 +8,28 @@ import com.tvd12.ezyfoxserver.wrapper.EzySimpleSessionManager; public class EzyEmbeddedStarter extends EzyNioStarter { - - protected final EzyConfig config; - protected final EzySettings settings; - - protected EzyEmbeddedStarter(Builder builder) { - super(builder); - this.config = builder.config; - this.settings = builder.settings; - } - - @Override - protected EzyConfig readConfig(String configFile) throws Exception { - if(config != null) - return config; - return super.readConfig(configFile); - } - @Override - protected EzyLoader newLoader() { - return new EzyEmbeddedLoader() { + protected final EzyConfig config; + protected final EzySettings settings; + + protected EzyEmbeddedStarter(Builder builder) { + super(builder); + this.config = builder.config; + this.settings = builder.settings; + } + + @Override + protected EzyConfig readConfig(String configFile) throws Exception { + if(config != null) + return config; + return super.readConfig(configFile); + } + + @Override + protected EzyLoader newLoader() { + return new EzyEmbeddedLoader() { @SuppressWarnings("rawtypes") - @Override + @Override protected EzySimpleSessionManager.Builder createSessionManagerBuilder(EzySettings settings) { return newSessionManagerBuilder(settings); @@ -37,35 +37,35 @@ protected EzyLoader newLoader() { @Override protected EzySettings readSettings() { - return settings; + return settings; } }; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyNioStarter.Builder { - - protected EzyConfig config; - protected EzySettings settings; - - public Builder config(EzyConfig config) { - this.config = config; - return this; - } - - public Builder settings(EzySettings settings) { - this.settings = settings; - return this; - } - - @Override - public EzyStarter build() { - return new EzyEmbeddedStarter(this); - } - - } - + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyNioStarter.Builder { + + protected EzyConfig config; + protected EzySettings settings; + + public Builder config(EzyConfig config) { + this.config = config; + return this; + } + + public Builder settings(EzySettings settings) { + this.settings = settings; + return this; + } + + @Override + public EzyStarter build() { + return new EzyEmbeddedStarter(this); + } + + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedServerTest.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedServerTest.java index 9736672c4..49cb1649c 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedServerTest.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedServerTest.java @@ -18,95 +18,95 @@ public class EzyEmbeddedServerTest { - public static void main(String[] args) throws Exception { - new EzyEmbeddedServerTest().test(); - } - - @Test - public void test() throws Exception { - EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() - .name("test") - .entryLoader(TestPluginEntryLoader.class); - - EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() - .name("test") - .entryLoader(TestAppEntryLoader.class); - - EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() - .name("test") - .application(appSettingBuilder.build()) - .plugin(pluginSettingBuilder.build()); - - EzySimpleUdpSetting udpSetting = new EzyUdpSettingBuilder() - .active(true) - .build(); - - EzySimpleSettings settings = new EzySettingsBuilder() - .zone(zoneSettingBuilder.build()) - .udp(udpSetting) - .build(); - - EzyEmbeddedServer server = EzyEmbeddedServer.builder() - .settings(settings) - .config(EzySimpleConfig.defaultConfig()) - .configFile("test-config/config.properties") - .build(); - server.start(); - Thread.sleep(2000); - server.stop(); - } - - @Test - public void startWithConfigFile() throws Exception { - EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() - .name("test") - .entryLoader(TestPluginEntryLoader.class); - - EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() - .name("test") - .entryLoader(TestAppEntryLoader.class); - - EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() - .name("test") - .application(appSettingBuilder.build()) - .plugin(pluginSettingBuilder.build()); - - EzySimpleSocketSetting socketSetting = new EzySocketSettingBuilder() - .active(false) // active or not, default true - .build(); - - EzySimpleWebSocketSetting webSocketSetting = new EzyWebSocketSettingBuilder() - .active(false) // active or not, default true - .build(); - - EzySimpleSettings settings = new EzySettingsBuilder() - .socket(socketSetting) - .websocket(webSocketSetting) - .zone(zoneSettingBuilder.build()) - .build(); - - EzyEmbeddedServer server = EzyEmbeddedServer.builder() - .settings(settings) - .configFile("test-config/config.properties") - .build(); - server.start(); - Thread.sleep(1000); - server.stop(); - } - - @Test - public void stopTest() { - EzySimpleSettings settings = new EzySettingsBuilder() - .build(); - EzyEmbeddedServer server = EzyEmbeddedServer.builder() - .settings(settings) - .build(); - server.stop(); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void settingNullTest() { - EzyEmbeddedServer.builder().build(); - } - + public static void main(String[] args) throws Exception { + new EzyEmbeddedServerTest().test(); + } + + @Test + public void test() throws Exception { + EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() + .name("test") + .entryLoader(TestPluginEntryLoader.class); + + EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() + .name("test") + .entryLoader(TestAppEntryLoader.class); + + EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() + .name("test") + .application(appSettingBuilder.build()) + .plugin(pluginSettingBuilder.build()); + + EzySimpleUdpSetting udpSetting = new EzyUdpSettingBuilder() + .active(true) + .build(); + + EzySimpleSettings settings = new EzySettingsBuilder() + .zone(zoneSettingBuilder.build()) + .udp(udpSetting) + .build(); + + EzyEmbeddedServer server = EzyEmbeddedServer.builder() + .settings(settings) + .config(EzySimpleConfig.defaultConfig()) + .configFile("test-config/config.properties") + .build(); + server.start(); + Thread.sleep(2000); + server.stop(); + } + + @Test + public void startWithConfigFile() throws Exception { + EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() + .name("test") + .entryLoader(TestPluginEntryLoader.class); + + EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() + .name("test") + .entryLoader(TestAppEntryLoader.class); + + EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() + .name("test") + .application(appSettingBuilder.build()) + .plugin(pluginSettingBuilder.build()); + + EzySimpleSocketSetting socketSetting = new EzySocketSettingBuilder() + .active(false) // active or not, default true + .build(); + + EzySimpleWebSocketSetting webSocketSetting = new EzyWebSocketSettingBuilder() + .active(false) // active or not, default true + .build(); + + EzySimpleSettings settings = new EzySettingsBuilder() + .socket(socketSetting) + .websocket(webSocketSetting) + .zone(zoneSettingBuilder.build()) + .build(); + + EzyEmbeddedServer server = EzyEmbeddedServer.builder() + .settings(settings) + .configFile("test-config/config.properties") + .build(); + server.start(); + Thread.sleep(1000); + server.stop(); + } + + @Test + public void stopTest() { + EzySimpleSettings settings = new EzySettingsBuilder() + .build(); + EzyEmbeddedServer server = EzyEmbeddedServer.builder() + .settings(settings) + .build(); + server.stop(); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void settingNullTest() { + EzyEmbeddedServer.builder().build(); + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedSettingsBuilderPrototype.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedSettingsBuilderPrototype.java index a350674b4..c109c6c39 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedSettingsBuilderPrototype.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/EzyEmbeddedSettingsBuilderPrototype.java @@ -17,117 +17,117 @@ public class EzyEmbeddedSettingsBuilderPrototype extends EzySettingsBuilder { - protected Set packagesToScan; - protected static final String DEFAULT_NAME = "default"; - - public EzyEmbeddedSettingsBuilderPrototype() { - this.packagesToScan = new HashSet<>(); - } - - public EzyEmbeddedSettingsBuilderPrototype scan(String packageToScan) { - this.packagesToScan.add(packageToScan); - return this; - } - - public EzyEmbeddedSettingsBuilderPrototype scan(String... packagesToScan) { - for(String packageToScan : packagesToScan) - scan(packageToScan); - return this; - } - - public EzyEmbeddedSettingsBuilderPrototype scan(Iterable packagesToScan) { - for(String packageToScan : packagesToScan) - scan(packageToScan); - return this; - } - - @Override - public EzySimpleSettings build() { - if(zones.getSize() == 0) { - EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() - .name(DEFAULT_NAME) - .entryLoader(EmbeddedPluginEntryLoader.class) - .entryLoaderArgs(new Object[] {packagesToScan}); - - EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() - .name(DEFAULT_NAME) - .entryLoader(EmbeddedAppEntryLoader.class) - .entryLoaderArgs(new Object[] {packagesToScan}); - - EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() - .name(DEFAULT_NAME) - .application(appSettingBuilder.build()) - .plugin(pluginSettingBuilder.build()); - zones.setItem(zoneSettingBuilder.build()); - } - return super.build(); - } - - public static class EmbeddedAppEntry extends EzySimpleAppEntry { + protected Set packagesToScan; + protected static final String DEFAULT_NAME = "default"; + + public EzyEmbeddedSettingsBuilderPrototype() { + this.packagesToScan = new HashSet<>(); + } + + public EzyEmbeddedSettingsBuilderPrototype scan(String packageToScan) { + this.packagesToScan.add(packageToScan); + return this; + } + + public EzyEmbeddedSettingsBuilderPrototype scan(String... packagesToScan) { + for(String packageToScan : packagesToScan) + scan(packageToScan); + return this; + } + + public EzyEmbeddedSettingsBuilderPrototype scan(Iterable packagesToScan) { + for(String packageToScan : packagesToScan) + scan(packageToScan); + return this; + } + + @Override + public EzySimpleSettings build() { + if(zones.getSize() == 0) { + EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() + .name(DEFAULT_NAME) + .entryLoader(EmbeddedPluginEntryLoader.class) + .entryLoaderArgs(new Object[] {packagesToScan}); + + EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() + .name(DEFAULT_NAME) + .entryLoader(EmbeddedAppEntryLoader.class) + .entryLoaderArgs(new Object[] {packagesToScan}); + + EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() + .name(DEFAULT_NAME) + .application(appSettingBuilder.build()) + .plugin(pluginSettingBuilder.build()); + zones.setItem(zoneSettingBuilder.build()); + } + return super.build(); + } + + public static class EmbeddedAppEntry extends EzySimpleAppEntry { - protected String[] packagesToScan; - - public EmbeddedAppEntry(String[] packagesToScan) { - this.packagesToScan = packagesToScan; - } - - @Override - protected String[] getScanableBeanPackages() { - return this.packagesToScan; - } + protected String[] packagesToScan; + + public EmbeddedAppEntry(String[] packagesToScan) { + this.packagesToScan = packagesToScan; + } + + @Override + protected String[] getScanableBeanPackages() { + return this.packagesToScan; + } - @Override - protected String[] getScanableBindingPackages() { - return this.packagesToScan; - } - - } - - public static class EmbeddedAppEntryLoader extends EzyAbstractAppEntryLoader { + @Override + protected String[] getScanableBindingPackages() { + return this.packagesToScan; + } + + } + + public static class EmbeddedAppEntryLoader extends EzyAbstractAppEntryLoader { - protected String[] packagesToScan; - - public EmbeddedAppEntryLoader(Set packagesToScan) { - this.packagesToScan = - packagesToScan.toArray(new String[packagesToScan.size()]); - } - - @Override - public EzyAppEntry load() throws Exception { - return new EmbeddedAppEntry(packagesToScan); - } - - } - - public static class EmbeddedPluginEntry extends EzySimplePluginEntry { + protected String[] packagesToScan; + + public EmbeddedAppEntryLoader(Set packagesToScan) { + this.packagesToScan = + packagesToScan.toArray(new String[packagesToScan.size()]); + } + + @Override + public EzyAppEntry load() throws Exception { + return new EmbeddedAppEntry(packagesToScan); + } + + } + + public static class EmbeddedPluginEntry extends EzySimplePluginEntry { - protected String[] packagesToScan; - - public EmbeddedPluginEntry(String[] packagesToScan) { - this.packagesToScan = packagesToScan; - } - - @Override - protected String[] getScanableBeanPackages() { - return this.packagesToScan; - } + protected String[] packagesToScan; + + public EmbeddedPluginEntry(String[] packagesToScan) { + this.packagesToScan = packagesToScan; + } + + @Override + protected String[] getScanableBeanPackages() { + return this.packagesToScan; + } - } + } - public static class EmbeddedPluginEntryLoader extends EzyAbstractPluginEntryLoader { + public static class EmbeddedPluginEntryLoader extends EzyAbstractPluginEntryLoader { - protected String[] packagesToScan; - - public EmbeddedPluginEntryLoader(Set packagesToScan) { - this.packagesToScan = - packagesToScan.toArray(new String[packagesToScan.size()]); - } - - @Override - public EzyPluginEntry load() throws Exception { - return new EmbeddedPluginEntry(packagesToScan); - } - - } - + protected String[] packagesToScan; + + public EmbeddedPluginEntryLoader(Set packagesToScan) { + this.packagesToScan = + packagesToScan.toArray(new String[packagesToScan.size()]); + } + + @Override + public EzyPluginEntry load() throws Exception { + return new EmbeddedPluginEntry(packagesToScan); + } + + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer.java index 38c80ed9e..c2d4c2658 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer.java @@ -22,95 +22,95 @@ public class HelloEmbeddedServer { - public static void main(String[] args) throws Exception { - EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() - .name("hello") - .addListenEvent(EzyEventType.USER_LOGIN) - .entryLoader(HelloPluginEntryLoader.class); - - EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() - .name("hello") - .entryLoader(HelloAppEntryLoader.class); - - EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() - .name("hello") - .application(appSettingBuilder.build()) - .plugin(pluginSettingBuilder.build()); - - EzyWebSocketSettingBuilder webSocketSettingBuilder = new EzyWebSocketSettingBuilder() - .active(true) - .managementEnable(true); - - EzySimpleSettings settings = new EzySettingsBuilder() - .zone(zoneSettingBuilder.build()) - .websocket(webSocketSettingBuilder.build()) - .build(); - - EzyEmbeddedServer server = EzyEmbeddedServer.builder() - .settings(settings) - .build(); - server.start(); - } - - public static class HelloAppEntry extends EzySimpleAppEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test" // replace by your package - }; - } - - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test" // replace by your package - }; - } - - @Override - protected EzyAppRequestController newUserRequestController(EzyBeanContext beanContext) { - return EzyUserRequestAppSingletonController.builder() - .beanContext(beanContext) - .build(); - } - - } - - public static class HelloAppEntryLoader extends EzyAbstractAppEntryLoader { - - @Override - public EzyAppEntry load() throws Exception { - return new HelloAppEntry(); - } - - } - - public static class HelloPluginEntry extends EzySimplePluginEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test.plugin" // replace by your package - }; - } - - @Override - protected EzyPluginRequestController newUserRequestController(EzyBeanContext beanContext) { - return EzyUserRequestPluginSingletonController.builder() - .beanContext(beanContext) - .build(); - } - - } - - public static class HelloPluginEntryLoader extends EzyAbstractPluginEntryLoader { - - @Override - public EzyPluginEntry load() throws Exception { - return new HelloPluginEntry(); - } - - } - + public static void main(String[] args) throws Exception { + EzyPluginSettingBuilder pluginSettingBuilder = new EzyPluginSettingBuilder() + .name("hello") + .addListenEvent(EzyEventType.USER_LOGIN) + .entryLoader(HelloPluginEntryLoader.class); + + EzyAppSettingBuilder appSettingBuilder = new EzyAppSettingBuilder() + .name("hello") + .entryLoader(HelloAppEntryLoader.class); + + EzyZoneSettingBuilder zoneSettingBuilder = new EzyZoneSettingBuilder() + .name("hello") + .application(appSettingBuilder.build()) + .plugin(pluginSettingBuilder.build()); + + EzyWebSocketSettingBuilder webSocketSettingBuilder = new EzyWebSocketSettingBuilder() + .active(true) + .managementEnable(true); + + EzySimpleSettings settings = new EzySettingsBuilder() + .zone(zoneSettingBuilder.build()) + .websocket(webSocketSettingBuilder.build()) + .build(); + + EzyEmbeddedServer server = EzyEmbeddedServer.builder() + .settings(settings) + .build(); + server.start(); + } + + public static class HelloAppEntry extends EzySimpleAppEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test" // replace by your package + }; + } + + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test" // replace by your package + }; + } + + @Override + protected EzyAppRequestController newUserRequestController(EzyBeanContext beanContext) { + return EzyUserRequestAppSingletonController.builder() + .beanContext(beanContext) + .build(); + } + + } + + public static class HelloAppEntryLoader extends EzyAbstractAppEntryLoader { + + @Override + public EzyAppEntry load() throws Exception { + return new HelloAppEntry(); + } + + } + + public static class HelloPluginEntry extends EzySimplePluginEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test.plugin" // replace by your package + }; + } + + @Override + protected EzyPluginRequestController newUserRequestController(EzyBeanContext beanContext) { + return EzyUserRequestPluginSingletonController.builder() + .beanContext(beanContext) + .build(); + } + + } + + public static class HelloPluginEntryLoader extends EzyAbstractPluginEntryLoader { + + @Override + public EzyPluginEntry load() throws Exception { + return new HelloPluginEntry(); + } + + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer2.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer2.java index 3f3d9e4a3..61c1fabb3 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer2.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer2.java @@ -11,62 +11,62 @@ public class HelloEmbeddedServer2 { - public static void main(String[] args) throws Exception { - EzySimpleSettings settings = new EzyEmbeddedSettingsBuilderPrototype() - .scan("com.tvd12.ezyfoxserver.embedded.test") - .build(); - - EzyEmbeddedServer server = EzyEmbeddedServer.builder() - .settings(settings) - .build(); - server.start(); - } - - public static class HelloAppEntry extends EzySimpleAppEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test" // replace by your package - }; - } - - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test" // replace by your package - }; - } - - } - - public static class HelloAppEntryLoader extends EzyAbstractAppEntryLoader { - - @Override - public EzyAppEntry load() throws Exception { - return new HelloAppEntry(); - } - - } - - public static class HelloPluginEntry extends EzySimplePluginEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test.plugin" // replace by your package - }; - } - - } - - public class HelloPluginEntryLoader extends EzyAbstractPluginEntryLoader { - - @Override - public EzyPluginEntry load() throws Exception { - return new HelloPluginEntry(); - } - - } - + public static void main(String[] args) throws Exception { + EzySimpleSettings settings = new EzyEmbeddedSettingsBuilderPrototype() + .scan("com.tvd12.ezyfoxserver.embedded.test") + .build(); + + EzyEmbeddedServer server = EzyEmbeddedServer.builder() + .settings(settings) + .build(); + server.start(); + } + + public static class HelloAppEntry extends EzySimpleAppEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test" // replace by your package + }; + } + + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test" // replace by your package + }; + } + + } + + public static class HelloAppEntryLoader extends EzyAbstractAppEntryLoader { + + @Override + public EzyAppEntry load() throws Exception { + return new HelloAppEntry(); + } + + } + + public static class HelloPluginEntry extends EzySimplePluginEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test.plugin" // replace by your package + }; + } + + } + + public class HelloPluginEntryLoader extends EzyAbstractPluginEntryLoader { + + @Override + public EzyPluginEntry load() throws Exception { + return new HelloPluginEntry(); + } + + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer3.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer3.java index 1ce2e251d..4a3eaddbf 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer3.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/HelloEmbeddedServer3.java @@ -42,177 +42,177 @@ public class HelloEmbeddedServer3 { - public static void main(String[] args) throws Exception { - EzySimplePluginSetting pluginSetting = new EzyPluginSettingBuilder() - .name("hello") // plugin name - .addListenEvent(EzyEventType.USER_LOGIN) // listen able events USER_LOGIN, USER_ADDED, USER_REMOVED - .configFile("config.properties") - .entryLoader(HelloPluginEntryLoader.class) -// .entryLoaderArgs() // pass arguments to entry loader constructor - .priority(1) // set priority, bigger number is lower, default 0 - .threadPoolSize(3) // set thread pool size to create executor service for this plugin, default 0 - .build(); - - EzySimpleAppSetting appSetting = new EzyAppSettingBuilder() - .name("hello") // app's name - .configFile("config.properties") - .entryLoader(HelloAppEntryLoader.class) - .maxUsers(9999) // set max user in this app, default 999999 -// .entryLoaderArgs() // pass arguments to entry loader constructor - .threadPoolSize(3) // set thread pool size to create executor service for this app, default 0 - .build(); - - EzySimpleUserManagementSetting userManagementSetting = new EzyUserManagementSettingBuilder() - .allowChangeSession(true) // allow change user's session, default true - .allowGuestLogin(true) // allow guest login, default false - .guestNamePrefix("Guest#") // set name prefix for guest - .maxSessionPerUser(5) // set number of max sessions per user // default 5 - .userMaxIdleTimeInSecond(15) // set max idle time of an user, default 0 - .userNamePattern("^[a-z0-9_.]{3,36}$") // set username pattern, default ^[a-z0-9_.]{3,36}$ - .build(); - - EzySimpleZoneSetting zoneSetting = new EzyZoneSettingBuilder() - .name("hello") // zone's name - .plugin(pluginSetting) // add a plug-in to zone - .application(appSetting) // add an app to zone - .configFile("config.properties") // set config file - .maxUsers(999999) // set maximum user for zone - .userManagement(userManagementSetting) // set user management settings - // add event controller, accept SERVER_INITIALIZING, SERVER_READY - .addEventController(EzyEventType.SERVER_READY, HelloZoneServerReadyController.class) - .build(); - - EzySimpleSocketSetting socketSetting = new EzySocketSettingBuilder() - .active(true) // active or not, default true - .address("0.0.0.0") // loopback address, default 0.0.0.0 - .codecCreator(MsgPackCodecCreator.class) // encoder/decoder creator, default MsgPackCodecCreator - .maxRequestSize(1024) // max request size, default 32768 - .port(3005) // port, default 3005 - .tcpNoDelay(true) // tcp no delay, default false - .writerThreadPoolSize(8) // thread pool size for socket writer, default 8 - .build(); - - EzySimpleWebSocketSetting webSocketSetting = new EzyWebSocketSettingBuilder() - .active(true) // active or not, default true - .address("0.0.0.0") // loopback address, default 0.0.0.0 - .codecCreator(JacksonCodecCreator.class) // encoder/decoder creator, default JacksonCodecCreator - .maxFrameSize(32678) // max frame size, default 32768 - .port(2208) // port, default 3005 - .writerThreadPoolSize(8) // thread pool size for socket writer, default 8 - .build(); - - EzySimpleMaxRequestPerSecond maxRequestPerSecond = new EzyMaxRequestPerSecondBuilder() - .value(15) // max request in a second - .action(EzyMaxRequestPerSecondAction.DROP_REQUEST) // action when get max - .build(); - - EzySimpleSessionManagementSetting sessionManagementSetting = new EzySessionManagementSettingBuilder() - .sessionMaxIdleTimeInSecond(30) // set max idle time for session, default 30s - .sessionMaxWaitingTimeInSecond(30) // set max waiting time to login for session, default 30s - .sessionMaxRequestPerSecond(maxRequestPerSecond) // set max request in a session for a session - .build(); - - EzySimpleUdpSetting udpSetting = new EzyUdpSettingBuilder() - .active(true) // active or not - .address("0.0.0.0") // set loopback IP - .channelPoolSize(16) // set number of udp channel for socket writing, default 16 - .codecCreator(MsgPackCodecCreator.class) // encoder/decoder creator, default MsgPackCodecCreator - .handlerThreadPoolSize(5) // set number of handler's thread, default 5 - .maxRequestSize(1024) // set max request's size - .port(2611) // set listen port - .build(); - - EzySimpleSettings settings = new EzySettingsBuilder() - .debug(true) // allow debug to print log or not, default false - .nodeName("hello") // for convenient - .zone(zoneSetting) // add a zone to server - .socket(socketSetting) // set socket setting - .websocket(webSocketSetting) // set websocket setting - .udp(udpSetting) // set udp setting - .sessionManagement(sessionManagementSetting) // set session management setting - // add event controller, accept SERVER_INITIALIZING, SERVER_READY - .addEventController(EzyEventType.SERVER_INITIALIZING, HelloServerInitializingReadyController.class) - .build(); - - EzyEmbeddedServer server = EzyEmbeddedServer.builder() - .settings(settings) - .build(); - server.start(); - } - - public static class HelloAppEntry extends EzySimpleAppEntry { - - // packages to scan bean - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test" // replace by your package - }; - } - - // packages to scan POJO mapped socket binary data - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test" // replace by your package - }; - } - - @Override - protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { - // register bean here - } - - } - - public static class HelloAppEntryLoader extends EzyAbstractAppEntryLoader { - - @Override - public EzyAppEntry load() throws Exception { - return new HelloAppEntry(); - } - - } - - public static class HelloPluginEntry extends EzySimplePluginEntry { - - // packages to scan bean - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.embedded.test.plugin" // replace by your package - }; - } - - } - - public static class HelloPluginEntryLoader extends EzyAbstractPluginEntryLoader { - - @Override - public EzyPluginEntry load() throws Exception { - return new HelloPluginEntry(); - } - - } - - public static class HelloServerInitializingReadyController - extends EzyAbstractServerEventController { - - @Override - public void handle(EzyServerContext ctx, EzySimpleServerInitializingEvent event) { - // add logic here - } - - } - - public static class HelloZoneServerReadyController - extends EzyAbstractZoneEventController { - - @Override - public void handle(EzyZoneContext ctx, EzyServerReadyEvent event) { - // add logic here - } - - } - + public static void main(String[] args) throws Exception { + EzySimplePluginSetting pluginSetting = new EzyPluginSettingBuilder() + .name("hello") // plugin name + .addListenEvent(EzyEventType.USER_LOGIN) // listen able events USER_LOGIN, USER_ADDED, USER_REMOVED + .configFile("config.properties") + .entryLoader(HelloPluginEntryLoader.class) +// .entryLoaderArgs() // pass arguments to entry loader constructor + .priority(1) // set priority, bigger number is lower, default 0 + .threadPoolSize(3) // set thread pool size to create executor service for this plugin, default 0 + .build(); + + EzySimpleAppSetting appSetting = new EzyAppSettingBuilder() + .name("hello") // app's name + .configFile("config.properties") + .entryLoader(HelloAppEntryLoader.class) + .maxUsers(9999) // set max user in this app, default 999999 +// .entryLoaderArgs() // pass arguments to entry loader constructor + .threadPoolSize(3) // set thread pool size to create executor service for this app, default 0 + .build(); + + EzySimpleUserManagementSetting userManagementSetting = new EzyUserManagementSettingBuilder() + .allowChangeSession(true) // allow change user's session, default true + .allowGuestLogin(true) // allow guest login, default false + .guestNamePrefix("Guest#") // set name prefix for guest + .maxSessionPerUser(5) // set number of max sessions per user // default 5 + .userMaxIdleTimeInSecond(15) // set max idle time of an user, default 0 + .userNamePattern("^[a-z0-9_.]{3,36}$") // set username pattern, default ^[a-z0-9_.]{3,36}$ + .build(); + + EzySimpleZoneSetting zoneSetting = new EzyZoneSettingBuilder() + .name("hello") // zone's name + .plugin(pluginSetting) // add a plug-in to zone + .application(appSetting) // add an app to zone + .configFile("config.properties") // set config file + .maxUsers(999999) // set maximum user for zone + .userManagement(userManagementSetting) // set user management settings + // add event controller, accept SERVER_INITIALIZING, SERVER_READY + .addEventController(EzyEventType.SERVER_READY, HelloZoneServerReadyController.class) + .build(); + + EzySimpleSocketSetting socketSetting = new EzySocketSettingBuilder() + .active(true) // active or not, default true + .address("0.0.0.0") // loopback address, default 0.0.0.0 + .codecCreator(MsgPackCodecCreator.class) // encoder/decoder creator, default MsgPackCodecCreator + .maxRequestSize(1024) // max request size, default 32768 + .port(3005) // port, default 3005 + .tcpNoDelay(true) // tcp no delay, default false + .writerThreadPoolSize(8) // thread pool size for socket writer, default 8 + .build(); + + EzySimpleWebSocketSetting webSocketSetting = new EzyWebSocketSettingBuilder() + .active(true) // active or not, default true + .address("0.0.0.0") // loopback address, default 0.0.0.0 + .codecCreator(JacksonCodecCreator.class) // encoder/decoder creator, default JacksonCodecCreator + .maxFrameSize(32678) // max frame size, default 32768 + .port(2208) // port, default 3005 + .writerThreadPoolSize(8) // thread pool size for socket writer, default 8 + .build(); + + EzySimpleMaxRequestPerSecond maxRequestPerSecond = new EzyMaxRequestPerSecondBuilder() + .value(15) // max request in a second + .action(EzyMaxRequestPerSecondAction.DROP_REQUEST) // action when get max + .build(); + + EzySimpleSessionManagementSetting sessionManagementSetting = new EzySessionManagementSettingBuilder() + .sessionMaxIdleTimeInSecond(30) // set max idle time for session, default 30s + .sessionMaxWaitingTimeInSecond(30) // set max waiting time to login for session, default 30s + .sessionMaxRequestPerSecond(maxRequestPerSecond) // set max request in a session for a session + .build(); + + EzySimpleUdpSetting udpSetting = new EzyUdpSettingBuilder() + .active(true) // active or not + .address("0.0.0.0") // set loopback IP + .channelPoolSize(16) // set number of udp channel for socket writing, default 16 + .codecCreator(MsgPackCodecCreator.class) // encoder/decoder creator, default MsgPackCodecCreator + .handlerThreadPoolSize(5) // set number of handler's thread, default 5 + .maxRequestSize(1024) // set max request's size + .port(2611) // set listen port + .build(); + + EzySimpleSettings settings = new EzySettingsBuilder() + .debug(true) // allow debug to print log or not, default false + .nodeName("hello") // for convenient + .zone(zoneSetting) // add a zone to server + .socket(socketSetting) // set socket setting + .websocket(webSocketSetting) // set websocket setting + .udp(udpSetting) // set udp setting + .sessionManagement(sessionManagementSetting) // set session management setting + // add event controller, accept SERVER_INITIALIZING, SERVER_READY + .addEventController(EzyEventType.SERVER_INITIALIZING, HelloServerInitializingReadyController.class) + .build(); + + EzyEmbeddedServer server = EzyEmbeddedServer.builder() + .settings(settings) + .build(); + server.start(); + } + + public static class HelloAppEntry extends EzySimpleAppEntry { + + // packages to scan bean + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test" // replace by your package + }; + } + + // packages to scan POJO mapped socket binary data + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test" // replace by your package + }; + } + + @Override + protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { + // register bean here + } + + } + + public static class HelloAppEntryLoader extends EzyAbstractAppEntryLoader { + + @Override + public EzyAppEntry load() throws Exception { + return new HelloAppEntry(); + } + + } + + public static class HelloPluginEntry extends EzySimplePluginEntry { + + // packages to scan bean + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.embedded.test.plugin" // replace by your package + }; + } + + } + + public static class HelloPluginEntryLoader extends EzyAbstractPluginEntryLoader { + + @Override + public EzyPluginEntry load() throws Exception { + return new HelloPluginEntry(); + } + + } + + public static class HelloServerInitializingReadyController + extends EzyAbstractServerEventController { + + @Override + public void handle(EzyServerContext ctx, EzySimpleServerInitializingEvent event) { + // add logic here + } + + } + + public static class HelloZoneServerReadyController + extends EzyAbstractZoneEventController { + + @Override + public void handle(EzyZoneContext ctx, EzyServerReadyEvent event) { + // add logic here + } + + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntry.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntry.java index 7ff089951..109152036 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntry.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntry.java @@ -6,28 +6,28 @@ public class TestAppEntry extends EzySimpleAppEntry { - @Override - protected void preConfig(EzyAppContext ctx) { - getLogger().info("\n=================== FREE CHAT APP START CONFIG ================\n"); - } - - @Override - protected void postConfig(EzyAppContext ctx) { - getLogger().info("\n=================== FREE CHAT APP END CONFIG ================\n"); - } - - @Override - protected String[] getScanableBeanPackages() { - return new String[0]; - } - - @Override - protected String[] getScanableBindingPackages() { - return new String[0]; - } - - @Override - protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { - } - + @Override + protected void preConfig(EzyAppContext ctx) { + getLogger().info("\n=================== FREE CHAT APP START CONFIG ================\n"); + } + + @Override + protected void postConfig(EzyAppContext ctx) { + getLogger().info("\n=================== FREE CHAT APP END CONFIG ================\n"); + } + + @Override + protected String[] getScanableBeanPackages() { + return new String[0]; + } + + @Override + protected String[] getScanableBindingPackages() { + return new String[0]; + } + + @Override + protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntryLoader.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntryLoader.java index 6c10eff4a..10a23206f 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntryLoader.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestAppEntryLoader.java @@ -5,9 +5,9 @@ public class TestAppEntryLoader extends EzyAbstractAppEntryLoader { - @Override - public EzyAppEntry load() throws Exception { - return new TestAppEntry(); - } - + @Override + public EzyAppEntry load() throws Exception { + return new TestAppEntry(); + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntry.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntry.java index 5e7d5f4af..d226011cd 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntry.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntry.java @@ -6,23 +6,23 @@ public class TestPluginEntry extends EzySimplePluginEntry { - @Override - protected void preConfig(EzyPluginContext ctx) { - getLogger().info("\n=================== TEST PLUGIN START CONFIG ================\n"); - } - - @Override - protected void postConfig(EzyPluginContext ctx) { - getLogger().info("\n=================== TEST PLUGIN END CONFIG ================\n"); - } - - @Override - protected String[] getScanableBeanPackages() { - return new String[] {"com.tvd12.ezyfoxserver.embedded.test.plugin"}; - } + @Override + protected void preConfig(EzyPluginContext ctx) { + getLogger().info("\n=================== TEST PLUGIN START CONFIG ================\n"); + } - @Override - protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { - } + @Override + protected void postConfig(EzyPluginContext ctx) { + getLogger().info("\n=================== TEST PLUGIN END CONFIG ================\n"); + } + + @Override + protected String[] getScanableBeanPackages() { + return new String[] {"com.tvd12.ezyfoxserver.embedded.test.plugin"}; + } + + @Override + protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { + } } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntryLoader.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntryLoader.java index 4a26b78c2..2d532e567 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntryLoader.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/TestPluginEntryLoader.java @@ -5,9 +5,9 @@ public class TestPluginEntryLoader extends EzyAbstractPluginEntryLoader { - @Override - public EzyPluginEntry load() throws Exception { - return new TestPluginEntry(); - } - + @Override + public EzyPluginEntry load() throws Exception { + return new TestPluginEntry(); + } + } diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/app/controller/HelloAppServerReadyController.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/app/controller/HelloAppServerReadyController.java index eafbccd48..3962f6f98 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/app/controller/HelloAppServerReadyController.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/app/controller/HelloAppServerReadyController.java @@ -10,11 +10,11 @@ @EzySingleton @EzyEventHandler(event = EzyEventNames.SERVER_READY) public class HelloAppServerReadyController - extends EzyAbstractAppEventController { + extends EzyAbstractAppEventController { - @Override - public void handle(EzyAppContext ctx, EzyServerReadyEvent event) { - logger.info("HELLO APP - SERVER READY"); - } - -} \ No newline at end of file + @Override + public void handle(EzyAppContext ctx, EzyServerReadyEvent event) { + logger.info("HELLO APP - SERVER READY"); + } + +} diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloPluginServerReadyController.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloPluginServerReadyController.java index b34aea796..fe08f6700 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloPluginServerReadyController.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloPluginServerReadyController.java @@ -10,11 +10,11 @@ @EzySingleton @EzyEventHandler(event = EzyEventNames.SERVER_READY) public class HelloPluginServerReadyController - extends EzyAbstractPluginEventController { + extends EzyAbstractPluginEventController { - @Override - public void handle(EzyPluginContext ctx, EzyServerReadyEvent event) { - logger.info("HELLO PLUGIN - SERVER READY"); - } - -} \ No newline at end of file + @Override + public void handle(EzyPluginContext ctx, EzyServerReadyEvent event) { + logger.info("HELLO PLUGIN - SERVER READY"); + } + +} diff --git a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloUserLoginController.java b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloUserLoginController.java index dfcb07857..5b8aebedf 100644 --- a/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloUserLoginController.java +++ b/ezyfox-server-embedded/src/test/java/com/tvd12/ezyfoxserver/embedded/test/plugin/HelloUserLoginController.java @@ -12,13 +12,13 @@ @EzySingleton @EzyEventHandler(EzyEventNames.USER_LOGIN) public class HelloUserLoginController - extends EzyAbstractPluginEventController { + extends EzyAbstractPluginEventController { - @Override - public void handle(EzyPluginContext ctx, EzyUserLoginEvent event) { - logger.info("HELLO - user {} login in", event.getUsername()); - if(event.getUsername().contains("admin")) - throw new EzyLoginErrorException(EzyLoginError.INVALID_USERNAME); - } + @Override + public void handle(EzyPluginContext ctx, EzyUserLoginEvent event) { + logger.info("HELLO - user {} login in", event.getUsername()); + if(event.getUsername().contains("admin")) + throw new EzyLoginErrorException(EzyLoginError.INVALID_USERNAME); + } -} \ No newline at end of file +} diff --git a/ezyfox-server-embedded/src/test/resources/AllTests.tng.xml b/ezyfox-server-embedded/src/test/resources/AllTests.tng.xml index 4708355eb..880ebfb54 100644 --- a/ezyfox-server-embedded/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-embedded/src/test/resources/AllTests.tng.xml @@ -1,9 +1,9 @@ - - - - - - \ No newline at end of file + + + + + + diff --git a/ezyfox-server-nio/assembly.xml b/ezyfox-server-nio/assembly.xml index 1a84be639..69e0178eb 100644 --- a/ezyfox-server-nio/assembly.xml +++ b/ezyfox-server-nio/assembly.xml @@ -1,16 +1,16 @@ - bin - false - - dir - + bin + false + + dir + - - - true - lib - - + + + true + lib + + - \ No newline at end of file + diff --git a/ezyfox-server-nio/pom.xml b/ezyfox-server-nio/pom.xml index 77d106bbd..d7d84d7f9 100755 --- a/ezyfox-server-nio/pom.xml +++ b/ezyfox-server-nio/pom.xml @@ -1,37 +1,37 @@ - 4.0.0 - - com.tvd12 - ezyfox-server - 1.2.3 - - ezyfox-server-nio + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + com.tvd12 + ezyfox-server + 1.2.3 + + ezyfox-server-nio - ezyfox-server-nio - https://youngmonkeys.org/project/ezyfox-sever/ + ezyfox-server-nio + https://youngmonkeys.org/project/ezyfox-sever/ - - 9.4.43.v20210629 - + + 9.4.43.v20210629 + - - - com.tvd12 - ezyfox-server-boot - ${project.version} - - - org.eclipse.jetty.websocket - websocket-server - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-client - - - - + + + com.tvd12 + ezyfox-server-boot + ${project.version} + + + org.eclipse.jetty.websocket + websocket-server + ${jetty.version} + + + org.eclipse.jetty.websocket + websocket-client + + + + diff --git a/ezyfox-server-nio/settings/ssl-config.properties b/ezyfox-server-nio/settings/ssl-config.properties index 914e17bfe..bb2fc449b 100644 --- a/ezyfox-server-nio/settings/ssl-config.properties +++ b/ezyfox-server-nio/settings/ssl-config.properties @@ -1,3 +1,3 @@ ssl.key_store="ssl/ssl-key-store.txt" ssl.keystore_password=ssl/ssl-keystore-password.txt -ssl.certificate_password=ssl/ssl-certificate-password.txt \ No newline at end of file +ssl.certificate_password=ssl/ssl-certificate-password.txt diff --git a/ezyfox-server-nio/settings/ssl/ssl-certificate-password.txt b/ezyfox-server-nio/settings/ssl/ssl-certificate-password.txt index 536aca34d..d97c5eada 100644 --- a/ezyfox-server-nio/settings/ssl/ssl-certificate-password.txt +++ b/ezyfox-server-nio/settings/ssl/ssl-certificate-password.txt @@ -1 +1 @@ -secret \ No newline at end of file +secret diff --git a/ezyfox-server-nio/settings/ssl/ssl-keystore-password.txt b/ezyfox-server-nio/settings/ssl/ssl-keystore-password.txt index 536aca34d..d97c5eada 100644 --- a/ezyfox-server-nio/settings/ssl/ssl-keystore-password.txt +++ b/ezyfox-server-nio/settings/ssl/ssl-keystore-password.txt @@ -1 +1 @@ -secret \ No newline at end of file +secret diff --git a/ezyfox-server-nio/settings/ssl/ssl-keystore.txt b/ezyfox-server-nio/settings/ssl/ssl-keystore.txt index 439ef0da4..27c1b25b2 100644 Binary files a/ezyfox-server-nio/settings/ssl/ssl-keystore.txt and b/ezyfox-server-nio/settings/ssl/ssl-keystore.txt differ diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyAbstractSocketServerBootstrap.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyAbstractSocketServerBootstrap.java index c61c36ee0..a0f8d3cc7 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyAbstractSocketServerBootstrap.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyAbstractSocketServerBootstrap.java @@ -16,64 +16,64 @@ public abstract class EzyAbstractSocketServerBootstrap implements EzyStartable, EzyDestroyable { - protected EzyServerContext serverContext; - protected EzySocketDataReceiver socketDataReceiver; - protected EzyHandlerGroupManager handlerGroupManager; - protected EzySessionTicketsQueue sessionTicketsQueue; - protected EzySocketEventLoopHandler writingLoopHandler; + protected EzyServerContext serverContext; + protected EzySocketDataReceiver socketDataReceiver; + protected EzyHandlerGroupManager handlerGroupManager; + protected EzySessionTicketsQueue sessionTicketsQueue; + protected EzySocketEventLoopHandler writingLoopHandler; - public EzyAbstractSocketServerBootstrap(Builder builder) { - this.serverContext = builder.serverContext; - this.socketDataReceiver = builder.socketDataReceiver; - this.handlerGroupManager = builder.handlerGroupManager; - this.sessionTicketsQueue = builder.sessionTicketsQueue; - } - - @Override - public void destroy() { - processWithLogException(() -> writingLoopHandler.destroy()); - } - - protected final EzySettings getServerSettings() { - return serverContext.getServer().getSettings(); - } - - protected final EzyNioSessionManager getSessionManager() { - return (EzyNioSessionManager) - serverContext.getServer().getSessionManager(); - } - - protected final EzySessionManagementSetting getSessionManagementSetting() { - return getServerSettings().getSessionManagement(); - } - - @SuppressWarnings("unchecked") - public static abstract class Builder - implements EzyBuilder { + public EzyAbstractSocketServerBootstrap(Builder builder) { + this.serverContext = builder.serverContext; + this.socketDataReceiver = builder.socketDataReceiver; + this.handlerGroupManager = builder.handlerGroupManager; + this.sessionTicketsQueue = builder.sessionTicketsQueue; + } - protected EzyServerContext serverContext; - private EzySocketDataReceiver socketDataReceiver; - protected EzyHandlerGroupManager handlerGroupManager; - protected EzySessionTicketsQueue sessionTicketsQueue; - - public B serverContext(EzyServerContext context) { - this.serverContext = context; - return (B) this; - } - - public B socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { - this.socketDataReceiver = socketDataReceiver; - return (B)this; - } - - public B handlerGroupManager(EzyHandlerGroupManager manager) { - this.handlerGroupManager = manager; - return (B) this; - } - - public B sessionTicketsQueue(EzySessionTicketsQueue queue) { - this.sessionTicketsQueue = queue; - return (B) this; - } - } + @Override + public void destroy() { + processWithLogException(() -> writingLoopHandler.destroy()); + } + + protected final EzySettings getServerSettings() { + return serverContext.getServer().getSettings(); + } + + protected final EzyNioSessionManager getSessionManager() { + return (EzyNioSessionManager) + serverContext.getServer().getSessionManager(); + } + + protected final EzySessionManagementSetting getSessionManagementSetting() { + return getServerSettings().getSessionManagement(); + } + + @SuppressWarnings("unchecked") + public static abstract class Builder + implements EzyBuilder { + + protected EzyServerContext serverContext; + private EzySocketDataReceiver socketDataReceiver; + protected EzyHandlerGroupManager handlerGroupManager; + protected EzySessionTicketsQueue sessionTicketsQueue; + + public B serverContext(EzyServerContext context) { + this.serverContext = context; + return (B) this; + } + + public B socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { + this.socketDataReceiver = socketDataReceiver; + return (B)this; + } + + public B handlerGroupManager(EzyHandlerGroupManager manager) { + this.handlerGroupManager = manager; + return (B) this; + } + + public B sessionTicketsQueue(EzySessionTicketsQueue queue) { + this.sessionTicketsQueue = queue; + return (B) this; + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioServerBootstrap.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioServerBootstrap.java index 977916eac..108fd0fda 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioServerBootstrap.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioServerBootstrap.java @@ -39,239 +39,239 @@ public class EzyNioServerBootstrap extends EzyHttpServerBootstrap { - - private EzyUdpServerBootstrap udpServerBootstrap; - private EzySocketServerBootstrap socketServerBootstrap; - private EzyWebSocketServerBootstrap websocketServerBootstrap; - - @Setter - private SSLContext sslContext; - @Setter - private EzyResponseApi responseApi; - @Setter - private EzyStreamingApi streamingApi; - @Setter - private EzySocketStreamQueue streamQueue; - @Setter - private EzySocketDataReceiver socketDataReceiver; - @Setter - private EzyHandlerGroupManager handlerGroupManager; - @Setter - private EzySessionTicketsQueue socketSessionTicketsQueue; - @Setter - private EzySessionTicketsRequestQueues socketSessionTicketsRequestQueues; - @Setter - private EzySessionTicketsQueue websocketSessionTicketsQueue; - @Setter - private EzySocketDisconnectionQueue socketDisconnectionQueue; - - private EzySocketEventLoopOneHandler systemRequestHandlingLoopHandler; - - private EzySocketEventLoopOneHandler extensionRequestHandlingLoopHandler; - - private EzySocketEventLoopOneHandler streamHandlingLoopHandler; - - private EzySocketEventLoopOneHandler socketDisconnectionHandlingLoopHandler; - - private EzySocketEventLoopOneHandler socketUserRemovalHandlingLoopHandler; - - @Override - protected void setupServer() { - EzyServer server = getServer(); - ((EzyResponseApiAware)server).setResponseApi(responseApi); - ((EzyStreamingApiAware)server).setStreamingApi(streamingApi); - } - - @Override - protected void startOtherBootstraps(Runnable callback) throws Exception { - startSocketServerBootstrap(); - startUdpServerBootstrap(); - startWebSocketServerBootstrap(); - startRequestHandlingLoopHandlers(); - startStreamHandlingLoopHandlers(); - startDisconnectionHandlingLoopHandlers(); - startUserRemovalHandlingLoopHandlers(); - callback.run(); - } - - private void startSocketServerBootstrap() throws Exception { - EzySocketSetting socketSetting = getSocketSetting(); - if(!socketSetting.isActive()) return; - logger.debug("starting tcp socket server bootstrap ...."); - socketServerBootstrap = newSocketServerBootstrap(); - socketServerBootstrap.start(); - logger.debug("tcp socket server bootstrap has started"); - } - - private void startUdpServerBootstrap() throws Exception { - EzyUdpSetting udpSetting = getUdpSetting(); - if(!udpSetting.isActive()) return; - logger.debug("starting udp socket server bootstrap ...."); - udpServerBootstrap = newUdpServerBootstrap(); - udpServerBootstrap.start(); - logger.debug("udp socket server bootstrap has started"); - } - - protected void startWebSocketServerBootstrap() throws Exception { - EzyWebSocketSetting wsSetting = getWebSocketSetting(); - if(!wsSetting.isActive()) return; - logger.debug("starting websocket server bootstrap ...."); - websocketServerBootstrap = newWebSocketServerBootstrap(); - websocketServerBootstrap.start(); - logger.debug("websockt server bootstrap has started"); - } - - private void startRequestHandlingLoopHandlers() throws Exception { - systemRequestHandlingLoopHandler = newSystemRequestHandlingLoopHandler(); - extensionRequestHandlingLoopHandler = newExtensionRequestHandlingLoopHandler(); - systemRequestHandlingLoopHandler.start(); - extensionRequestHandlingLoopHandler.start(); - } - - private void startStreamHandlingLoopHandlers() throws Exception { - EzySettings settings = this.getServerSettings(); - EzyStreamingSetting streamingSetting = settings.getStreaming(); - if(streamingSetting.isEnable()) { - streamHandlingLoopHandler = newSocketStreamHandlingLoopHandler(); - streamHandlingLoopHandler.start(); - } - } - - private void startDisconnectionHandlingLoopHandlers() throws Exception { - socketDisconnectionHandlingLoopHandler = newSocketDisconnectionHandlingLoopHandler(); - socketDisconnectionHandlingLoopHandler.start(); - } - - private void startUserRemovalHandlingLoopHandlers() throws Exception { - socketUserRemovalHandlingLoopHandler = newSocketUserRemovalHandlingLoopHandler(); - socketUserRemovalHandlingLoopHandler.start(); - } - - private EzySocketServerBootstrap newSocketServerBootstrap() { - return EzySocketServerBootstrap.builder() - .serverContext(context) - .socketDataReceiver(socketDataReceiver) - .handlerGroupManager(handlerGroupManager) - .sessionTicketsQueue(socketSessionTicketsQueue) - .build(); - } - - private EzyUdpServerBootstrap newUdpServerBootstrap() { - return EzyUdpServerBootstrap.builder() - .serverContext(context) - .socketDataReceiver(socketDataReceiver) - .handlerGroupManager(handlerGroupManager) - .build(); - } - - private EzyWebSocketServerBootstrap newWebSocketServerBootstrap() { - return EzyWebSocketServerBootstrap.builder() - .serverContext(context) - .sslContext(sslContext) - .socketDataReceiver(socketDataReceiver) - .handlerGroupManager(handlerGroupManager) - .sessionTicketsQueue(websocketSessionTicketsQueue) - .build(); - } - - private EzySocketEventLoopOneHandler newSystemRequestHandlingLoopHandler() { - EzySocketEventLoopOneHandler loopHandler = new EzySocketSystemRequestHandlingLoopHandler(); - loopHandler.setThreadPoolSize(getSystemRequestHandlerPoolSize()); - EzySocketRequestHandler eventHandler = new EzySocketSystemRequestHandler(); - eventHandler.setDataHandlerGroupFetcher(handlerGroupManager); - eventHandler.setSessionTicketsQueue(socketSessionTicketsRequestQueues.getSystemQueue()); - loopHandler.setEventHandler(eventHandler); - return loopHandler; - } - - private EzySocketEventLoopOneHandler newExtensionRequestHandlingLoopHandler() { - EzySocketEventLoopOneHandler loopHandler = new EzySocketExtensionRequestHandlingLoopHandler(); - loopHandler.setThreadPoolSize(getExtensionRequestHandlerPoolSize()); - EzySocketRequestHandler eventHandler = new EzySocketExtensionRequestHandler(); - eventHandler.setDataHandlerGroupFetcher(handlerGroupManager); - eventHandler.setSessionTicketsQueue(socketSessionTicketsRequestQueues.getExtensionQueue()); - loopHandler.setEventHandler(eventHandler); - return loopHandler; - } - - private EzySocketEventLoopOneHandler newSocketStreamHandlingLoopHandler() { - EzySocketEventLoopOneHandler loopHandler = new EzySocketStreamHandlingLoopHandler(); - loopHandler.setThreadPoolSize(getStreamHandlerPoolSize()); - EzySocketStreamHandler eventHandler = new EzySocketStreamHandler(); - eventHandler.setStreamQueue(streamQueue); - eventHandler.setDataHandlerGroupFetcher(handlerGroupManager); - loopHandler.setEventHandler(eventHandler); - return loopHandler; - } - - private EzySocketEventLoopOneHandler newSocketDisconnectionHandlingLoopHandler() { - EzySocketEventLoopOneHandler loopHandler = new EzySocketDisconnectionHandlingLoopHandler(); - loopHandler.setThreadPoolSize(getSocketDisconnectionHandlerPoolSize()); - EzySocketDisconnectionHandler eventHandler = new EzySocketDisconnectionHandler(); - eventHandler.setDataHandlerGroupRemover(handlerGroupManager); - eventHandler.setDisconnectionQueue(socketDisconnectionQueue); - loopHandler.setEventHandler(eventHandler); - return loopHandler; - } - - private EzySocketEventLoopOneHandler newSocketUserRemovalHandlingLoopHandler() { - EzySocketEventLoopOneHandler loopHandler = new EzySocketUserRemovalHandlingLoopHandler(); - loopHandler.setThreadPoolSize(getSocketUserRemovalHandlerPoolSize()); - EzySocketUserRemovalQueue userRemovalQueue = context.get(EzySocketUserRemovalQueue.class); - EzySocketUserRemovalHandler eventHandler = new EzySocketUserRemovalHandler(userRemovalQueue); - loopHandler.setEventHandler(eventHandler); - return loopHandler; - } - - private int getStreamHandlerPoolSize() { - return getThreadPoolSizeSetting().getStreamHandler(); - } - - private int getSystemRequestHandlerPoolSize() { - return getThreadPoolSizeSetting().getSystemRequestHandler(); - } - - private int getExtensionRequestHandlerPoolSize() { - return getThreadPoolSizeSetting().getExtensionRequestHandler(); - } - - private int getSocketDisconnectionHandlerPoolSize() { - return getThreadPoolSizeSetting().getSocketDisconnectionHandler(); - } - - private int getSocketUserRemovalHandlerPoolSize() { - return getThreadPoolSizeSetting().getSocketUserRemovalHandler(); - } - - @Override - public void destroy() { - super.destroy(); - if(socketServerBootstrap != null) - processWithLogException(() -> socketServerBootstrap.destroy()); - if(websocketServerBootstrap != null) - processWithLogException(() -> websocketServerBootstrap.destroy()); - if(udpServerBootstrap != null) - processWithLogException(() -> udpServerBootstrap.destroy()); - if(socketDataReceiver != null) - processWithLogException(() -> socketDataReceiver.destroy()); - if(handlerGroupManager != null) - processWithLogException(() -> handlerGroupManager.destroy()); - if(systemRequestHandlingLoopHandler != null) - processWithLogException(() -> systemRequestHandlingLoopHandler.destroy()); - if(extensionRequestHandlingLoopHandler != null) - processWithLogException(() -> extensionRequestHandlingLoopHandler.destroy()); - if(socketDisconnectionHandlingLoopHandler != null) - processWithLogException(() -> socketDisconnectionHandlingLoopHandler.destroy()); - if(socketUserRemovalHandlingLoopHandler != null) - processWithLogException(() -> socketUserRemovalHandlingLoopHandler.destroy()); - this.socketServerBootstrap = null; - this.websocketServerBootstrap = null; - this.socketDataReceiver = null; - this.handlerGroupManager = null; - this.systemRequestHandlingLoopHandler = null; - this.extensionRequestHandlingLoopHandler = null; - this.socketDisconnectionHandlingLoopHandler = null; - this.socketUserRemovalHandlingLoopHandler = null; - } - + + private EzyUdpServerBootstrap udpServerBootstrap; + private EzySocketServerBootstrap socketServerBootstrap; + private EzyWebSocketServerBootstrap websocketServerBootstrap; + + @Setter + private SSLContext sslContext; + @Setter + private EzyResponseApi responseApi; + @Setter + private EzyStreamingApi streamingApi; + @Setter + private EzySocketStreamQueue streamQueue; + @Setter + private EzySocketDataReceiver socketDataReceiver; + @Setter + private EzyHandlerGroupManager handlerGroupManager; + @Setter + private EzySessionTicketsQueue socketSessionTicketsQueue; + @Setter + private EzySessionTicketsRequestQueues socketSessionTicketsRequestQueues; + @Setter + private EzySessionTicketsQueue websocketSessionTicketsQueue; + @Setter + private EzySocketDisconnectionQueue socketDisconnectionQueue; + + private EzySocketEventLoopOneHandler systemRequestHandlingLoopHandler; + + private EzySocketEventLoopOneHandler extensionRequestHandlingLoopHandler; + + private EzySocketEventLoopOneHandler streamHandlingLoopHandler; + + private EzySocketEventLoopOneHandler socketDisconnectionHandlingLoopHandler; + + private EzySocketEventLoopOneHandler socketUserRemovalHandlingLoopHandler; + + @Override + protected void setupServer() { + EzyServer server = getServer(); + ((EzyResponseApiAware)server).setResponseApi(responseApi); + ((EzyStreamingApiAware)server).setStreamingApi(streamingApi); + } + + @Override + protected void startOtherBootstraps(Runnable callback) throws Exception { + startSocketServerBootstrap(); + startUdpServerBootstrap(); + startWebSocketServerBootstrap(); + startRequestHandlingLoopHandlers(); + startStreamHandlingLoopHandlers(); + startDisconnectionHandlingLoopHandlers(); + startUserRemovalHandlingLoopHandlers(); + callback.run(); + } + + private void startSocketServerBootstrap() throws Exception { + EzySocketSetting socketSetting = getSocketSetting(); + if(!socketSetting.isActive()) return; + logger.debug("starting tcp socket server bootstrap ...."); + socketServerBootstrap = newSocketServerBootstrap(); + socketServerBootstrap.start(); + logger.debug("tcp socket server bootstrap has started"); + } + + private void startUdpServerBootstrap() throws Exception { + EzyUdpSetting udpSetting = getUdpSetting(); + if(!udpSetting.isActive()) return; + logger.debug("starting udp socket server bootstrap ...."); + udpServerBootstrap = newUdpServerBootstrap(); + udpServerBootstrap.start(); + logger.debug("udp socket server bootstrap has started"); + } + + protected void startWebSocketServerBootstrap() throws Exception { + EzyWebSocketSetting wsSetting = getWebSocketSetting(); + if(!wsSetting.isActive()) return; + logger.debug("starting websocket server bootstrap ...."); + websocketServerBootstrap = newWebSocketServerBootstrap(); + websocketServerBootstrap.start(); + logger.debug("websockt server bootstrap has started"); + } + + private void startRequestHandlingLoopHandlers() throws Exception { + systemRequestHandlingLoopHandler = newSystemRequestHandlingLoopHandler(); + extensionRequestHandlingLoopHandler = newExtensionRequestHandlingLoopHandler(); + systemRequestHandlingLoopHandler.start(); + extensionRequestHandlingLoopHandler.start(); + } + + private void startStreamHandlingLoopHandlers() throws Exception { + EzySettings settings = this.getServerSettings(); + EzyStreamingSetting streamingSetting = settings.getStreaming(); + if(streamingSetting.isEnable()) { + streamHandlingLoopHandler = newSocketStreamHandlingLoopHandler(); + streamHandlingLoopHandler.start(); + } + } + + private void startDisconnectionHandlingLoopHandlers() throws Exception { + socketDisconnectionHandlingLoopHandler = newSocketDisconnectionHandlingLoopHandler(); + socketDisconnectionHandlingLoopHandler.start(); + } + + private void startUserRemovalHandlingLoopHandlers() throws Exception { + socketUserRemovalHandlingLoopHandler = newSocketUserRemovalHandlingLoopHandler(); + socketUserRemovalHandlingLoopHandler.start(); + } + + private EzySocketServerBootstrap newSocketServerBootstrap() { + return EzySocketServerBootstrap.builder() + .serverContext(context) + .socketDataReceiver(socketDataReceiver) + .handlerGroupManager(handlerGroupManager) + .sessionTicketsQueue(socketSessionTicketsQueue) + .build(); + } + + private EzyUdpServerBootstrap newUdpServerBootstrap() { + return EzyUdpServerBootstrap.builder() + .serverContext(context) + .socketDataReceiver(socketDataReceiver) + .handlerGroupManager(handlerGroupManager) + .build(); + } + + private EzyWebSocketServerBootstrap newWebSocketServerBootstrap() { + return EzyWebSocketServerBootstrap.builder() + .serverContext(context) + .sslContext(sslContext) + .socketDataReceiver(socketDataReceiver) + .handlerGroupManager(handlerGroupManager) + .sessionTicketsQueue(websocketSessionTicketsQueue) + .build(); + } + + private EzySocketEventLoopOneHandler newSystemRequestHandlingLoopHandler() { + EzySocketEventLoopOneHandler loopHandler = new EzySocketSystemRequestHandlingLoopHandler(); + loopHandler.setThreadPoolSize(getSystemRequestHandlerPoolSize()); + EzySocketRequestHandler eventHandler = new EzySocketSystemRequestHandler(); + eventHandler.setDataHandlerGroupFetcher(handlerGroupManager); + eventHandler.setSessionTicketsQueue(socketSessionTicketsRequestQueues.getSystemQueue()); + loopHandler.setEventHandler(eventHandler); + return loopHandler; + } + + private EzySocketEventLoopOneHandler newExtensionRequestHandlingLoopHandler() { + EzySocketEventLoopOneHandler loopHandler = new EzySocketExtensionRequestHandlingLoopHandler(); + loopHandler.setThreadPoolSize(getExtensionRequestHandlerPoolSize()); + EzySocketRequestHandler eventHandler = new EzySocketExtensionRequestHandler(); + eventHandler.setDataHandlerGroupFetcher(handlerGroupManager); + eventHandler.setSessionTicketsQueue(socketSessionTicketsRequestQueues.getExtensionQueue()); + loopHandler.setEventHandler(eventHandler); + return loopHandler; + } + + private EzySocketEventLoopOneHandler newSocketStreamHandlingLoopHandler() { + EzySocketEventLoopOneHandler loopHandler = new EzySocketStreamHandlingLoopHandler(); + loopHandler.setThreadPoolSize(getStreamHandlerPoolSize()); + EzySocketStreamHandler eventHandler = new EzySocketStreamHandler(); + eventHandler.setStreamQueue(streamQueue); + eventHandler.setDataHandlerGroupFetcher(handlerGroupManager); + loopHandler.setEventHandler(eventHandler); + return loopHandler; + } + + private EzySocketEventLoopOneHandler newSocketDisconnectionHandlingLoopHandler() { + EzySocketEventLoopOneHandler loopHandler = new EzySocketDisconnectionHandlingLoopHandler(); + loopHandler.setThreadPoolSize(getSocketDisconnectionHandlerPoolSize()); + EzySocketDisconnectionHandler eventHandler = new EzySocketDisconnectionHandler(); + eventHandler.setDataHandlerGroupRemover(handlerGroupManager); + eventHandler.setDisconnectionQueue(socketDisconnectionQueue); + loopHandler.setEventHandler(eventHandler); + return loopHandler; + } + + private EzySocketEventLoopOneHandler newSocketUserRemovalHandlingLoopHandler() { + EzySocketEventLoopOneHandler loopHandler = new EzySocketUserRemovalHandlingLoopHandler(); + loopHandler.setThreadPoolSize(getSocketUserRemovalHandlerPoolSize()); + EzySocketUserRemovalQueue userRemovalQueue = context.get(EzySocketUserRemovalQueue.class); + EzySocketUserRemovalHandler eventHandler = new EzySocketUserRemovalHandler(userRemovalQueue); + loopHandler.setEventHandler(eventHandler); + return loopHandler; + } + + private int getStreamHandlerPoolSize() { + return getThreadPoolSizeSetting().getStreamHandler(); + } + + private int getSystemRequestHandlerPoolSize() { + return getThreadPoolSizeSetting().getSystemRequestHandler(); + } + + private int getExtensionRequestHandlerPoolSize() { + return getThreadPoolSizeSetting().getExtensionRequestHandler(); + } + + private int getSocketDisconnectionHandlerPoolSize() { + return getThreadPoolSizeSetting().getSocketDisconnectionHandler(); + } + + private int getSocketUserRemovalHandlerPoolSize() { + return getThreadPoolSizeSetting().getSocketUserRemovalHandler(); + } + + @Override + public void destroy() { + super.destroy(); + if(socketServerBootstrap != null) + processWithLogException(() -> socketServerBootstrap.destroy()); + if(websocketServerBootstrap != null) + processWithLogException(() -> websocketServerBootstrap.destroy()); + if(udpServerBootstrap != null) + processWithLogException(() -> udpServerBootstrap.destroy()); + if(socketDataReceiver != null) + processWithLogException(() -> socketDataReceiver.destroy()); + if(handlerGroupManager != null) + processWithLogException(() -> handlerGroupManager.destroy()); + if(systemRequestHandlingLoopHandler != null) + processWithLogException(() -> systemRequestHandlingLoopHandler.destroy()); + if(extensionRequestHandlingLoopHandler != null) + processWithLogException(() -> extensionRequestHandlingLoopHandler.destroy()); + if(socketDisconnectionHandlingLoopHandler != null) + processWithLogException(() -> socketDisconnectionHandlingLoopHandler.destroy()); + if(socketUserRemovalHandlingLoopHandler != null) + processWithLogException(() -> socketUserRemovalHandlingLoopHandler.destroy()); + this.socketServerBootstrap = null; + this.websocketServerBootstrap = null; + this.socketDataReceiver = null; + this.handlerGroupManager = null; + this.systemRequestHandlingLoopHandler = null; + this.extensionRequestHandlingLoopHandler = null; + this.socketDisconnectionHandlingLoopHandler = null; + this.socketUserRemovalHandlingLoopHandler = null; + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioStarter.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioStarter.java index 09e4bb935..00e47c3e2 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioStarter.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioStarter.java @@ -9,31 +9,31 @@ public class EzyNioStarter extends EzyStarter { - protected EzyNioStarter(Builder builder) { - super(builder); - } - - @Override - protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { - return new EzyNioServerBootstrapBuilderImpl(); - } - - @SuppressWarnings({ "rawtypes" }) - @Override - protected EzySimpleSessionManager.Builder newSessionManagerBuilder(EzySettings settings) { - return EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(settings.getSessionManagement().getSessionMaxRequestPerSecond()); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyStarter.Builder { - @Override - public EzyStarter build() { - return new EzyNioStarter(this); - } - } + protected EzyNioStarter(Builder builder) { + super(builder); + } + + @Override + protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { + return new EzyNioServerBootstrapBuilderImpl(); + } + + @SuppressWarnings({ "rawtypes" }) + @Override + protected EzySimpleSessionManager.Builder newSessionManagerBuilder(EzySettings settings) { + return EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(settings.getSessionManagement().getSessionMaxRequestPerSecond()); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyStarter.Builder { + @Override + public EzyStarter build() { + return new EzyNioStarter(this); + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzySocketServerBootstrap.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzySocketServerBootstrap.java index 8cdb5cb82..b1cf66ca1 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzySocketServerBootstrap.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzySocketServerBootstrap.java @@ -24,146 +24,146 @@ public class EzySocketServerBootstrap extends EzyAbstractSocketServerBootstrap { - private Selector readSelector; - private Selector acceptSelector; - private ServerSocket serverSocket; - private ServerSocketChannel serverSocketChannel; - - private EzySocketEventLoopHandler readingLoopHandler; - private EzySocketEventLoopHandler socketAcceptanceLoopHandler; - - public EzySocketServerBootstrap(Builder builder) { - super(builder); - } - - @Override - public void start() throws Exception { - openSelectors(); - newAndConfigServerSocketChannel(); - getBindAndConfigServerSocket(); - startSocketHandlers(); - } - - @Override - public void destroy() { - processWithLogException(() -> writingLoopHandler.destroy()); - processWithLogException(() -> readingLoopHandler.destroy()); - processWithLogException(() -> socketAcceptanceLoopHandler.destroy()); - processWithLogException(() -> serverSocket.close()); - processWithLogException(() -> serverSocketChannel.close()); - } - - private void openSelectors() throws Exception { - this.readSelector = openSelector(); - this.acceptSelector = openSelector(); - } - - private void newAndConfigServerSocketChannel() throws Exception { - this.serverSocketChannel = newServerSocketChannel(); - this.serverSocketChannel.configureBlocking(false); - } - - private void getBindAndConfigServerSocket() throws Exception { - this.serverSocket = serverSocketChannel.socket(); - this.serverSocket.setReuseAddress(true); - this.serverSocket.bind(new InetSocketAddress(getSocketAddress(), getSocketPort())); - this.serverSocketChannel.register(acceptSelector, SelectionKey.OP_ACCEPT); - } - - private void startSocketHandlers() throws Exception { - EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor(); - writingLoopHandler = newWritingLoopHandler(); - readingLoopHandler = newReadingLoopHandler(socketAcceptor); - socketAcceptanceLoopHandler = newSocketAcceptanceLoopHandler(socketAcceptor); - socketAcceptanceLoopHandler.start(); - readingLoopHandler.start(); - writingLoopHandler.start(); - } - - private EzySocketEventLoopHandler newWritingLoopHandler() { - EzySocketWritingLoopHandler loopHandler = new EzySocketWritingLoopHandler(); - loopHandler.setThreadPoolSize(getSocketWriterPoolSize()); - loopHandler.setEventHandlerSupplier(() -> { - EzySocketWriter eventHandler = new EzyNioSocketWriter(); - eventHandler.setWriterGroupFetcher(handlerGroupManager); - eventHandler.setSessionTicketsQueue(sessionTicketsQueue); - return eventHandler; - }); - return loopHandler; - } - - private EzySocketEventLoopHandler newReadingLoopHandler( - EzyNioAcceptableConnectionsHandler acceptableConnectionsHandler) { - EzySocketEventLoopOneHandler loopHandler = new EzyNioSocketReadingLoopHandler(); - loopHandler.setThreadPoolSize(getSocketReaderPoolSize()); - EzyNioSocketReader eventHandler = new EzyNioSocketReader(); - eventHandler.setOwnSelector(readSelector); - eventHandler.setSocketDataReceiver(socketDataReceiver); - eventHandler.setAcceptableConnectionsHandler(acceptableConnectionsHandler); - loopHandler.setEventHandler(eventHandler); - return loopHandler; - } - - private EzySocketEventLoopHandler newSocketAcceptanceLoopHandler( - EzyNioSocketAcceptor socketAcceptor) { - EzySocketEventLoopOneHandler loopHandler = new EzyNioSocketAcceptanceLoopHandler(); - loopHandler.setThreadPoolSize(getSocketAcceptorPoolSize()); - socketAcceptor.setTcpNoDelay(getSocketTcpNoDelay()); - socketAcceptor.setReadSelector(readSelector); - socketAcceptor.setOwnSelector(acceptSelector); - socketAcceptor.setAcceptableConnections(new ArrayList<>()); - socketAcceptor.setHandlerGroupManager(handlerGroupManager); - loopHandler.setEventHandler(socketAcceptor); - return loopHandler; - } - - private Selector openSelector() throws Exception { - return Selector.open(); - } - - private ServerSocketChannel newServerSocketChannel() throws Exception { - return ServerSocketChannel.open(); - } - - private int getSocketReaderPoolSize() { - return EzyNioThreadPoolSizes.SOCKET_READER; - } - - private int getSocketWriterPoolSize() { - return getSocketSetting().getWriterThreadPoolSize(); - } - - private int getSocketAcceptorPoolSize() { - return EzyNioThreadPoolSizes.SOCKET_ACCEPTOR; - } - - private int getSocketPort() { - return getSocketSetting().getPort(); - } - - private String getSocketAddress() { - return getSocketSetting().getAddress(); - } - - private boolean getSocketTcpNoDelay() { - return getSocketSetting().isTcpNoDelay(); - } - - private EzySocketSetting getSocketSetting() { - return getServerSettings().getSocket(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder - extends EzyAbstractSocketServerBootstrap.Builder { - - @Override - public EzySocketServerBootstrap build() { - return new EzySocketServerBootstrap(this); - } - - } + private Selector readSelector; + private Selector acceptSelector; + private ServerSocket serverSocket; + private ServerSocketChannel serverSocketChannel; + + private EzySocketEventLoopHandler readingLoopHandler; + private EzySocketEventLoopHandler socketAcceptanceLoopHandler; + + public EzySocketServerBootstrap(Builder builder) { + super(builder); + } + + @Override + public void start() throws Exception { + openSelectors(); + newAndConfigServerSocketChannel(); + getBindAndConfigServerSocket(); + startSocketHandlers(); + } + + @Override + public void destroy() { + processWithLogException(() -> writingLoopHandler.destroy()); + processWithLogException(() -> readingLoopHandler.destroy()); + processWithLogException(() -> socketAcceptanceLoopHandler.destroy()); + processWithLogException(() -> serverSocket.close()); + processWithLogException(() -> serverSocketChannel.close()); + } + + private void openSelectors() throws Exception { + this.readSelector = openSelector(); + this.acceptSelector = openSelector(); + } + + private void newAndConfigServerSocketChannel() throws Exception { + this.serverSocketChannel = newServerSocketChannel(); + this.serverSocketChannel.configureBlocking(false); + } + + private void getBindAndConfigServerSocket() throws Exception { + this.serverSocket = serverSocketChannel.socket(); + this.serverSocket.setReuseAddress(true); + this.serverSocket.bind(new InetSocketAddress(getSocketAddress(), getSocketPort())); + this.serverSocketChannel.register(acceptSelector, SelectionKey.OP_ACCEPT); + } + + private void startSocketHandlers() throws Exception { + EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor(); + writingLoopHandler = newWritingLoopHandler(); + readingLoopHandler = newReadingLoopHandler(socketAcceptor); + socketAcceptanceLoopHandler = newSocketAcceptanceLoopHandler(socketAcceptor); + socketAcceptanceLoopHandler.start(); + readingLoopHandler.start(); + writingLoopHandler.start(); + } + + private EzySocketEventLoopHandler newWritingLoopHandler() { + EzySocketWritingLoopHandler loopHandler = new EzySocketWritingLoopHandler(); + loopHandler.setThreadPoolSize(getSocketWriterPoolSize()); + loopHandler.setEventHandlerSupplier(() -> { + EzySocketWriter eventHandler = new EzyNioSocketWriter(); + eventHandler.setWriterGroupFetcher(handlerGroupManager); + eventHandler.setSessionTicketsQueue(sessionTicketsQueue); + return eventHandler; + }); + return loopHandler; + } + + private EzySocketEventLoopHandler newReadingLoopHandler( + EzyNioAcceptableConnectionsHandler acceptableConnectionsHandler) { + EzySocketEventLoopOneHandler loopHandler = new EzyNioSocketReadingLoopHandler(); + loopHandler.setThreadPoolSize(getSocketReaderPoolSize()); + EzyNioSocketReader eventHandler = new EzyNioSocketReader(); + eventHandler.setOwnSelector(readSelector); + eventHandler.setSocketDataReceiver(socketDataReceiver); + eventHandler.setAcceptableConnectionsHandler(acceptableConnectionsHandler); + loopHandler.setEventHandler(eventHandler); + return loopHandler; + } + + private EzySocketEventLoopHandler newSocketAcceptanceLoopHandler( + EzyNioSocketAcceptor socketAcceptor) { + EzySocketEventLoopOneHandler loopHandler = new EzyNioSocketAcceptanceLoopHandler(); + loopHandler.setThreadPoolSize(getSocketAcceptorPoolSize()); + socketAcceptor.setTcpNoDelay(getSocketTcpNoDelay()); + socketAcceptor.setReadSelector(readSelector); + socketAcceptor.setOwnSelector(acceptSelector); + socketAcceptor.setAcceptableConnections(new ArrayList<>()); + socketAcceptor.setHandlerGroupManager(handlerGroupManager); + loopHandler.setEventHandler(socketAcceptor); + return loopHandler; + } + + private Selector openSelector() throws Exception { + return Selector.open(); + } + + private ServerSocketChannel newServerSocketChannel() throws Exception { + return ServerSocketChannel.open(); + } + + private int getSocketReaderPoolSize() { + return EzyNioThreadPoolSizes.SOCKET_READER; + } + + private int getSocketWriterPoolSize() { + return getSocketSetting().getWriterThreadPoolSize(); + } + + private int getSocketAcceptorPoolSize() { + return EzyNioThreadPoolSizes.SOCKET_ACCEPTOR; + } + + private int getSocketPort() { + return getSocketSetting().getPort(); + } + + private String getSocketAddress() { + return getSocketSetting().getAddress(); + } + + private boolean getSocketTcpNoDelay() { + return getSocketSetting().isTcpNoDelay(); + } + + private EzySocketSetting getSocketSetting() { + return getServerSettings().getSocket(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzyAbstractSocketServerBootstrap.Builder { + + @Override + public EzySocketServerBootstrap build() { + return new EzySocketServerBootstrap(this); + } + + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyUdpServerBootstrap.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyUdpServerBootstrap.java index ee74af9b0..c907679f8 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyUdpServerBootstrap.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyUdpServerBootstrap.java @@ -26,146 +26,146 @@ public class EzyUdpServerBootstrap implements EzyStartable, EzyDestroyable { - private Selector readSelector; - private EzyDatagramChannelPool udpChannelPool; - private EzyNioUdpDataHandler udpDataHandler; - private EzySocketEventLoopHandler readingLoopHandler; - - private final EzyServerContext serverContext; - private final EzySocketDataReceiver socketDataReceiver; - private final EzyHandlerGroupManager handlerGroupManager; - - public EzyUdpServerBootstrap(Builder builder) { - this.serverContext = builder.serverContext; - this.socketDataReceiver = builder.socketDataReceiver; - this.handlerGroupManager = builder.handlerGroupManager; - this.udpChannelPool = newChannelPool(); - this.udpDataHandler = newUdpDataHandler(); - this.serverContext.setProperty(EzyNioUdpDataHandler.class, udpDataHandler); - } - - @Override - public void start() throws Exception { - openSelectors(); - configChannelPool(); - startSocketHandlers(); - } - - @Override - public void destroy() { - processWithLogException(() -> readingLoopHandler.destroy()); - processWithLogException(() -> udpChannelPool.close()); - } - - private void openSelectors() throws Exception { - this.readSelector = openSelector(); - } - - private EzyDatagramChannelPool newChannelPool() { - int poolSize = getUdpSetting().getChannelPoolSize(); - return new EzyDatagramChannelPool(poolSize); - } - - private void configChannelPool() throws Exception { - this.udpChannelPool.bind(new InetSocketAddress(getUdpAddress(), getUdpPort())); - this.udpChannelPool.register(readSelector); - } - - private void startSocketHandlers() throws Exception { - readingLoopHandler = newReadingLoopHandler(); - readingLoopHandler.start(); - } - - private EzySocketEventLoopHandler newReadingLoopHandler() { - EzySocketEventLoopOneHandler loopHandler = new EzyNioUdpReadingLoopHandler(); - loopHandler.setThreadPoolSize(getSocketReaderPoolSize()); - EzyNioUdpReader eventHandler = new EzyNioUdpReader(getUdpMaxRequestSize()); - eventHandler.setOwnSelector(readSelector); - eventHandler.setUdpDataHandler(udpDataHandler); - loopHandler.setEventHandler(eventHandler); - return loopHandler; - } - - private EzyNioUdpDataHandler newUdpDataHandler() { - int handlerThreadPoolSize = getSocketHandlerPoolSize(); - EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(handlerThreadPoolSize); - handler.setResponseApi(getResponseApi()); - handler.setDatagramChannelPool(udpChannelPool); - handler.setSessionManager(getSessionManager()); - handler.setSocketDataReceiver(socketDataReceiver); - handler.setHandlerGroupManager(handlerGroupManager); - return handler; - } - - private Selector openSelector() throws Exception { - return Selector.open(); - } - - private int getSocketReaderPoolSize() { - return EzyNioThreadPoolSizes.SOCKET_READER; - } - - private int getSocketHandlerPoolSize() { - return getUdpSetting().getHandlerThreadPoolSize(); - } - - private int getUdpPort() { - return getUdpSetting().getPort(); - } - - private String getUdpAddress() { - return getUdpSetting().getAddress(); - } - - private int getUdpMaxRequestSize() { - return getUdpSetting().getMaxRequestSize(); - } - - private EzyUdpSetting getUdpSetting() { - return getServerSettings().getUdp(); - } - - private EzySettings getServerSettings() { - return serverContext.getServer().getSettings(); - } - - private EzyResponseApi getResponseApi() { - return serverContext.getServer().getResponseApi(); - } - - @SuppressWarnings("rawtypes") - private EzySessionManager getSessionManager() { - return serverContext.getServer().getSessionManager(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - - private EzyServerContext serverContext; - private EzySocketDataReceiver socketDataReceiver; - private EzyHandlerGroupManager handlerGroupManager; - - public Builder serverContext(EzyServerContext context) { - this.serverContext = context; - return this; - } - - public Builder socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { - this.socketDataReceiver = socketDataReceiver; - return this; - } - - public Builder handlerGroupManager(EzyHandlerGroupManager manager) { - this.handlerGroupManager = manager; - return this; - } - - @Override - public EzyUdpServerBootstrap build() { - return new EzyUdpServerBootstrap(this); - } - } + private Selector readSelector; + private EzyDatagramChannelPool udpChannelPool; + private EzyNioUdpDataHandler udpDataHandler; + private EzySocketEventLoopHandler readingLoopHandler; + + private final EzyServerContext serverContext; + private final EzySocketDataReceiver socketDataReceiver; + private final EzyHandlerGroupManager handlerGroupManager; + + public EzyUdpServerBootstrap(Builder builder) { + this.serverContext = builder.serverContext; + this.socketDataReceiver = builder.socketDataReceiver; + this.handlerGroupManager = builder.handlerGroupManager; + this.udpChannelPool = newChannelPool(); + this.udpDataHandler = newUdpDataHandler(); + this.serverContext.setProperty(EzyNioUdpDataHandler.class, udpDataHandler); + } + + @Override + public void start() throws Exception { + openSelectors(); + configChannelPool(); + startSocketHandlers(); + } + + @Override + public void destroy() { + processWithLogException(() -> readingLoopHandler.destroy()); + processWithLogException(() -> udpChannelPool.close()); + } + + private void openSelectors() throws Exception { + this.readSelector = openSelector(); + } + + private EzyDatagramChannelPool newChannelPool() { + int poolSize = getUdpSetting().getChannelPoolSize(); + return new EzyDatagramChannelPool(poolSize); + } + + private void configChannelPool() throws Exception { + this.udpChannelPool.bind(new InetSocketAddress(getUdpAddress(), getUdpPort())); + this.udpChannelPool.register(readSelector); + } + + private void startSocketHandlers() throws Exception { + readingLoopHandler = newReadingLoopHandler(); + readingLoopHandler.start(); + } + + private EzySocketEventLoopHandler newReadingLoopHandler() { + EzySocketEventLoopOneHandler loopHandler = new EzyNioUdpReadingLoopHandler(); + loopHandler.setThreadPoolSize(getSocketReaderPoolSize()); + EzyNioUdpReader eventHandler = new EzyNioUdpReader(getUdpMaxRequestSize()); + eventHandler.setOwnSelector(readSelector); + eventHandler.setUdpDataHandler(udpDataHandler); + loopHandler.setEventHandler(eventHandler); + return loopHandler; + } + + private EzyNioUdpDataHandler newUdpDataHandler() { + int handlerThreadPoolSize = getSocketHandlerPoolSize(); + EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(handlerThreadPoolSize); + handler.setResponseApi(getResponseApi()); + handler.setDatagramChannelPool(udpChannelPool); + handler.setSessionManager(getSessionManager()); + handler.setSocketDataReceiver(socketDataReceiver); + handler.setHandlerGroupManager(handlerGroupManager); + return handler; + } + + private Selector openSelector() throws Exception { + return Selector.open(); + } + + private int getSocketReaderPoolSize() { + return EzyNioThreadPoolSizes.SOCKET_READER; + } + + private int getSocketHandlerPoolSize() { + return getUdpSetting().getHandlerThreadPoolSize(); + } + + private int getUdpPort() { + return getUdpSetting().getPort(); + } + + private String getUdpAddress() { + return getUdpSetting().getAddress(); + } + + private int getUdpMaxRequestSize() { + return getUdpSetting().getMaxRequestSize(); + } + + private EzyUdpSetting getUdpSetting() { + return getServerSettings().getUdp(); + } + + private EzySettings getServerSettings() { + return serverContext.getServer().getSettings(); + } + + private EzyResponseApi getResponseApi() { + return serverContext.getServer().getResponseApi(); + } + + @SuppressWarnings("rawtypes") + private EzySessionManager getSessionManager() { + return serverContext.getServer().getSessionManager(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private EzyServerContext serverContext; + private EzySocketDataReceiver socketDataReceiver; + private EzyHandlerGroupManager handlerGroupManager; + + public Builder serverContext(EzyServerContext context) { + this.serverContext = context; + return this; + } + + public Builder socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { + this.socketDataReceiver = socketDataReceiver; + return this; + } + + public Builder handlerGroupManager(EzyHandlerGroupManager manager) { + this.handlerGroupManager = manager; + return this; + } + + @Override + public EzyUdpServerBootstrap build() { + return new EzyUdpServerBootstrap(this); + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyWebSocketServerBootstrap.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyWebSocketServerBootstrap.java index 6c7798932..7cf52df34 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyWebSocketServerBootstrap.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyWebSocketServerBootstrap.java @@ -15,86 +15,86 @@ public class EzyWebSocketServerBootstrap extends EzyAbstractSocketServerBootstrap { - private Server server; - private SSLContext sslContext; - - public EzyWebSocketServerBootstrap(Builder builder) { - super(builder); - this.sslContext = builder.sslContext; - } - - @Override - public void start() throws Exception { - server = newSocketServer(); - server.start(); - writingLoopHandler = newWritingLoopHandler(); - writingLoopHandler.start(); - } - - @Override - public void destroy() { - processWithLogException(() -> writingLoopHandler.destroy()); - processWithLogException(() -> server.stop()); - } - - private Server newSocketServer() { - return newSocketServerCreator() - .setting(getWsSetting()) - .sessionManager(getSessionManager()) - .handlerGroupManager(handlerGroupManager) - .sessionManagementSetting(getSessionManagementSetting()) - .socketDataReceiver(socketDataReceiver) - .create(); - } - - private EzySocketEventLoopHandler newWritingLoopHandler() { - EzyWsWritingLoopHandler loopHandler = new EzyWsWritingLoopHandler(); - loopHandler.setThreadPoolSize(getSocketWriterPoolSize()); - loopHandler.setEventHandlerSupplier(() -> { - EzySocketWriter eventHandler = new EzySocketWriter(); - eventHandler.setWriterGroupFetcher(handlerGroupManager); - eventHandler.setSessionTicketsQueue(sessionTicketsQueue); - return eventHandler; - }); - return loopHandler; - } - - private EzyWebSocketServerCreator newSocketServerCreator() { - if(isSslActive()) - return new EzyWebSocketSecureServerCreator(sslContext); - return new EzyWebSocketServerCreator(); - } - - private int getSocketWriterPoolSize() { - return getWsSetting().getWriterThreadPoolSize(); - } - - private boolean isSslActive() { - return getWsSetting().isSslActive(); - } - - private EzyWebSocketSetting getWsSetting() { - return getServerSettings().getWebsocket(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder - extends EzyAbstractSocketServerBootstrap.Builder { - - private SSLContext sslContext; - - public Builder sslContext(SSLContext sslContext) { - this.sslContext = sslContext; - return this; - } - - @Override - public EzyWebSocketServerBootstrap build() { - return new EzyWebSocketServerBootstrap(this); - } - } - + private Server server; + private SSLContext sslContext; + + public EzyWebSocketServerBootstrap(Builder builder) { + super(builder); + this.sslContext = builder.sslContext; + } + + @Override + public void start() throws Exception { + server = newSocketServer(); + server.start(); + writingLoopHandler = newWritingLoopHandler(); + writingLoopHandler.start(); + } + + @Override + public void destroy() { + processWithLogException(() -> writingLoopHandler.destroy()); + processWithLogException(() -> server.stop()); + } + + private Server newSocketServer() { + return newSocketServerCreator() + .setting(getWsSetting()) + .sessionManager(getSessionManager()) + .handlerGroupManager(handlerGroupManager) + .sessionManagementSetting(getSessionManagementSetting()) + .socketDataReceiver(socketDataReceiver) + .create(); + } + + private EzySocketEventLoopHandler newWritingLoopHandler() { + EzyWsWritingLoopHandler loopHandler = new EzyWsWritingLoopHandler(); + loopHandler.setThreadPoolSize(getSocketWriterPoolSize()); + loopHandler.setEventHandlerSupplier(() -> { + EzySocketWriter eventHandler = new EzySocketWriter(); + eventHandler.setWriterGroupFetcher(handlerGroupManager); + eventHandler.setSessionTicketsQueue(sessionTicketsQueue); + return eventHandler; + }); + return loopHandler; + } + + private EzyWebSocketServerCreator newSocketServerCreator() { + if(isSslActive()) + return new EzyWebSocketSecureServerCreator(sslContext); + return new EzyWebSocketServerCreator(); + } + + private int getSocketWriterPoolSize() { + return getWsSetting().getWriterThreadPoolSize(); + } + + private boolean isSslActive() { + return getWsSetting().isSslActive(); + } + + private EzyWebSocketSetting getWsSetting() { + return getServerSettings().getWebsocket(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzyAbstractSocketServerBootstrap.Builder { + + private SSLContext sslContext; + + public Builder sslContext(SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + @Override + public EzyWebSocketServerBootstrap build() { + return new EzyWebSocketServerBootstrap(this); + } + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyHandlerGroupBuilderFactoryImpl.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyHandlerGroupBuilderFactoryImpl.java index 900183a1a..8ae54b289 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyHandlerGroupBuilderFactoryImpl.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyHandlerGroupBuilderFactoryImpl.java @@ -29,175 +29,175 @@ public class EzyHandlerGroupBuilderFactoryImpl implements EzyHandlerGroupBuilderFactory { private final ExecutorService statsThreadPool; - - private final EzyStatistics statistics; - private final AtomicInteger socketSessionCount; - private final AtomicInteger webSocketSessionCount; - private final EzyCodecFactory codecFactory; - private final EzyServerContext serverContext; - private final EzySessionCreator sessionCreator; - private final EzySocketStreamQueue streamQueue; - private final EzySocketDisconnectionQueue disconnectionQueue; - private final EzySessionTicketsQueue socketSessionTicketsQueue; - private final EzySessionTicketsQueue webSocketSessionTicketsQueue; - private final EzySessionTicketsRequestQueues sessionTicketsRequestQueues; - - public EzyHandlerGroupBuilderFactoryImpl(Builder builder) { - this.socketSessionCount = new AtomicInteger(0); - this.webSocketSessionCount = new AtomicInteger(0); - this.statistics = builder.statistics; - this.statsThreadPool = builder.statsThreadPool; - this.streamQueue = builder.streamQueue; - this.codecFactory = builder.codecFactory; - this.serverContext = builder.serverContext; - this.sessionCreator = builder.sessionCreator; - this.disconnectionQueue = builder.disconnectionQueue; - this.socketSessionTicketsQueue = builder.socketSessionTicketsQueue; - this.webSocketSessionTicketsQueue = builder.webSocketSessionTicketsQueue; - this.sessionTicketsRequestQueues = builder.sessionTicketsRequestQueues; - } - - @Override - public EzyAbstractHandlerGroup.Builder newBuilder(EzyChannel channel, EzyConnectionType type) { - EzyAbstractHandlerGroup.Builder builder = (type == EzyConnectionType.SOCKET) - ? newBuilderBySocketType() - : newBuilderByWebSocketType(); - builder.session(sessionCreator.create(channel)); - builder.serverContext(serverContext); - builder.streamQueue(streamQueue); - builder.disconnectionQueue(disconnectionQueue); - builder.decoder(newDataDecoder(type)); - builder.statsThreadPool(statsThreadPool); - builder.sessionTicketsRequestQueues(sessionTicketsRequestQueues); - return builder; - } - - private EzyAbstractHandlerGroup.Builder newBuilderBySocketType() { - EzyAbstractHandlerGroup.Builder builder = EzySimpleNioHandlerGroup.builder(); - builder.sessionCount(socketSessionCount); - builder.sessionStats(getSocketSessionStats()); - builder.networkStats(getSocketNetworkStats()); - builder.sessionTicketsQueue(socketSessionTicketsQueue); - return builder; - } - - private EzyAbstractHandlerGroup.Builder newBuilderByWebSocketType() { - EzyAbstractHandlerGroup.Builder builder = EzySimpleWsHandlerGroup.builder(); - builder.sessionCount(webSocketSessionCount); - builder.sessionStats(getWebSocketSessionStats()); - builder.networkStats(getWebSocketNetworkStats()); - builder.sessionTicketsQueue(webSocketSessionTicketsQueue); - return builder; - } - - private Object newDataDecoder(EzyConnectionType type) { - return codecFactory.newDecoder(type); - } - - private EzySessionStats getSocketSessionStats() { - return (EzySessionStats) getSocketStatistics().getSessionStats(); - } - - private EzySessionStats getWebSocketSessionStats() { - return (EzySessionStats) getWebSocketStatistics().getSessionStats(); - } - - private EzyNetworkStats getSocketNetworkStats() { - return (EzyNetworkStats) getSocketStatistics().getNetworkStats(); - } - - private EzyNetworkStats getWebSocketNetworkStats() { - return (EzyNetworkStats) getWebSocketStatistics().getNetworkStats(); - } - - private EzySocketStatistics getSocketStatistics() { - return statistics.getSocketStats(); - } - - private EzyWebSocketStatistics getWebSocketStatistics() { - return statistics.getWebSocketStats(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - private EzyStatistics statistics; - private ExecutorService statsThreadPool; - private EzyCodecFactory codecFactory; - private EzyServerContext serverContext; - private EzySessionCreator sessionCreator; - private EzySocketStreamQueue streamQueue; - private EzySocketDisconnectionQueue disconnectionQueue; - private EzySessionTicketsQueue socketSessionTicketsQueue; - private EzySessionTicketsQueue webSocketSessionTicketsQueue; - private EzySessionTicketsRequestQueues sessionTicketsRequestQueues; - - public Builder statistics(EzyStatistics statistics) { - this.statistics = statistics; - return this; - } - - public Builder statsThreadPool(ExecutorService statsThreadPool) { - this.statsThreadPool = statsThreadPool; - return this; - } - - public Builder streamQueue(EzySocketStreamQueue streamQueue) { - this.streamQueue = streamQueue; - return this; - } - - public Builder disconnectionQueue(EzySocketDisconnectionQueue disconnectionQueue) { - this.disconnectionQueue = disconnectionQueue; - return this; - } - - public Builder codecFactory(EzyCodecFactory codecFactory) { - this.codecFactory = codecFactory; - return this; - } - - public Builder serverContext(EzyServerContext serverContext) { - this.serverContext = serverContext; - return this; - } - - public Builder sessionCreator(EzySessionCreator sessionCreator) { - this.sessionCreator = sessionCreator; - return this; - } - - public Builder socketSessionTicketsQueue(EzySessionTicketsQueue socketSessionTicketsQueue) { - this.socketSessionTicketsQueue = socketSessionTicketsQueue; - return this; - } - - public Builder webSocketSessionTicketsQueue(EzySessionTicketsQueue webSocketSessionTicketsQueue) { - this.webSocketSessionTicketsQueue = webSocketSessionTicketsQueue; - return this; - } - - public Builder sessionTicketsRequestQueues(EzySessionTicketsRequestQueues sessionTicketsRequestQueues) { - this.sessionTicketsRequestQueues = sessionTicketsRequestQueues; - return this; - } - - @Override - public EzyHandlerGroupBuilderFactory build() { - if(sessionCreator == null) - this.sessionCreator = newSessionCreator(serverContext); - return new EzyHandlerGroupBuilderFactoryImpl(this); - } - - protected EzySessionCreator newSessionCreator(EzyServerContext serverContext) { - EzyServer server = serverContext.getServer(); - EzySettings settings = server.getSettings(); - return EzySimpleSessionCreator.builder() - .sessionManager(server.getSessionManager()) - .sessionSetting(settings.getSessionManagement()) - .build(); - } - } + + private final EzyStatistics statistics; + private final AtomicInteger socketSessionCount; + private final AtomicInteger webSocketSessionCount; + private final EzyCodecFactory codecFactory; + private final EzyServerContext serverContext; + private final EzySessionCreator sessionCreator; + private final EzySocketStreamQueue streamQueue; + private final EzySocketDisconnectionQueue disconnectionQueue; + private final EzySessionTicketsQueue socketSessionTicketsQueue; + private final EzySessionTicketsQueue webSocketSessionTicketsQueue; + private final EzySessionTicketsRequestQueues sessionTicketsRequestQueues; + + public EzyHandlerGroupBuilderFactoryImpl(Builder builder) { + this.socketSessionCount = new AtomicInteger(0); + this.webSocketSessionCount = new AtomicInteger(0); + this.statistics = builder.statistics; + this.statsThreadPool = builder.statsThreadPool; + this.streamQueue = builder.streamQueue; + this.codecFactory = builder.codecFactory; + this.serverContext = builder.serverContext; + this.sessionCreator = builder.sessionCreator; + this.disconnectionQueue = builder.disconnectionQueue; + this.socketSessionTicketsQueue = builder.socketSessionTicketsQueue; + this.webSocketSessionTicketsQueue = builder.webSocketSessionTicketsQueue; + this.sessionTicketsRequestQueues = builder.sessionTicketsRequestQueues; + } + + @Override + public EzyAbstractHandlerGroup.Builder newBuilder(EzyChannel channel, EzyConnectionType type) { + EzyAbstractHandlerGroup.Builder builder = (type == EzyConnectionType.SOCKET) + ? newBuilderBySocketType() + : newBuilderByWebSocketType(); + builder.session(sessionCreator.create(channel)); + builder.serverContext(serverContext); + builder.streamQueue(streamQueue); + builder.disconnectionQueue(disconnectionQueue); + builder.decoder(newDataDecoder(type)); + builder.statsThreadPool(statsThreadPool); + builder.sessionTicketsRequestQueues(sessionTicketsRequestQueues); + return builder; + } + + private EzyAbstractHandlerGroup.Builder newBuilderBySocketType() { + EzyAbstractHandlerGroup.Builder builder = EzySimpleNioHandlerGroup.builder(); + builder.sessionCount(socketSessionCount); + builder.sessionStats(getSocketSessionStats()); + builder.networkStats(getSocketNetworkStats()); + builder.sessionTicketsQueue(socketSessionTicketsQueue); + return builder; + } + + private EzyAbstractHandlerGroup.Builder newBuilderByWebSocketType() { + EzyAbstractHandlerGroup.Builder builder = EzySimpleWsHandlerGroup.builder(); + builder.sessionCount(webSocketSessionCount); + builder.sessionStats(getWebSocketSessionStats()); + builder.networkStats(getWebSocketNetworkStats()); + builder.sessionTicketsQueue(webSocketSessionTicketsQueue); + return builder; + } + + private Object newDataDecoder(EzyConnectionType type) { + return codecFactory.newDecoder(type); + } + + private EzySessionStats getSocketSessionStats() { + return (EzySessionStats) getSocketStatistics().getSessionStats(); + } + + private EzySessionStats getWebSocketSessionStats() { + return (EzySessionStats) getWebSocketStatistics().getSessionStats(); + } + + private EzyNetworkStats getSocketNetworkStats() { + return (EzyNetworkStats) getSocketStatistics().getNetworkStats(); + } + + private EzyNetworkStats getWebSocketNetworkStats() { + return (EzyNetworkStats) getWebSocketStatistics().getNetworkStats(); + } + + private EzySocketStatistics getSocketStatistics() { + return statistics.getSocketStats(); + } + + private EzyWebSocketStatistics getWebSocketStatistics() { + return statistics.getWebSocketStats(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + private EzyStatistics statistics; + private ExecutorService statsThreadPool; + private EzyCodecFactory codecFactory; + private EzyServerContext serverContext; + private EzySessionCreator sessionCreator; + private EzySocketStreamQueue streamQueue; + private EzySocketDisconnectionQueue disconnectionQueue; + private EzySessionTicketsQueue socketSessionTicketsQueue; + private EzySessionTicketsQueue webSocketSessionTicketsQueue; + private EzySessionTicketsRequestQueues sessionTicketsRequestQueues; + + public Builder statistics(EzyStatistics statistics) { + this.statistics = statistics; + return this; + } + + public Builder statsThreadPool(ExecutorService statsThreadPool) { + this.statsThreadPool = statsThreadPool; + return this; + } + + public Builder streamQueue(EzySocketStreamQueue streamQueue) { + this.streamQueue = streamQueue; + return this; + } + + public Builder disconnectionQueue(EzySocketDisconnectionQueue disconnectionQueue) { + this.disconnectionQueue = disconnectionQueue; + return this; + } + + public Builder codecFactory(EzyCodecFactory codecFactory) { + this.codecFactory = codecFactory; + return this; + } + + public Builder serverContext(EzyServerContext serverContext) { + this.serverContext = serverContext; + return this; + } + + public Builder sessionCreator(EzySessionCreator sessionCreator) { + this.sessionCreator = sessionCreator; + return this; + } + + public Builder socketSessionTicketsQueue(EzySessionTicketsQueue socketSessionTicketsQueue) { + this.socketSessionTicketsQueue = socketSessionTicketsQueue; + return this; + } + + public Builder webSocketSessionTicketsQueue(EzySessionTicketsQueue webSocketSessionTicketsQueue) { + this.webSocketSessionTicketsQueue = webSocketSessionTicketsQueue; + return this; + } + + public Builder sessionTicketsRequestQueues(EzySessionTicketsRequestQueues sessionTicketsRequestQueues) { + this.sessionTicketsRequestQueues = sessionTicketsRequestQueues; + return this; + } + + @Override + public EzyHandlerGroupBuilderFactory build() { + if(sessionCreator == null) + this.sessionCreator = newSessionCreator(serverContext); + return new EzyHandlerGroupBuilderFactoryImpl(this); + } + + protected EzySessionCreator newSessionCreator(EzyServerContext serverContext) { + EzyServer server = serverContext.getServer(); + EzySettings settings = server.getSettings(); + return EzySimpleSessionCreator.builder() + .sessionManager(server.getSessionManager()) + .sessionSetting(settings.getSessionManagement()) + .build(); + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyNioServerBootstrapBuilderImpl.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyNioServerBootstrapBuilderImpl.java index 6f233a8b5..923629326 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyNioServerBootstrapBuilderImpl.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyNioServerBootstrapBuilderImpl.java @@ -26,120 +26,120 @@ import com.tvd12.ezyfoxserver.socket.EzySocketStreamQueue; public class EzyNioServerBootstrapBuilderImpl - extends EzyHttpServerBootstrapBuilder - implements EzyNioServerBootstrapBuilder { - - @Override - protected EzyServerBootstrap newServerBootstrap() { - ExecutorService statsThreadPool = newStatsThreadPool(); - EzyCodecFactory codecFactory = newCodecFactory(); - EzyStreamingApi streamingApi = newStreamingApi(); - EzyResponseApi responseApi = newResponseApi(codecFactory); - EzySocketStreamQueue streamQueue = newStreamQueue(); - EzySessionTicketsQueue socketSessionTicketsQueue = newSocketSessionTicketsQueue(); - EzySessionTicketsQueue websocketSessionTicketsQueue = newWebSocketSessionTicketsQueue(); - EzySocketDisconnectionQueue socketDisconnectionQueue = newSocketDisconnectionQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = newSessionTicketsRequestQueues(); - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = newHandlerGroupBuilderFactory( - statsThreadPool, - codecFactory, - streamQueue, - socketDisconnectionQueue, - socketSessionTicketsQueue, - websocketSessionTicketsQueue, - sessionTicketsRequestQueues); - EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager( - handlerGroupBuilderFactory); - EzySocketDataReceiver socketDataReceiver = newSocketDataReceiver(handlerGroupManager); - EzyNioServerBootstrap bootstrap = new EzyNioServerBootstrap(); - bootstrap.setResponseApi(responseApi); - bootstrap.setStreamingApi(streamingApi); - bootstrap.setStreamQueue(streamQueue); - bootstrap.setSocketDataReceiver(socketDataReceiver); - bootstrap.setHandlerGroupManager(handlerGroupManager); - bootstrap.setSocketDisconnectionQueue(socketDisconnectionQueue); - bootstrap.setSocketSessionTicketsQueue(socketSessionTicketsQueue); - bootstrap.setWebsocketSessionTicketsQueue(websocketSessionTicketsQueue); - bootstrap.setSocketSessionTicketsRequestQueues(sessionTicketsRequestQueues); - bootstrap.setSslContext(newSslContext(getWebsocketSetting().getSslConfig())); - return bootstrap; - } - - private EzyHandlerGroupManager newHandlerGroupManager( - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory) { - - return EzyHandlerGroupManagerImpl.builder() - .handlerGroupBuilderFactory(handlerGroupBuilderFactory) - .build(); - } - - private EzyHandlerGroupBuilderFactory newHandlerGroupBuilderFactory( - ExecutorService statsThreadPool, - EzyCodecFactory codecFactory, - EzySocketStreamQueue streamQueue, - EzySocketDisconnectionQueue disconnectionQueue, - EzySessionTicketsQueue socketSessionTicketsQueue, - EzySessionTicketsQueue websocketSessionTicketsQueue, - EzySessionTicketsRequestQueues sessionTicketsRequestQueues) { - - return EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(server.getStatistics()) - .serverContext(serverContext) - .streamQueue(streamQueue) - .codecFactory(codecFactory) - .statsThreadPool(statsThreadPool) - .disconnectionQueue(disconnectionQueue) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(websocketSessionTicketsQueue) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - } - - protected EzyStreamingApi newStreamingApi() { - return new EzyProxyStreamingApi(); - } - - protected EzyResponseApi newResponseApi(EzyCodecFactory codecFactory) { - return new EzyProxyResponseApi(codecFactory); - } - - private ExecutorService newStatsThreadPool() { - int threadPoolSize = getThreadPoolSizeSetting().getStatistics(); - return EzyExecutors.newFixedThreadPool(threadPoolSize, "statistics"); - } - - private EzySocketDataReceiver newSocketDataReceiver(EzyHandlerGroupManager handlerGroupManager) { - return EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .threadPoolSize(getThreadPoolSizeSetting().getSocketDataReceiver()) - .build(); - } - - private EzySocketStreamQueue newStreamQueue() { - return new EzyBlockingSocketStreamQueue(); - } - - private EzySessionTicketsQueue newSocketSessionTicketsQueue() { - return new EzyBlockingSessionTicketsQueue(); - } - - private EzySessionTicketsQueue newWebSocketSessionTicketsQueue() { - return new EzyBlockingSessionTicketsQueue(); - } - - private EzySocketDisconnectionQueue newSocketDisconnectionQueue() { - return new EzyBlockingSocketDisconnectionQueue(); - } - - private EzySessionTicketsRequestQueues newSessionTicketsRequestQueues() { - return new EzySessionTicketsRequestQueues(); - } - - private EzyCodecFactory newCodecFactory() { - return EzySimpleCodecFactory.builder() - .socketSetting(getSocketSetting()) - .websocketSetting(getWebsocketSetting()) - .build(); + extends EzyHttpServerBootstrapBuilder + implements EzyNioServerBootstrapBuilder { + + @Override + protected EzyServerBootstrap newServerBootstrap() { + ExecutorService statsThreadPool = newStatsThreadPool(); + EzyCodecFactory codecFactory = newCodecFactory(); + EzyStreamingApi streamingApi = newStreamingApi(); + EzyResponseApi responseApi = newResponseApi(codecFactory); + EzySocketStreamQueue streamQueue = newStreamQueue(); + EzySessionTicketsQueue socketSessionTicketsQueue = newSocketSessionTicketsQueue(); + EzySessionTicketsQueue websocketSessionTicketsQueue = newWebSocketSessionTicketsQueue(); + EzySocketDisconnectionQueue socketDisconnectionQueue = newSocketDisconnectionQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = newSessionTicketsRequestQueues(); + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = newHandlerGroupBuilderFactory( + statsThreadPool, + codecFactory, + streamQueue, + socketDisconnectionQueue, + socketSessionTicketsQueue, + websocketSessionTicketsQueue, + sessionTicketsRequestQueues); + EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager( + handlerGroupBuilderFactory); + EzySocketDataReceiver socketDataReceiver = newSocketDataReceiver(handlerGroupManager); + EzyNioServerBootstrap bootstrap = new EzyNioServerBootstrap(); + bootstrap.setResponseApi(responseApi); + bootstrap.setStreamingApi(streamingApi); + bootstrap.setStreamQueue(streamQueue); + bootstrap.setSocketDataReceiver(socketDataReceiver); + bootstrap.setHandlerGroupManager(handlerGroupManager); + bootstrap.setSocketDisconnectionQueue(socketDisconnectionQueue); + bootstrap.setSocketSessionTicketsQueue(socketSessionTicketsQueue); + bootstrap.setWebsocketSessionTicketsQueue(websocketSessionTicketsQueue); + bootstrap.setSocketSessionTicketsRequestQueues(sessionTicketsRequestQueues); + bootstrap.setSslContext(newSslContext(getWebsocketSetting().getSslConfig())); + return bootstrap; + } + + private EzyHandlerGroupManager newHandlerGroupManager( + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory) { + + return EzyHandlerGroupManagerImpl.builder() + .handlerGroupBuilderFactory(handlerGroupBuilderFactory) + .build(); + } + + private EzyHandlerGroupBuilderFactory newHandlerGroupBuilderFactory( + ExecutorService statsThreadPool, + EzyCodecFactory codecFactory, + EzySocketStreamQueue streamQueue, + EzySocketDisconnectionQueue disconnectionQueue, + EzySessionTicketsQueue socketSessionTicketsQueue, + EzySessionTicketsQueue websocketSessionTicketsQueue, + EzySessionTicketsRequestQueues sessionTicketsRequestQueues) { + + return EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(server.getStatistics()) + .serverContext(serverContext) + .streamQueue(streamQueue) + .codecFactory(codecFactory) + .statsThreadPool(statsThreadPool) + .disconnectionQueue(disconnectionQueue) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(websocketSessionTicketsQueue) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + } + + protected EzyStreamingApi newStreamingApi() { + return new EzyProxyStreamingApi(); + } + + protected EzyResponseApi newResponseApi(EzyCodecFactory codecFactory) { + return new EzyProxyResponseApi(codecFactory); + } + + private ExecutorService newStatsThreadPool() { + int threadPoolSize = getThreadPoolSizeSetting().getStatistics(); + return EzyExecutors.newFixedThreadPool(threadPoolSize, "statistics"); + } + + private EzySocketDataReceiver newSocketDataReceiver(EzyHandlerGroupManager handlerGroupManager) { + return EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .threadPoolSize(getThreadPoolSizeSetting().getSocketDataReceiver()) + .build(); + } + + private EzySocketStreamQueue newStreamQueue() { + return new EzyBlockingSocketStreamQueue(); + } + + private EzySessionTicketsQueue newSocketSessionTicketsQueue() { + return new EzyBlockingSessionTicketsQueue(); + } + + private EzySessionTicketsQueue newWebSocketSessionTicketsQueue() { + return new EzyBlockingSessionTicketsQueue(); } - + + private EzySocketDisconnectionQueue newSocketDisconnectionQueue() { + return new EzyBlockingSocketDisconnectionQueue(); + } + + private EzySessionTicketsRequestQueues newSessionTicketsRequestQueues() { + return new EzySessionTicketsRequestQueues(); + } + + private EzyCodecFactory newCodecFactory() { + return EzySimpleCodecFactory.builder() + .socketSetting(getSocketSetting()) + .websocketSetting(getWebsocketSetting()) + .build(); + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketSecureServerCreator.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketSecureServerCreator.java index 8b8c40a5a..b4bc3692b 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketSecureServerCreator.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketSecureServerCreator.java @@ -13,31 +13,31 @@ public class EzyWebSocketSecureServerCreator extends EzyWebSocketServerCreator { - protected SSLContext sslContext; - - public EzyWebSocketSecureServerCreator(SSLContext sslContext) { - this.sslContext = sslContext; - } - - @Override - protected void configServer( - Server server, HttpConfiguration httpConfig, ServerConnector wsConnector) { - - HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); - httpsConfig.addCustomizer(new SecureRequestCustomizer()); - - SslContextFactory sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setSslContext(sslContext); - - ServerConnector wssConnector = new ServerConnector(server, - new SslConnectionFactory(sslContextFactory, - HttpVersion.HTTP_1_1.asString()), - new HttpConnectionFactory(httpsConfig)); - - wssConnector.setHost(setting.getAddress()); - wssConnector.setPort(setting.getSslPort()); - - server.addConnector(wssConnector); - } - + protected SSLContext sslContext; + + public EzyWebSocketSecureServerCreator(SSLContext sslContext) { + this.sslContext = sslContext; + } + + @Override + protected void configServer( + Server server, HttpConfiguration httpConfig, ServerConnector wsConnector) { + + HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); + httpsConfig.addCustomizer(new SecureRequestCustomizer()); + + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setSslContext(sslContext); + + ServerConnector wssConnector = new ServerConnector(server, + new SslConnectionFactory(sslContextFactory, + HttpVersion.HTTP_1_1.asString()), + new HttpConnectionFactory(httpsConfig)); + + wssConnector.setHost(setting.getAddress()); + wssConnector.setPort(setting.getSslPort()); + + server.addConnector(wssConnector); + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerCreator.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerCreator.java index e956e3074..956f4fc99 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerCreator.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerCreator.java @@ -30,112 +30,112 @@ public class EzyWebSocketServerCreator { - protected EzySocketDataReceiver socketDataReceiver; - protected EzyWebSocketSetting setting; - protected EzyNioSessionManager sessionManager; - protected EzyHandlerGroupManager handlerGroupManager; - protected EzySessionManagementSetting sessionManagementSetting; - - public EzyWebSocketServerCreator socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { - this.socketDataReceiver = socketDataReceiver; - return this; - } - - public EzyWebSocketServerCreator setting(EzyWebSocketSetting setting) { - this.setting = setting; - return this; - } - - public EzyWebSocketServerCreator sessionManager(EzyNioSessionManager sessionManager) { - this.sessionManager = sessionManager; - return this; - } - - public EzyWebSocketServerCreator handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { - this.handlerGroupManager = handlerGroupManager; - return this; - } - - public EzyWebSocketServerCreator sessionManagementSetting(EzySessionManagementSetting sessionManagementSetting) { - this.sessionManagementSetting = sessionManagementSetting; - return this; - } - - public Server create() { - ContextHandler wsContextHandler = new ContextHandler("/ws"); - wsContextHandler.setAllowNullPathInfo(true); - EzyWsHandler wsHandler = newWsHandler(); - wsContextHandler.setHandler(newWebSocketHandler(wsHandler)); - QueuedThreadPool threadPool = new QueuedThreadPool(16, 8); - threadPool.setName("ezyfox-ws-handler"); - Server server = new Server(threadPool); - ContextHandlerCollection contextHandlers = new ContextHandlerCollection(); - contextHandlers.addHandler(wsContextHandler); - if(setting.isManagementEnable()) - contextHandlers.addHandler(managementHandler()); - server.setHandler(contextHandlers); - HttpConfiguration httpConfig = new HttpConfiguration(); - httpConfig.setSecureScheme("https"); - httpConfig.setSecurePort(setting.getSslPort()); - ServerConnector wsConnector = new ServerConnector(server); - wsConnector.setPort(setting.getPort()); - wsConnector.setHost(setting.getAddress()); - server.addConnector(wsConnector); - configServer(server, httpConfig, wsConnector); - return server; - } - - private ContextHandler managementHandler() { - ServletContextHandler contextHandler = new ServletContextHandler(); - contextHandler.setContextPath("/management"); - contextHandler.addServlet(HealthCheckServlet.class, "/health-check"); - return contextHandler; - } - - protected void configServer( - Server server, HttpConfiguration httpConfig, ServerConnector wsConnector) { - - } - - private EzyWsHandler newWsHandler() { - return EzyWsHandler.builder() - .sessionManager(sessionManager) - .handlerGroupManager(handlerGroupManager) - .sessionManagementSetting(sessionManagementSetting) - .socketDataReceiver(socketDataReceiver) - .build(); - } - - private WebSocketCreator newWebSocketCreator(EzyWsHandler handler) { - return new WebSocketCreator() { - @Override - public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) { - return handler; - } - }; - } - - private WebSocketHandler newWebSocketHandler(EzyWsHandler handler) { - return new WebSocketHandler() { - @Override - public void configure(WebSocketServletFactory factory) { - WebSocketPolicy policy = factory.getPolicy(); - factory.setCreator(newWebSocketCreator(handler)); - policy.setMaxTextMessageSize(setting.getMaxFrameSize()); - policy.setMaxBinaryMessageSize(setting.getMaxFrameSize()); - policy.setMaxTextMessageBufferSize(setting.getMaxFrameSize()); - policy.setMaxBinaryMessageBufferSize(setting.getMaxFrameSize()); - } - }; - } - - public static class HealthCheckServlet extends HttpServlet { - private static final long serialVersionUID = -5456527539188272097L; - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.setStatus(200); - } - } - + protected EzySocketDataReceiver socketDataReceiver; + protected EzyWebSocketSetting setting; + protected EzyNioSessionManager sessionManager; + protected EzyHandlerGroupManager handlerGroupManager; + protected EzySessionManagementSetting sessionManagementSetting; + + public EzyWebSocketServerCreator socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { + this.socketDataReceiver = socketDataReceiver; + return this; + } + + public EzyWebSocketServerCreator setting(EzyWebSocketSetting setting) { + this.setting = setting; + return this; + } + + public EzyWebSocketServerCreator sessionManager(EzyNioSessionManager sessionManager) { + this.sessionManager = sessionManager; + return this; + } + + public EzyWebSocketServerCreator handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { + this.handlerGroupManager = handlerGroupManager; + return this; + } + + public EzyWebSocketServerCreator sessionManagementSetting(EzySessionManagementSetting sessionManagementSetting) { + this.sessionManagementSetting = sessionManagementSetting; + return this; + } + + public Server create() { + ContextHandler wsContextHandler = new ContextHandler("/ws"); + wsContextHandler.setAllowNullPathInfo(true); + EzyWsHandler wsHandler = newWsHandler(); + wsContextHandler.setHandler(newWebSocketHandler(wsHandler)); + QueuedThreadPool threadPool = new QueuedThreadPool(16, 8); + threadPool.setName("ezyfox-ws-handler"); + Server server = new Server(threadPool); + ContextHandlerCollection contextHandlers = new ContextHandlerCollection(); + contextHandlers.addHandler(wsContextHandler); + if(setting.isManagementEnable()) + contextHandlers.addHandler(managementHandler()); + server.setHandler(contextHandlers); + HttpConfiguration httpConfig = new HttpConfiguration(); + httpConfig.setSecureScheme("https"); + httpConfig.setSecurePort(setting.getSslPort()); + ServerConnector wsConnector = new ServerConnector(server); + wsConnector.setPort(setting.getPort()); + wsConnector.setHost(setting.getAddress()); + server.addConnector(wsConnector); + configServer(server, httpConfig, wsConnector); + return server; + } + + private ContextHandler managementHandler() { + ServletContextHandler contextHandler = new ServletContextHandler(); + contextHandler.setContextPath("/management"); + contextHandler.addServlet(HealthCheckServlet.class, "/health-check"); + return contextHandler; + } + + protected void configServer( + Server server, HttpConfiguration httpConfig, ServerConnector wsConnector) { + + } + + private EzyWsHandler newWsHandler() { + return EzyWsHandler.builder() + .sessionManager(sessionManager) + .handlerGroupManager(handlerGroupManager) + .sessionManagementSetting(sessionManagementSetting) + .socketDataReceiver(socketDataReceiver) + .build(); + } + + private WebSocketCreator newWebSocketCreator(EzyWsHandler handler) { + return new WebSocketCreator() { + @Override + public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) { + return handler; + } + }; + } + + private WebSocketHandler newWebSocketHandler(EzyWsHandler handler) { + return new WebSocketHandler() { + @Override + public void configure(WebSocketServletFactory factory) { + WebSocketPolicy policy = factory.getPolicy(); + factory.setCreator(newWebSocketCreator(handler)); + policy.setMaxTextMessageSize(setting.getMaxFrameSize()); + policy.setMaxBinaryMessageSize(setting.getMaxFrameSize()); + policy.setMaxTextMessageBufferSize(setting.getMaxFrameSize()); + policy.setMaxBinaryMessageBufferSize(setting.getMaxFrameSize()); + } + }; + } + + public static class HealthCheckServlet extends HttpServlet { + private static final long serialVersionUID = -5456527539188272097L; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setStatus(200); + } + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/constant/EzyNioThreadPoolSizes.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/constant/EzyNioThreadPoolSizes.java index 9c960a884..618a6ccbb 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/constant/EzyNioThreadPoolSizes.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/constant/EzyNioThreadPoolSizes.java @@ -2,9 +2,9 @@ public final class EzyNioThreadPoolSizes { - public static final int SOCKET_READER = 1; - public static final int SOCKET_ACCEPTOR = 1; - - private EzyNioThreadPoolSizes() {} - + public static final int SOCKET_READER = 1; + public static final int SOCKET_ACCEPTOR = 1; + + private EzyNioThreadPoolSizes() {} + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzyDecodeDelegate.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzyDecodeDelegate.java index 3afd3c631..e277e3da2 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzyDecodeDelegate.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzyDecodeDelegate.java @@ -2,6 +2,6 @@ public interface EzyDecodeDelegate { - void onDecoded(); - + void onDecoded(); + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyNioSession.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyNioSession.java index dd2259b10..66538ab39 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyNioSession.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyNioSession.java @@ -6,8 +6,8 @@ public interface EzyNioSession extends EzySession { - String SELECTION_KEY = "SessionSelectionKey"; - - SelectionKey getSelectionKey(); - + String SELECTION_KEY = "SessionSelectionKey"; + + SelectionKey getSelectionKey(); + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzySimpleSession.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzySimpleSession.java index 9486fbaa6..4631ff2ff 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzySimpleSession.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzySimpleSession.java @@ -10,11 +10,11 @@ @Setter @Getter public class EzySimpleSession extends EzyAbstractSession implements EzyNioSession { - private static final long serialVersionUID = -8390274886953462147L; + private static final long serialVersionUID = -8390274886953462147L; + + @Override + public SelectionKey getSelectionKey() { + return (SelectionKey) properties.get(SELECTION_KEY); + } - @Override - public SelectionKey getSelectionKey() { - return (SelectionKey) properties.get(SELECTION_KEY); - } - } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyHandlerGroupBuilderFactory.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyHandlerGroupBuilderFactory.java index 03f7fc900..f48b61e57 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyHandlerGroupBuilderFactory.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyHandlerGroupBuilderFactory.java @@ -6,6 +6,6 @@ public interface EzyHandlerGroupBuilderFactory { - EzyAbstractHandlerGroup.Builder newBuilder(EzyChannel channel, EzyConnectionType type); - + EzyAbstractHandlerGroup.Builder newBuilder(EzyChannel channel, EzyConnectionType type); + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyNioSessionFactory.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyNioSessionFactory.java index fe54f86e3..a13cf998e 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyNioSessionFactory.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyNioSessionFactory.java @@ -6,10 +6,10 @@ public class EzyNioSessionFactory extends EzyAbstractSessionFactory { - @Override - protected EzyNioSession newSession() { - EzySimpleSession session = new EzySimpleSession(); - return session; - } - + @Override + protected EzyNioSession newSession() { + EzySimpleSession session = new EzySimpleSession(); + return session; + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractHandlerGroup.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractHandlerGroup.java index 7b46ccc5d..2e81e7d42 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractHandlerGroup.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractHandlerGroup.java @@ -34,329 +34,329 @@ import com.tvd12.ezyfoxserver.statistics.EzySessionStats; public abstract class EzyAbstractHandlerGroup - < - D extends EzyDestroyable - > - extends EzyLoggable - implements - EzyImmediateDeliver, - EzyDroppedPackets, - EzyDestroyable { + < + D extends EzyDestroyable + > + extends EzyLoggable + implements + EzyImmediateDeliver, + EzyDroppedPackets, + EzyDestroyable { - protected final EzyChannel channel; - - protected final D decoder; - protected final EzyNioDataHandler handler; + protected final EzyChannel channel; + + protected final D decoder; + protected final EzyNioDataHandler handler; - protected final boolean streamingEnable; - protected final AtomicInteger sessionCount; - protected final EzySessionStats sessionStats; - protected final EzyNetworkStats networkStats; - - protected final ExecutorService statsThreadPool; + protected final boolean streamingEnable; + protected final AtomicInteger sessionCount; + protected final EzySessionStats sessionStats; + protected final EzyNetworkStats networkStats; + + protected final ExecutorService statsThreadPool; - protected final EzyNioSession session; - protected final EzySocketStreamQueue streamQueue; - protected final EzySessionTicketsQueue sessionTicketsQueue; - protected final EzySocketDisconnectionQueue disconnectionQueue; - protected final EzySessionTicketsRequestQueues sessionTicketsRequestQueues; - - public EzyAbstractHandlerGroup(Builder builder) { - this.session = builder.session; - this.sessionCount = builder.sessionCount; - this.sessionStats = builder.sessionStats; - this.networkStats = builder.networkStats; - this.statsThreadPool = builder.statsThreadPool; - this.streamQueue = builder.streamQueue; - this.streamingEnable = builder.isStreamingEnable(); - this.disconnectionQueue = builder.disconnectionQueue; - this.sessionTicketsQueue = builder.sessionTicketsQueue; - this.sessionTicketsRequestQueues = builder.sessionTicketsRequestQueues; + protected final EzyNioSession session; + protected final EzySocketStreamQueue streamQueue; + protected final EzySessionTicketsQueue sessionTicketsQueue; + protected final EzySocketDisconnectionQueue disconnectionQueue; + protected final EzySessionTicketsRequestQueues sessionTicketsRequestQueues; + + public EzyAbstractHandlerGroup(Builder builder) { + this.session = builder.session; + this.sessionCount = builder.sessionCount; + this.sessionStats = builder.sessionStats; + this.networkStats = builder.networkStats; + this.statsThreadPool = builder.statsThreadPool; + this.streamQueue = builder.streamQueue; + this.streamingEnable = builder.isStreamingEnable(); + this.disconnectionQueue = builder.disconnectionQueue; + this.sessionTicketsQueue = builder.sessionTicketsQueue; + this.sessionTicketsRequestQueues = builder.sessionTicketsRequestQueues; - this.channel = session.getChannel(); - - this.decoder = newDecoder(builder.decoder); - this.handler = newDataHandler(builder); + this.channel = session.getChannel(); + + this.decoder = newDecoder(builder.decoder); + this.handler = newDataHandler(builder); - ((EzyAbstractSession)session).setDisconnectionQueue(disconnectionQueue); - ((EzyAbstractSession)session).setSessionTicketsQueue(sessionTicketsQueue); - ((EzyAbstractSession)session).setDroppedPackets(this); - ((EzyAbstractSession)session).setImmediateDeliver(this); - sessionStats.addSessions(1); - sessionStats.setCurrentSessions(sessionCount.incrementAndGet()); - } - - protected abstract D newDecoder(Object decoder); - - private EzyNioDataHandler newDataHandler(Builder builder) { - EzySimpleNioDataHandler handler = new EzySimpleNioDataHandler( - builder.serverContext, - builder.session); - return handler; - } - - public final void enqueueDisconnection(EzyConstant reason) { - session.disconnect(reason); - } - - public final void fireChannelInactive() { - fireChannelInactive(EzyDisconnectReason.UNKNOWN); - } - - public final void fireChannelInactive(EzyConstant reason) { - try { - handler.channelInactive(reason); - } - catch(Exception e) { - logger.error("handler inactive error", e); - } - finally { - sessionStats.setCurrentSessions(sessionCount.decrementAndGet()); - } - } - - public final void fireExceptionCaught(Throwable throwable) { - try { - handler.exceptionCaught(throwable); - } - catch(Exception e) { - fireChannelInactive(EzyDisconnectReason.SERVER_ERROR); - } - } - - public final void firePacketSend(EzyPacket packet, Object writeBuffer) throws Exception { - executeSendingPacket(packet, writeBuffer); - } - - public final void fireChannelRead(EzyCommand cmd, EzyArray msg) throws Exception { - handler.channelRead(cmd, msg); - } - - public void fireStreamBytesReceived(byte[] bytes) throws Exception { - handler.streamingReceived(bytes); - } - - @Override - public final void sendPacketNow(EzyPacket packet) { - try { - sendPacketNow0(packet); - } - finally { - packet.release(); - } - } - - protected void sendPacketNow0(EzyPacket packet) { - executeSendingPacket(packet, null); - } - - @Override - public void addDroppedPacket(EzyPacket packet) { - networkStats.addDroppedOutPackets(1); - networkStats.addDroppedOutBytes(packet.getSize()); - } - - protected final void handleReceivedData(Object data, int dataSize) { - boolean hasMaxRequestPerSecond = session.addReceviedRequests(1); - if(hasMaxRequestPerSecond) { - handler.processMaxRequestPerSecond(); - networkStats.addDroppedInPackets(1); - networkStats.addDroppedInBytes(dataSize); - logger.debug("request queue of session: {} is full, drop incomming request", session); - return; - } - if(!session.isActivated()) { - logger.debug("session: {} maybe destroyed, drop incomming request", session); - return; - } - EzySocketRequest request = newSocketRequest(data); - boolean success = sessionTicketsRequestQueues.addRequest(request); - if(!success) { - networkStats.addDroppedInPackets(1); - networkStats.addDroppedInBytes(dataSize); - logger.info("request queue is full, drop incomming request"); - } - } - - private EzySocketRequest newSocketRequest(Object data) { - return new EzySimpleSocketRequest(session, (EzyArray) data); - } - - protected final void executeSendingPacket(EzyPacket packet, Object writeBuffer) { - try { - EzyChannel channel = session.getChannel(); - if(canWriteBytes(channel)) { - int writeBytes = 0; - if(packet.getTransportType() == EzyTransportType.TCP) - writeBytes = writePacketToSocket(packet, writeBuffer); - else - writeBytes = writeUdpPacketToSocket(packet, writeBuffer); - executeAddWrittenBytes(writeBytes); - } - } - catch(Exception e) { - int packetSize = packet.getSize(); - networkStats.addWriteErrorPackets(1); - networkStats.addWriteErrorBytes(packetSize); - logger.warn("can't send {} bytes to session: {}, error: {}({})", packetSize, session, e.getClass().getName(), e.getMessage()); - } - } - - protected int writePacketToSocket(EzyPacket packet, Object writeBuffer) throws Exception { - try { - Object bytes = packet.getData(); - int writeBytes = channel.write(bytes, packet.isBinary()); - packet.release(); - return writeBytes; - } - finally { - packet.release(); - } - } - - protected int writeUdpPacketToSocket(EzyPacket packet, Object writeBuffer) throws Exception { - try { - EzyDatagramChannelPool udpChannelPool = session.getDatagramChannelPool(); - if(udpChannelPool == null) - return 0; - SocketAddress clientAddress = session.getUdpClientAddress(); - if(clientAddress == null) - return 0; - byte[] bytes = getBytesToWrite(packet); - int bytesToWrite = bytes.length; - ByteBuffer buffer = getWriteBuffer((ByteBuffer)writeBuffer, bytesToWrite); - buffer.clear(); - buffer.put(bytes); - buffer.flip(); - DatagramChannel channel = udpChannelPool.getChannel(); - int writtenByes = channel.send(buffer, clientAddress); - return writtenByes; - } - finally { - packet.release(); - } - } - - protected byte[] getBytesToWrite(EzyPacket packet) { - return (byte[])packet.getData(); - } - - protected ByteBuffer getWriteBuffer(ByteBuffer fixed, int bytesToWrite) { - return bytesToWrite > fixed.capacity() ? ByteBuffer.allocate(bytesToWrite) : fixed; - } - - private boolean canWriteBytes(EzyChannel channel) { - if(channel == null) - return false; - if(channel.isConnected()) - return true; - return false; - } - - protected final void executeAddReadBytes(int bytes) { - statsThreadPool.execute(() -> addReadBytes(bytes)); - } - - private void executeAddWrittenBytes(int bytes) { - statsThreadPool.execute(() -> addWrittenBytes(bytes)); - } - - private void addReadBytes(int count) { - session.addReadBytes(count); - networkStats.addReadBytes(count); - networkStats.addReadPackets(1); - } - - private void addWrittenBytes(int count) { - session.addWrittenBytes(count); - networkStats.addWrittenBytes(count); - networkStats.addWrittenPackets(1); - } + ((EzyAbstractSession)session).setDisconnectionQueue(disconnectionQueue); + ((EzyAbstractSession)session).setSessionTicketsQueue(sessionTicketsQueue); + ((EzyAbstractSession)session).setDroppedPackets(this); + ((EzyAbstractSession)session).setImmediateDeliver(this); + sessionStats.addSessions(1); + sessionStats.setCurrentSessions(sessionCount.incrementAndGet()); + } + + protected abstract D newDecoder(Object decoder); + + private EzyNioDataHandler newDataHandler(Builder builder) { + EzySimpleNioDataHandler handler = new EzySimpleNioDataHandler( + builder.serverContext, + builder.session); + return handler; + } + + public final void enqueueDisconnection(EzyConstant reason) { + session.disconnect(reason); + } + + public final void fireChannelInactive() { + fireChannelInactive(EzyDisconnectReason.UNKNOWN); + } + + public final void fireChannelInactive(EzyConstant reason) { + try { + handler.channelInactive(reason); + } + catch(Exception e) { + logger.error("handler inactive error", e); + } + finally { + sessionStats.setCurrentSessions(sessionCount.decrementAndGet()); + } + } + + public final void fireExceptionCaught(Throwable throwable) { + try { + handler.exceptionCaught(throwable); + } + catch(Exception e) { + fireChannelInactive(EzyDisconnectReason.SERVER_ERROR); + } + } + + public final void firePacketSend(EzyPacket packet, Object writeBuffer) throws Exception { + executeSendingPacket(packet, writeBuffer); + } + + public final void fireChannelRead(EzyCommand cmd, EzyArray msg) throws Exception { + handler.channelRead(cmd, msg); + } + + public void fireStreamBytesReceived(byte[] bytes) throws Exception { + handler.streamingReceived(bytes); + } + + @Override + public final void sendPacketNow(EzyPacket packet) { + try { + sendPacketNow0(packet); + } + finally { + packet.release(); + } + } + + protected void sendPacketNow0(EzyPacket packet) { + executeSendingPacket(packet, null); + } + + @Override + public void addDroppedPacket(EzyPacket packet) { + networkStats.addDroppedOutPackets(1); + networkStats.addDroppedOutBytes(packet.getSize()); + } + + protected final void handleReceivedData(Object data, int dataSize) { + boolean hasMaxRequestPerSecond = session.addReceviedRequests(1); + if(hasMaxRequestPerSecond) { + handler.processMaxRequestPerSecond(); + networkStats.addDroppedInPackets(1); + networkStats.addDroppedInBytes(dataSize); + logger.debug("request queue of session: {} is full, drop incomming request", session); + return; + } + if(!session.isActivated()) { + logger.debug("session: {} maybe destroyed, drop incomming request", session); + return; + } + EzySocketRequest request = newSocketRequest(data); + boolean success = sessionTicketsRequestQueues.addRequest(request); + if(!success) { + networkStats.addDroppedInPackets(1); + networkStats.addDroppedInBytes(dataSize); + logger.info("request queue is full, drop incomming request"); + } + } + + private EzySocketRequest newSocketRequest(Object data) { + return new EzySimpleSocketRequest(session, (EzyArray) data); + } + + protected final void executeSendingPacket(EzyPacket packet, Object writeBuffer) { + try { + EzyChannel channel = session.getChannel(); + if(canWriteBytes(channel)) { + int writeBytes = 0; + if(packet.getTransportType() == EzyTransportType.TCP) + writeBytes = writePacketToSocket(packet, writeBuffer); + else + writeBytes = writeUdpPacketToSocket(packet, writeBuffer); + executeAddWrittenBytes(writeBytes); + } + } + catch(Exception e) { + int packetSize = packet.getSize(); + networkStats.addWriteErrorPackets(1); + networkStats.addWriteErrorBytes(packetSize); + logger.warn("can't send {} bytes to session: {}, error: {}({})", packetSize, session, e.getClass().getName(), e.getMessage()); + } + } + + protected int writePacketToSocket(EzyPacket packet, Object writeBuffer) throws Exception { + try { + Object bytes = packet.getData(); + int writeBytes = channel.write(bytes, packet.isBinary()); + packet.release(); + return writeBytes; + } + finally { + packet.release(); + } + } + + protected int writeUdpPacketToSocket(EzyPacket packet, Object writeBuffer) throws Exception { + try { + EzyDatagramChannelPool udpChannelPool = session.getDatagramChannelPool(); + if(udpChannelPool == null) + return 0; + SocketAddress clientAddress = session.getUdpClientAddress(); + if(clientAddress == null) + return 0; + byte[] bytes = getBytesToWrite(packet); + int bytesToWrite = bytes.length; + ByteBuffer buffer = getWriteBuffer((ByteBuffer)writeBuffer, bytesToWrite); + buffer.clear(); + buffer.put(bytes); + buffer.flip(); + DatagramChannel channel = udpChannelPool.getChannel(); + int writtenByes = channel.send(buffer, clientAddress); + return writtenByes; + } + finally { + packet.release(); + } + } + + protected byte[] getBytesToWrite(EzyPacket packet) { + return (byte[])packet.getData(); + } + + protected ByteBuffer getWriteBuffer(ByteBuffer fixed, int bytesToWrite) { + return bytesToWrite > fixed.capacity() ? ByteBuffer.allocate(bytesToWrite) : fixed; + } + + private boolean canWriteBytes(EzyChannel channel) { + if(channel == null) + return false; + if(channel.isConnected()) + return true; + return false; + } + + protected final void executeAddReadBytes(int bytes) { + statsThreadPool.execute(() -> addReadBytes(bytes)); + } + + private void executeAddWrittenBytes(int bytes) { + statsThreadPool.execute(() -> addWrittenBytes(bytes)); + } + + private void addReadBytes(int count) { + session.addReadBytes(count); + networkStats.addReadBytes(count); + networkStats.addReadPackets(1); + } + + private void addWrittenBytes(int count) { + session.addWrittenBytes(count); + networkStats.addWrittenBytes(count); + networkStats.addWrittenPackets(1); + } - public EzyNioSession getSession() { - return session; - } - - @Override - public void destroy() { - processWithLogException(() -> decoder.destroy()); - processWithLogException(() -> handler.destroy()); - } - - public static abstract class Builder implements EzyBuilder { + public EzyNioSession getSession() { + return session; + } + + @Override + public void destroy() { + processWithLogException(() -> decoder.destroy()); + processWithLogException(() -> handler.destroy()); + } + + public static abstract class Builder implements EzyBuilder { - protected AtomicInteger sessionCount; - protected EzySessionStats sessionStats; - protected EzyNetworkStats networkStats; - - protected ExecutorService statsThreadPool; - - protected Object decoder; - protected EzyNioSession session; - protected EzyServerContext serverContext; - protected EzySocketStreamQueue streamQueue; - protected EzySessionTicketsQueue sessionTicketsQueue; - protected EzySocketDisconnectionQueue disconnectionQueue; - protected EzySessionTicketsRequestQueues sessionTicketsRequestQueues; - - public Builder decoder(Object decoder) { - this.decoder = decoder; - return this; - } - - public Builder session(EzyNioSession session) { - this.session = session; - return this; - } - - public Builder sessionCount(AtomicInteger sessionCount) { - this.sessionCount = sessionCount; - return this; - } - - public Builder sessionStats(EzySessionStats sessionStats) { - this.sessionStats = sessionStats; - return this; - } - - public Builder networkStats(EzyNetworkStats networkStats) { - this.networkStats = networkStats; - return this; - } - - public Builder statsThreadPool(ExecutorService statsThreadPool) { - this.statsThreadPool = statsThreadPool; - return this; - } - - public Builder serverContext(EzyServerContext serverContext) { - this.serverContext = serverContext; - return this; - } - - public Builder streamQueue(EzySocketStreamQueue streamQueue) { - this.streamQueue = streamQueue; - return this; - } - - public Builder sessionTicketsQueue(EzySessionTicketsQueue queue) { - this.sessionTicketsQueue = queue; - return this; - } - - public Builder disconnectionQueue(EzySocketDisconnectionQueue disconnectionQueue) { - this.disconnectionQueue = disconnectionQueue; - return this; - } - - public Builder sessionTicketsRequestQueues(EzySessionTicketsRequestQueues sessionTicketsRequestQueues) { - this.sessionTicketsRequestQueues = sessionTicketsRequestQueues; - return this; - } - - protected boolean isStreamingEnable() { - return serverContext.getServer().getSettings().getStreaming().isEnable(); - } - } - + protected AtomicInteger sessionCount; + protected EzySessionStats sessionStats; + protected EzyNetworkStats networkStats; + + protected ExecutorService statsThreadPool; + + protected Object decoder; + protected EzyNioSession session; + protected EzyServerContext serverContext; + protected EzySocketStreamQueue streamQueue; + protected EzySessionTicketsQueue sessionTicketsQueue; + protected EzySocketDisconnectionQueue disconnectionQueue; + protected EzySessionTicketsRequestQueues sessionTicketsRequestQueues; + + public Builder decoder(Object decoder) { + this.decoder = decoder; + return this; + } + + public Builder session(EzyNioSession session) { + this.session = session; + return this; + } + + public Builder sessionCount(AtomicInteger sessionCount) { + this.sessionCount = sessionCount; + return this; + } + + public Builder sessionStats(EzySessionStats sessionStats) { + this.sessionStats = sessionStats; + return this; + } + + public Builder networkStats(EzyNetworkStats networkStats) { + this.networkStats = networkStats; + return this; + } + + public Builder statsThreadPool(ExecutorService statsThreadPool) { + this.statsThreadPool = statsThreadPool; + return this; + } + + public Builder serverContext(EzyServerContext serverContext) { + this.serverContext = serverContext; + return this; + } + + public Builder streamQueue(EzySocketStreamQueue streamQueue) { + this.streamQueue = streamQueue; + return this; + } + + public Builder sessionTicketsQueue(EzySessionTicketsQueue queue) { + this.sessionTicketsQueue = queue; + return this; + } + + public Builder disconnectionQueue(EzySocketDisconnectionQueue disconnectionQueue) { + this.disconnectionQueue = disconnectionQueue; + return this; + } + + public Builder sessionTicketsRequestQueues(EzySessionTicketsRequestQueues sessionTicketsRequestQueues) { + this.sessionTicketsRequestQueues = sessionTicketsRequestQueues; + return this; + } + + protected boolean isStreamingEnable() { + return serverContext.getServer().getSettings().getStreaming().isEnable(); + } + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyHandlerGroup.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyHandlerGroup.java index 6757c368c..e8bd4ae54 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyHandlerGroup.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyHandlerGroup.java @@ -7,16 +7,16 @@ import com.tvd12.ezyfoxserver.socket.EzySocketWriterGroup; public interface EzyHandlerGroup extends - EzySocketDataHandlerGroup, - EzySocketWriterGroup, - EzyDestroyable { - - void enqueueDisconnection(EzyConstant reason); + EzySocketDataHandlerGroup, + EzySocketWriterGroup, + EzyDestroyable { + + void enqueueDisconnection(EzyConstant reason); + + void fireExceptionCaught(Throwable throwable); + + default void enqueueDisconnection() { + enqueueDisconnection(EzyDisconnectReason.UNKNOWN); + } - void fireExceptionCaught(Throwable throwable); - - default void enqueueDisconnection() { - enqueueDisconnection(EzyDisconnectReason.UNKNOWN); - } - } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataHandler.java index 7f731fd68..fec9e8d20 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataHandler.java @@ -5,8 +5,8 @@ public interface EzyNioDataHandler extends EzySocketDataHandler { - void channelInactive(EzyConstant disconnectReason); - + void channelInactive(EzyConstant disconnectReason); + void exceptionCaught(Throwable throwable) throws Exception; - + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioExceptionHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioExceptionHandler.java index c64766f5b..bbf2e463d 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioExceptionHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioExceptionHandler.java @@ -2,6 +2,6 @@ public interface EzyNioExceptionHandler { - - + + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioHandlerGroup.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioHandlerGroup.java index 0834e35f2..885195dba 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioHandlerGroup.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioHandlerGroup.java @@ -5,10 +5,10 @@ public interface EzyNioHandlerGroup extends EzyHandlerGroup { - void fireBytesReceived(byte[] bytes) throws Exception; - - void fireMessageReceived(EzyMessage message) throws Exception; - - EzyNioSession getSession(); - + void fireBytesReceived(byte[] bytes) throws Exception; + + void fireMessageReceived(EzyMessage message) throws Exception; + + EzyNioSession getSession(); + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioUdpDataHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioUdpDataHandler.java index b9cb0fc02..dc386fbd8 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioUdpDataHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioUdpDataHandler.java @@ -4,6 +4,6 @@ public interface EzyNioUdpDataHandler { - void fireUdpPacketReceived(EzyUdpReceivedPacket packet) throws Exception; - + void fireUdpPacketReceived(EzyUdpReceivedPacket packet) throws Exception; + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataHandler.java index fb1ebe2e3..d251a5a9f 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataHandler.java @@ -7,16 +7,16 @@ import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; public class EzySimpleNioDataHandler - extends EzySimpleDataHandler - implements EzyNioDataHandler { - - public EzySimpleNioDataHandler(EzyServerContext ctx, EzyNioSession session) { - super(ctx, session); - } - - @Override - public void channelRead(EzyCommand cmd, EzyArray msg) throws Exception { - dataReceived(cmd, msg); + extends EzySimpleDataHandler + implements EzyNioDataHandler { + + public EzySimpleNioDataHandler(EzyServerContext ctx, EzyNioSession session) { + super(ctx, session); + } + + @Override + public void channelRead(EzyCommand cmd, EzyArray msg) throws Exception { + dataReceived(cmd, msg); } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioHandlerGroup.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioHandlerGroup.java index 16881c42f..cf695e180 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioHandlerGroup.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioHandlerGroup.java @@ -14,123 +14,123 @@ import com.tvd12.ezyfoxserver.socket.EzySocketStream; public class EzySimpleNioHandlerGroup - extends EzyAbstractHandlerGroup - implements EzyNioHandlerGroup { - - private final EzyCallback decodeBytesCallback; - - public EzySimpleNioHandlerGroup(Builder builder) { - super(builder); - this.decodeBytesCallback = m -> this.executeHandleReceivedMessage(m); - } - - @Override - protected EzyMessageDataDecoder newDecoder(Object decoder) { - return new EzySimpleMessageDataDecoder((EzyByteToObjectDecoder)decoder); - } - - @Override - public void fireBytesReceived(byte[] bytes) throws Exception { - handleReceivedBytes(bytes); - } - - @Override - public void fireMessageReceived(EzyMessage message) throws Exception { - handleReceivedMesssage(message); - } - - private void handleReceivedBytes(byte[] bytes) { - try { - decoder.decode(bytes, decodeBytesCallback); - } - catch(Exception throwable) { - fireExceptionCaught(throwable); - } - } - - private void executeHandleReceivedMessage(EzyMessage message) { - handleReceivedMesssage(message); - } - - private void handleReceivedMesssage(EzyMessage message) { - try { - EzyMessageHeader header = message.getHeader(); - if(header.isRawBytes()) { - boolean sessionStreamingEnable = session.isStreamingEnable(); - if(!streamingEnable || !sessionStreamingEnable) { - return; - } - byte[] rawBytes = message.getContent(); - EzySocketStream stream = new EzySimpleSocketStream(session, rawBytes); - streamQueue.add(stream); - } - else { - Object data = decodeMessage(message); - int dataSize = message.getByteCount(); - handleReceivedData(data, dataSize); - } - } - catch (Exception e) { - fireExceptionCaught(e); - } - finally { - executeAddReadBytes(message.getByteCount()); - } - } - - private Object decodeMessage(EzyMessage message) throws Exception { - Object answer = decoder.decode(message, session.getSessionKey()); - return answer; - } - - @Override - protected void sendPacketNow0(EzyPacket packet) { - ByteBuffer writeBuffer = ByteBuffer.allocate(packet.getSize()); - executeSendingPacket(packet, writeBuffer); - } - - @Override - protected int writePacketToSocket(EzyPacket packet, Object writeBuffer) throws Exception { - byte[] bytes = getBytesToWrite(packet); - int bytesToWrite = bytes.length; - ByteBuffer buffer = getWriteBuffer((ByteBuffer)writeBuffer, bytesToWrite); - buffer.clear(); - buffer.put(bytes); - buffer.flip(); - int bytesWritten = channel.write(buffer, packet.isBinary()); - if (bytesWritten < bytesToWrite) { - byte[] remainBytes = getPacketFragment(buffer); - packet.setFragment(remainBytes); - SelectionKey selectionKey = session.getSelectionKey(); - if(selectionKey != null && selectionKey.isValid()) { - selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); - } - else { - logger.warn("selection key invalid, wrriten bytes: {}, session: {}", bytesWritten, session); - } - } - else { - packet.release(); - } - return bytesWritten; - } - - private byte[] getPacketFragment(ByteBuffer buffer) { - byte[] remainBytes = new byte[buffer.remaining()]; - buffer.get(remainBytes); - return remainBytes; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyAbstractHandlerGroup.Builder { - - @Override - public EzyNioHandlerGroup build() { - return new EzySimpleNioHandlerGroup(this); - } - } + extends EzyAbstractHandlerGroup + implements EzyNioHandlerGroup { + + private final EzyCallback decodeBytesCallback; + + public EzySimpleNioHandlerGroup(Builder builder) { + super(builder); + this.decodeBytesCallback = m -> this.executeHandleReceivedMessage(m); + } + + @Override + protected EzyMessageDataDecoder newDecoder(Object decoder) { + return new EzySimpleMessageDataDecoder((EzyByteToObjectDecoder)decoder); + } + + @Override + public void fireBytesReceived(byte[] bytes) throws Exception { + handleReceivedBytes(bytes); + } + + @Override + public void fireMessageReceived(EzyMessage message) throws Exception { + handleReceivedMesssage(message); + } + + private void handleReceivedBytes(byte[] bytes) { + try { + decoder.decode(bytes, decodeBytesCallback); + } + catch(Exception throwable) { + fireExceptionCaught(throwable); + } + } + + private void executeHandleReceivedMessage(EzyMessage message) { + handleReceivedMesssage(message); + } + + private void handleReceivedMesssage(EzyMessage message) { + try { + EzyMessageHeader header = message.getHeader(); + if(header.isRawBytes()) { + boolean sessionStreamingEnable = session.isStreamingEnable(); + if(!streamingEnable || !sessionStreamingEnable) { + return; + } + byte[] rawBytes = message.getContent(); + EzySocketStream stream = new EzySimpleSocketStream(session, rawBytes); + streamQueue.add(stream); + } + else { + Object data = decodeMessage(message); + int dataSize = message.getByteCount(); + handleReceivedData(data, dataSize); + } + } + catch (Exception e) { + fireExceptionCaught(e); + } + finally { + executeAddReadBytes(message.getByteCount()); + } + } + + private Object decodeMessage(EzyMessage message) throws Exception { + Object answer = decoder.decode(message, session.getSessionKey()); + return answer; + } + + @Override + protected void sendPacketNow0(EzyPacket packet) { + ByteBuffer writeBuffer = ByteBuffer.allocate(packet.getSize()); + executeSendingPacket(packet, writeBuffer); + } + + @Override + protected int writePacketToSocket(EzyPacket packet, Object writeBuffer) throws Exception { + byte[] bytes = getBytesToWrite(packet); + int bytesToWrite = bytes.length; + ByteBuffer buffer = getWriteBuffer((ByteBuffer)writeBuffer, bytesToWrite); + buffer.clear(); + buffer.put(bytes); + buffer.flip(); + int bytesWritten = channel.write(buffer, packet.isBinary()); + if (bytesWritten < bytesToWrite) { + byte[] remainBytes = getPacketFragment(buffer); + packet.setFragment(remainBytes); + SelectionKey selectionKey = session.getSelectionKey(); + if(selectionKey != null && selectionKey.isValid()) { + selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); + } + else { + logger.warn("selection key invalid, wrriten bytes: {}, session: {}", bytesWritten, session); + } + } + else { + packet.release(); + } + return bytesWritten; + } + + private byte[] getPacketFragment(ByteBuffer buffer) { + byte[] remainBytes = new byte[buffer.remaining()]; + buffer.get(remainBytes); + return remainBytes; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyAbstractHandlerGroup.Builder { + + @Override + public EzyNioHandlerGroup build() { + return new EzySimpleNioHandlerGroup(this); + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioUdpDataHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioUdpDataHandler.java index 14ffe3e7f..9bc5e7f45 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioUdpDataHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioUdpDataHandler.java @@ -39,118 +39,118 @@ import lombok.Setter; @SuppressWarnings("rawtypes") -public class EzySimpleNioUdpDataHandler - extends EzyLoggable - implements - EzyNioUdpDataHandler, - EzySessionManagerAware, - EzyHandlerGroupManagerAware, - EzyDatagramChannelPoolAware, - EzyDestroyable { +public class EzySimpleNioUdpDataHandler + extends EzyLoggable + implements + EzyNioUdpDataHandler, + EzySessionManagerAware, + EzyHandlerGroupManagerAware, + EzyDatagramChannelPoolAware, + EzyDestroyable { + + @Setter + protected EzyResponseApi responseApi; + @Setter + protected EzySessionManager sessionManager; + @Setter + protected EzyHandlerGroupManager handlerGroupManager; + @Setter + protected EzyDatagramChannelPool datagramChannelPool; + @Setter + protected EzySocketDataReceiver socketDataReceiver; + + protected final ExecutorService executorService; + + public EzySimpleNioUdpDataHandler(int threadPoolSize) { + this.executorService = + EzyExecutors.newFixedThreadPool(threadPoolSize, "udp-data-handler"); + } + + @Override + public void fireUdpPacketReceived(EzyUdpReceivedPacket packet) throws Exception { + this.executorService.execute(() -> handleReceivedUdpPacket(packet)); + } + + protected void handleReceivedUdpPacket(EzyUdpReceivedPacket packet) { + try { + EzyMessage message = EzyMessageReaders.bytesToMessage(packet.getBytes()); + if(message == null) + return; + InetSocketAddress udpAddress = packet.getAddress(); + Object socketChannel = handlerGroupManager.getSocketChannel(udpAddress); + if(socketChannel != null) { + SocketAddress tcpAddress = (socketChannel instanceof SocketChannel) + ? ((SocketChannel)socketChannel).getRemoteAddress() + : ((Session)socketChannel).getRemoteAddress(); + if(isOneClient(tcpAddress, udpAddress)) + socketDataReceiver.udpReceive(socketChannel, message); + } + else { + EzyMessageHeader header = message.getHeader(); + if(header.isUdpHandshake()) + handleUdpHandshake(packet.getChannel(), udpAddress, message); + } + } + catch (Exception e) { + logger.warn("handle received udp package: {} error: {}({})", packet, e.getClass().getName(), e.getMessage()); + } + } + + protected void handleUdpHandshake( + DatagramChannel channel, + InetSocketAddress address, EzyMessage message) throws Exception { + byte[] content = message.getContent(); + if(content.length < 11) + return; + byte[] sessionIdBytes = EzyBytes.copy(content, 0, 8); + long sessionId = EzyLongs.bin2long(sessionIdBytes); + byte[] tokenSizeBytes = EzyBytes.copy(content, 8, 2); + int tokenSize = EzyInts.bin2int(tokenSizeBytes); + if(tokenSize > 512) + return; + byte[] tokenBytes = EzyBytes.copy(content, 10, tokenSize); + EzySession session = sessionManager.getSession(sessionId); + if(session == null) + return; + int responseCode = 498; + String token = new String(tokenBytes); + String sessionToken = session.getToken(); + if(sessionToken.equals(token)) { + responseCode = 200; + SocketAddress oldUdpAddress = session.getUdpClientAddress(); + handlerGroupManager.unmapHandlerGroup(oldUdpAddress); + handlerGroupManager.mapSocketChannel(address, session); + ((EzyDatagramChannelAware)session).setDatagramChannel(channel); + ((EzyUdpClientAddressAware)session).setUdpClientAddress(address); + ((EzyDatagramChannelPoolAware)session).setDatagramChannelPool(datagramChannelPool); + } + response(session, responseCode); + } + + protected void response(EzySession recipient, int responseCode) throws Exception { + EzyArray responseData = EzyEntityFactory.newArray(); + responseData.add(responseCode); + EzyArray responseCommand = EzyEntityFactory.newArray(); + responseCommand.add(EzyCommand.UDP_HANDSHAKE.getId()); + responseCommand.add(responseData); + EzySimplePackage response = new EzySimplePackage(); + response.addRecipient(recipient); + response.setTransportType(EzyTransportType.UDP); + response.setData(responseCommand); + responseApi.response(response); + logger.debug("response udp handshake to: {}, code: {}", recipient, responseCode); + } + + protected boolean isOneClient(SocketAddress tcpAddress, SocketAddress udpAddress) { + String tcpHost = EzySocketAddresses.getHost(tcpAddress); + String udpHost = EzySocketAddresses.getHost(udpAddress); + boolean answer = tcpHost.equals(udpHost); + return answer; + } + + @Override + public void destroy() { + this.executorService.shutdownNow(); + } - @Setter - protected EzyResponseApi responseApi; - @Setter - protected EzySessionManager sessionManager; - @Setter - protected EzyHandlerGroupManager handlerGroupManager; - @Setter - protected EzyDatagramChannelPool datagramChannelPool; - @Setter - protected EzySocketDataReceiver socketDataReceiver; - - protected final ExecutorService executorService; - - public EzySimpleNioUdpDataHandler(int threadPoolSize) { - this.executorService = - EzyExecutors.newFixedThreadPool(threadPoolSize, "udp-data-handler"); - } - - @Override - public void fireUdpPacketReceived(EzyUdpReceivedPacket packet) throws Exception { - this.executorService.execute(() -> handleReceivedUdpPacket(packet)); - } - - protected void handleReceivedUdpPacket(EzyUdpReceivedPacket packet) { - try { - EzyMessage message = EzyMessageReaders.bytesToMessage(packet.getBytes()); - if(message == null) - return; - InetSocketAddress udpAddress = packet.getAddress(); - Object socketChannel = handlerGroupManager.getSocketChannel(udpAddress); - if(socketChannel != null) { - SocketAddress tcpAddress = (socketChannel instanceof SocketChannel) - ? ((SocketChannel)socketChannel).getRemoteAddress() - : ((Session)socketChannel).getRemoteAddress(); - if(isOneClient(tcpAddress, udpAddress)) - socketDataReceiver.udpReceive(socketChannel, message); - } - else { - EzyMessageHeader header = message.getHeader(); - if(header.isUdpHandshake()) - handleUdpHandshake(packet.getChannel(), udpAddress, message); - } - } - catch (Exception e) { - logger.warn("handle received udp package: {} error: {}({})", packet, e.getClass().getName(), e.getMessage()); - } - } - - protected void handleUdpHandshake( - DatagramChannel channel, - InetSocketAddress address, EzyMessage message) throws Exception { - byte[] content = message.getContent(); - if(content.length < 11) - return; - byte[] sessionIdBytes = EzyBytes.copy(content, 0, 8); - long sessionId = EzyLongs.bin2long(sessionIdBytes); - byte[] tokenSizeBytes = EzyBytes.copy(content, 8, 2); - int tokenSize = EzyInts.bin2int(tokenSizeBytes); - if(tokenSize > 512) - return; - byte[] tokenBytes = EzyBytes.copy(content, 10, tokenSize); - EzySession session = sessionManager.getSession(sessionId); - if(session == null) - return; - int responseCode = 498; - String token = new String(tokenBytes); - String sessionToken = session.getToken(); - if(sessionToken.equals(token)) { - responseCode = 200; - SocketAddress oldUdpAddress = session.getUdpClientAddress(); - handlerGroupManager.unmapHandlerGroup(oldUdpAddress); - handlerGroupManager.mapSocketChannel(address, session); - ((EzyDatagramChannelAware)session).setDatagramChannel(channel); - ((EzyUdpClientAddressAware)session).setUdpClientAddress(address); - ((EzyDatagramChannelPoolAware)session).setDatagramChannelPool(datagramChannelPool); - } - response(session, responseCode); - } - - protected void response(EzySession recipient, int responseCode) throws Exception { - EzyArray responseData = EzyEntityFactory.newArray(); - responseData.add(responseCode); - EzyArray responseCommand = EzyEntityFactory.newArray(); - responseCommand.add(EzyCommand.UDP_HANDSHAKE.getId()); - responseCommand.add(responseData); - EzySimplePackage response = new EzySimplePackage(); - response.addRecipient(recipient); - response.setTransportType(EzyTransportType.UDP); - response.setData(responseCommand); - responseApi.response(response); - logger.debug("response udp handshake to: {}, code: {}", recipient, responseCode); - } - - protected boolean isOneClient(SocketAddress tcpAddress, SocketAddress udpAddress) { - String tcpHost = EzySocketAddresses.getHost(tcpAddress); - String udpHost = EzySocketAddresses.getHost(udpAddress); - boolean answer = tcpHost.equals(udpHost); - return answer; - } - - @Override - public void destroy() { - this.executorService.shutdownNow(); - } - } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioAcceptableConnectionsHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioAcceptableConnectionsHandler.java index 9713c7b53..83ec38344 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioAcceptableConnectionsHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioAcceptableConnectionsHandler.java @@ -2,6 +2,6 @@ public interface EzyNioAcceptableConnectionsHandler { - void handleAcceptableConnections(); - + void handleAcceptableConnections(); + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptanceLoopHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptanceLoopHandler.java index db9aaec3b..5becd978d 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptanceLoopHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptanceLoopHandler.java @@ -3,10 +3,10 @@ import com.tvd12.ezyfoxserver.socket.EzySocketEventLoopOneHandler; public class EzyNioSocketAcceptanceLoopHandler extends EzySocketEventLoopOneHandler { - - @Override - protected String getThreadName() { - return "socket-acceptor"; - } - + + @Override + protected String getThreadName() { + return "socket-acceptor"; + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptor.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptor.java index 0da2476f0..1bc57de5e 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptor.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketAcceptor.java @@ -20,101 +20,101 @@ import lombok.Setter; public class EzyNioSocketAcceptor - extends EzySocketAbstractEventHandler - implements EzyHandlerGroupManagerAware, EzyNioAcceptableConnectionsHandler { - - @Setter - protected boolean tcpNoDelay; - @Setter - protected Selector ownSelector; - @Setter - protected Selector readSelector; - @Setter - protected List acceptableConnections; - @Setter - protected EzyHandlerGroupManager handlerGroupManager; - - @Override - public void destroy() { - processWithLogException(() -> ownSelector.close()); - } - - @Override - public void handleEvent() { - try { - processReadyKeys(); - } - catch(Exception e) { - logger.info("I/O error at socket-acceptor", e); - } - } - - public void handleAcceptableConnections() { - if(acceptableConnections.isEmpty()) { - return; - } - synchronized (acceptableConnections) { - handleAcceptableConnections0(); - } - } - - private void processReadyKeys() throws Exception { - ownSelector.select(); - - Set readyKeys = ownSelector.selectedKeys(); - Iterator iterator = readyKeys.iterator(); - while(iterator.hasNext()) { - SelectionKey key = iterator.next(); - iterator.remove(); - processReadyKey(key); - } - readSelector.wakeup(); - } - - private void processReadyKey(SelectionKey key) throws Exception { - if(key.isAcceptable()) { - ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); - SocketChannel clientChannel = serverChannel.accept(); - addConnection(clientChannel); - } - } - - private void addConnection(SocketChannel clientChannel) { - synchronized (acceptableConnections) { - acceptableConnections.add(clientChannel); - } - } - - private void handleAcceptableConnections0() { - Iterator iterator = acceptableConnections.iterator(); - while(iterator.hasNext()) { - SocketChannel clientChannel = iterator.next(); - iterator.remove(); - acceptConnection(clientChannel); - } - } - - private void acceptConnection(SocketChannel clientChannel) { - try { - acceptConnection0(clientChannel); - } - catch(Exception e) { - logger.error("can't acception connection: {}", clientChannel, e); - } - } - - private void acceptConnection0(SocketChannel clientChannel) throws Exception { - clientChannel.configureBlocking(false); - clientChannel.socket().setTcpNoDelay(tcpNoDelay); - - EzyChannel channel = new EzyNioSocketChannel(clientChannel); - - EzyNioHandlerGroup handlerGroup = handlerGroupManager - .newHandlerGroup(channel, EzyConnectionType.SOCKET); - EzyNioSession session = handlerGroup.getSession(); - - SelectionKey selectionKey = clientChannel.register(readSelector, SelectionKey.OP_READ); - session.setProperty(EzyNioSession.SELECTION_KEY, selectionKey); - } - + extends EzySocketAbstractEventHandler + implements EzyHandlerGroupManagerAware, EzyNioAcceptableConnectionsHandler { + + @Setter + protected boolean tcpNoDelay; + @Setter + protected Selector ownSelector; + @Setter + protected Selector readSelector; + @Setter + protected List acceptableConnections; + @Setter + protected EzyHandlerGroupManager handlerGroupManager; + + @Override + public void destroy() { + processWithLogException(() -> ownSelector.close()); + } + + @Override + public void handleEvent() { + try { + processReadyKeys(); + } + catch(Exception e) { + logger.info("I/O error at socket-acceptor", e); + } + } + + public void handleAcceptableConnections() { + if(acceptableConnections.isEmpty()) { + return; + } + synchronized (acceptableConnections) { + handleAcceptableConnections0(); + } + } + + private void processReadyKeys() throws Exception { + ownSelector.select(); + + Set readyKeys = ownSelector.selectedKeys(); + Iterator iterator = readyKeys.iterator(); + while(iterator.hasNext()) { + SelectionKey key = iterator.next(); + iterator.remove(); + processReadyKey(key); + } + readSelector.wakeup(); + } + + private void processReadyKey(SelectionKey key) throws Exception { + if(key.isAcceptable()) { + ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); + SocketChannel clientChannel = serverChannel.accept(); + addConnection(clientChannel); + } + } + + private void addConnection(SocketChannel clientChannel) { + synchronized (acceptableConnections) { + acceptableConnections.add(clientChannel); + } + } + + private void handleAcceptableConnections0() { + Iterator iterator = acceptableConnections.iterator(); + while(iterator.hasNext()) { + SocketChannel clientChannel = iterator.next(); + iterator.remove(); + acceptConnection(clientChannel); + } + } + + private void acceptConnection(SocketChannel clientChannel) { + try { + acceptConnection0(clientChannel); + } + catch(Exception e) { + logger.error("can't acception connection: {}", clientChannel, e); + } + } + + private void acceptConnection0(SocketChannel clientChannel) throws Exception { + clientChannel.configureBlocking(false); + clientChannel.socket().setTcpNoDelay(tcpNoDelay); + + EzyChannel channel = new EzyNioSocketChannel(clientChannel); + + EzyNioHandlerGroup handlerGroup = handlerGroupManager + .newHandlerGroup(channel, EzyConnectionType.SOCKET); + EzyNioSession session = handlerGroup.getSession(); + + SelectionKey selectionKey = clientChannel.register(readSelector, SelectionKey.OP_READ); + session.setProperty(EzyNioSession.SELECTION_KEY, selectionKey); + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketChannel.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketChannel.java index b9e62de90..4bf610a86 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketChannel.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketChannel.java @@ -15,47 +15,47 @@ @Getter public class EzyNioSocketChannel implements EzyChannel { - private final SocketChannel channel; - private final SocketAddress serverAddress; - private final SocketAddress clientAddress; - - public EzyNioSocketChannel(SocketChannel channel) { - this.channel = channel; - this.serverAddress = returnWithException(() -> channel.getLocalAddress()); - this.clientAddress = returnWithException(() -> channel.getRemoteAddress()); - } - - @Override - public int write(Object data, boolean binary) throws Exception { - int writtenBytes = channel.write((ByteBuffer)data); - return writtenBytes; - } - - @SuppressWarnings("unchecked") - @Override - public SocketChannel getConnection() { - return channel; - } - - @Override - public EzyConnectionType getConnectionType() { - return EzyConnectionType.SOCKET; - } - - @Override - public boolean isConnected() { - boolean connected = channel.isConnected(); - return connected; - } - - @Override - public void disconnect() { - processWithLogException(() -> channel.finishConnect()); - } - - @Override - public void close() { - processWithLogException(() -> channel.close()); - } - + private final SocketChannel channel; + private final SocketAddress serverAddress; + private final SocketAddress clientAddress; + + public EzyNioSocketChannel(SocketChannel channel) { + this.channel = channel; + this.serverAddress = returnWithException(() -> channel.getLocalAddress()); + this.clientAddress = returnWithException(() -> channel.getRemoteAddress()); + } + + @Override + public int write(Object data, boolean binary) throws Exception { + int writtenBytes = channel.write((ByteBuffer)data); + return writtenBytes; + } + + @SuppressWarnings("unchecked") + @Override + public SocketChannel getConnection() { + return channel; + } + + @Override + public EzyConnectionType getConnectionType() { + return EzyConnectionType.SOCKET; + } + + @Override + public boolean isConnected() { + boolean connected = channel.isConnected(); + return connected; + } + + @Override + public void disconnect() { + processWithLogException(() -> channel.finishConnect()); + } + + @Override + public void close() { + processWithLogException(() -> channel.close()); + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReader.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReader.java index b31201170..cfb15f16e 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReader.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReader.java @@ -14,68 +14,68 @@ public class EzyNioSocketReader extends EzySocketAbstractEventHandler { - @Setter - protected Selector ownSelector; - @Setter - protected EzySocketDataReceiver socketDataReceiver; - @Setter - protected EzyNioAcceptableConnectionsHandler acceptableConnectionsHandler; + @Setter + protected Selector ownSelector; + @Setter + protected EzySocketDataReceiver socketDataReceiver; + @Setter + protected EzyNioAcceptableConnectionsHandler acceptableConnectionsHandler; + + @Override + public void destroy() { + processWithLogException(() -> ownSelector.close()); + } + + @Override + public void handleEvent() { + try { + handleAcceptableConnections(); + processReadyKeys0(); + Thread.sleep(3L); + } + catch(Exception e) { + logger.info("I/O error at socket-reader: {}({})", e.getClass().getName(), e.getMessage()); + } + } + + private void handleAcceptableConnections() { + acceptableConnectionsHandler.handleAcceptableConnections(); + } + + private void processReadyKeys0() throws Exception { + int readyKeyCount = ownSelector.selectNow(); + if(readyKeyCount > 0) { + processReadyKeys(); + } + } + + private void processReadyKeys() throws Exception { + Set readyKeys = this.ownSelector.selectedKeys(); + Iterator iterator = readyKeys.iterator(); + while(iterator.hasNext()) { + SelectionKey key = iterator.next(); + iterator.remove(); + if(key.isValid()) { + processReadyKey(key); + } + } + } + + private void processReadyKey(SelectionKey key) throws Exception { + if(key.isWritable()) { + processWritableKey(key); + } + if(key.isReadable()) { + processReadableKey(key); + } + } + + private void processWritableKey(SelectionKey key) throws Exception { + key.interestOps(SelectionKey.OP_READ); + } + + private void processReadableKey(SelectionKey key) throws Exception { + socketDataReceiver.tcpReceive((SocketChannel) key.channel()); + } - @Override - public void destroy() { - processWithLogException(() -> ownSelector.close()); - } - - @Override - public void handleEvent() { - try { - handleAcceptableConnections(); - processReadyKeys0(); - Thread.sleep(3L); - } - catch(Exception e) { - logger.info("I/O error at socket-reader: {}({})", e.getClass().getName(), e.getMessage()); - } - } - - private void handleAcceptableConnections() { - acceptableConnectionsHandler.handleAcceptableConnections(); - } - - private void processReadyKeys0() throws Exception { - int readyKeyCount = ownSelector.selectNow(); - if(readyKeyCount > 0) { - processReadyKeys(); - } - } - - private void processReadyKeys() throws Exception { - Set readyKeys = this.ownSelector.selectedKeys(); - Iterator iterator = readyKeys.iterator(); - while(iterator.hasNext()) { - SelectionKey key = iterator.next(); - iterator.remove(); - if(key.isValid()) { - processReadyKey(key); - } - } - } - - private void processReadyKey(SelectionKey key) throws Exception { - if(key.isWritable()) { - processWritableKey(key); - } - if(key.isReadable()) { - processReadableKey(key); - } - } - - private void processWritableKey(SelectionKey key) throws Exception { - key.interestOps(SelectionKey.OP_READ); - } - - private void processReadableKey(SelectionKey key) throws Exception { - socketDataReceiver.tcpReceive((SocketChannel) key.channel()); - } - } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReadingLoopHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReadingLoopHandler.java index 61cb4d9aa..50522f8bb 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReadingLoopHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketReadingLoopHandler.java @@ -3,10 +3,10 @@ import com.tvd12.ezyfoxserver.socket.EzySocketEventLoopOneHandler; public class EzyNioSocketReadingLoopHandler extends EzySocketEventLoopOneHandler { - - @Override - protected String getThreadName() { - return "socket-reader"; - } - + + @Override + protected String getThreadName() { + return "socket-reader"; + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketWriter.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketWriter.java index 396722530..96354e556 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketWriter.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNioSocketWriter.java @@ -6,10 +6,10 @@ public class EzyNioSocketWriter extends EzySocketWriter { - protected ByteBuffer writeBuffer = ByteBuffer.allocate(32768); - - @Override - protected Object getWriteBuffer() { - return writeBuffer; - } + protected ByteBuffer writeBuffer = ByteBuffer.allocate(32768); + + @Override + protected Object getWriteBuffer() { + return writeBuffer; + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketDataReceiver.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketDataReceiver.java index d75c060f3..d01729fee 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketDataReceiver.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketDataReceiver.java @@ -19,179 +19,179 @@ import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; public class EzySocketDataReceiver extends EzyLoggable implements EzyDestroyable { - - protected final int threadPoolSize; - protected final ByteBuffer tcpByteBuffers[]; - protected final ExecutorService[] executorServices; - protected final EzyHandlerGroupManager handlerGroupManager; - - public EzySocketDataReceiver(Builder builder) { - this.threadPoolSize = builder.threadPoolSize; - this.handlerGroupManager = builder.handlerGroupManager; - this.tcpByteBuffers = newTcpByteBuffers(threadPoolSize); - this.executorServices = newExecutorServices(threadPoolSize); - } - - private ByteBuffer[] newTcpByteBuffers(int size) { - ByteBuffer[] answer = new ByteBuffer[size]; - for(int i = 0 ; i < size ; ++i) - answer[i] = ByteBuffer.allocateDirect(getMaxBufferSize()); - return answer; - } - - private ExecutorService[] newExecutorServices(int threadPoolSize) { - ExecutorService[] answer = new ExecutorService[threadPoolSize]; - for(int i = 0 ; i < threadPoolSize ; ++i) - answer[i] = EzyExecutors.newSingleThreadExecutor("socket-data-receiver"); - return answer; - } - - public void tcpReceive(SocketChannel channel) { - int index = Math.abs(channel.hashCode() % threadPoolSize); - ByteBuffer buffer = tcpByteBuffers[index]; - ExecutorService executorService = executorServices[index]; - executorService.execute(() -> tcpReceive0(channel, buffer)); - } - - private void tcpReceive0(SocketChannel channel, ByteBuffer buffer) { - try { - tcpReadBytes(channel, buffer); - } - catch (Exception e) { - logger.info("I/O error at tcp-data-reader (channel: {}): {}({})", channel, e.getClass().getName(), e.getMessage()); - } - } - - private void tcpReadBytes(SocketChannel channel, ByteBuffer buffer) throws Exception { - int readBytes = -1; - Exception exception = null; - try { - buffer.clear(); - readBytes = channel.read(buffer); - } - catch (ClosedChannelException e) { - // do nothing - } - catch (Exception e) { - exception = e; - } - if(readBytes == -1) { - tcpCloseConnection(channel); - } - else if(readBytes > 0) { - processReadBytes(channel, buffer); - } - if(exception != null) - throw exception; - } - - private void processReadBytes(SocketChannel channel, ByteBuffer buffer) throws Exception { - buffer.flip(); - byte[] binary = new byte[buffer.limit()]; - buffer.get(binary); - EzyNioHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(channel); - if(handlerGroup != null) - handlerGroup.fireBytesReceived(binary); - } - - private void tcpCloseConnection(SocketChannel channel) { - EzyHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(channel); - if(handlerGroup != null) - handlerGroup.enqueueDisconnection(); - } - - public void udpReceive(Object socketChannel, EzyMessage message) { - ExecutorService executorService = selectedExecutorService(socketChannel); - executorService.execute(() -> udpReceive0(socketChannel, message)); - } - - private void udpReceive0(Object socketChannel, EzyMessage message) { - try { - EzyNioHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(socketChannel); - if(handlerGroup != null) - handlerGroup.fireMessageReceived(message); - } - catch(Exception e) { - logger.info("I/O error at udp-message-received (channel: {}): {}({})", socketChannel, e.getClass().getName(), e.getMessage()); - } - - } - - public void wsReceive(Session session, String message) { - ExecutorService executorService = selectedExecutorService(session); - executorService.execute(() -> wsReceive0(session, message)); - } - - private void wsReceive0(Session session, String message) { - try { - EzyWsHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(session); - if(handlerGroup != null) - handlerGroup.fireBytesReceived(message); - } - catch(Exception e) { - logger.info("I/O error at ws-message-received (session: {}): {}({})", session, e.getClass().getName(), e.getMessage()); - } - } - - public void wsReceive(Session session, byte[] payload, int offset, int len) { - ExecutorService executorService = selectedExecutorService(session); - executorService.execute(() -> wsReceive0(session, payload, offset, len)); - } - - private void wsReceive0(Session session, byte[] payload, int offset, int len) { - try { - EzyWsHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(session); - if(handlerGroup != null) - handlerGroup.fireBytesReceived(payload, offset, len); - } - catch(Exception e) { - logger.info("I/O error at ws-message-received (session: {}): {}({})", session, e.getClass().getName(), e.getMessage()); - } - } - - public void wsCloseConnection(Session session) { - EzyWsHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(session); - if(handlerGroup != null) - handlerGroup.enqueueDisconnection(); - } - - @Override - public void destroy() { - for(ExecutorService executorService : executorServices) - executorService.shutdownNow(); - } - - private ExecutorService selectedExecutorService(Object channel) { - int index = Math.abs(channel.hashCode() % threadPoolSize); - return executorServices[index]; - } - - private int getMaxBufferSize() { - return EzyCoreConstants.MAX_READ_BUFFER_SIZE; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - protected int threadPoolSize; - protected EzyHandlerGroupManager handlerGroupManager; - - public Builder threadPoolSize(int threadPoolSize) { - this.threadPoolSize = threadPoolSize; - return this; - } - - public Builder handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { - this.handlerGroupManager = handlerGroupManager; - return this; - } - - @Override - public EzySocketDataReceiver build() { - return new EzySocketDataReceiver(this); - } - } - + + protected final int threadPoolSize; + protected final ByteBuffer tcpByteBuffers[]; + protected final ExecutorService[] executorServices; + protected final EzyHandlerGroupManager handlerGroupManager; + + public EzySocketDataReceiver(Builder builder) { + this.threadPoolSize = builder.threadPoolSize; + this.handlerGroupManager = builder.handlerGroupManager; + this.tcpByteBuffers = newTcpByteBuffers(threadPoolSize); + this.executorServices = newExecutorServices(threadPoolSize); + } + + private ByteBuffer[] newTcpByteBuffers(int size) { + ByteBuffer[] answer = new ByteBuffer[size]; + for(int i = 0 ; i < size ; ++i) + answer[i] = ByteBuffer.allocateDirect(getMaxBufferSize()); + return answer; + } + + private ExecutorService[] newExecutorServices(int threadPoolSize) { + ExecutorService[] answer = new ExecutorService[threadPoolSize]; + for(int i = 0 ; i < threadPoolSize ; ++i) + answer[i] = EzyExecutors.newSingleThreadExecutor("socket-data-receiver"); + return answer; + } + + public void tcpReceive(SocketChannel channel) { + int index = Math.abs(channel.hashCode() % threadPoolSize); + ByteBuffer buffer = tcpByteBuffers[index]; + ExecutorService executorService = executorServices[index]; + executorService.execute(() -> tcpReceive0(channel, buffer)); + } + + private void tcpReceive0(SocketChannel channel, ByteBuffer buffer) { + try { + tcpReadBytes(channel, buffer); + } + catch (Exception e) { + logger.info("I/O error at tcp-data-reader (channel: {}): {}({})", channel, e.getClass().getName(), e.getMessage()); + } + } + + private void tcpReadBytes(SocketChannel channel, ByteBuffer buffer) throws Exception { + int readBytes = -1; + Exception exception = null; + try { + buffer.clear(); + readBytes = channel.read(buffer); + } + catch (ClosedChannelException e) { + // do nothing + } + catch (Exception e) { + exception = e; + } + if(readBytes == -1) { + tcpCloseConnection(channel); + } + else if(readBytes > 0) { + processReadBytes(channel, buffer); + } + if(exception != null) + throw exception; + } + + private void processReadBytes(SocketChannel channel, ByteBuffer buffer) throws Exception { + buffer.flip(); + byte[] binary = new byte[buffer.limit()]; + buffer.get(binary); + EzyNioHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(channel); + if(handlerGroup != null) + handlerGroup.fireBytesReceived(binary); + } + + private void tcpCloseConnection(SocketChannel channel) { + EzyHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(channel); + if(handlerGroup != null) + handlerGroup.enqueueDisconnection(); + } + + public void udpReceive(Object socketChannel, EzyMessage message) { + ExecutorService executorService = selectedExecutorService(socketChannel); + executorService.execute(() -> udpReceive0(socketChannel, message)); + } + + private void udpReceive0(Object socketChannel, EzyMessage message) { + try { + EzyNioHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(socketChannel); + if(handlerGroup != null) + handlerGroup.fireMessageReceived(message); + } + catch(Exception e) { + logger.info("I/O error at udp-message-received (channel: {}): {}({})", socketChannel, e.getClass().getName(), e.getMessage()); + } + + } + + public void wsReceive(Session session, String message) { + ExecutorService executorService = selectedExecutorService(session); + executorService.execute(() -> wsReceive0(session, message)); + } + + private void wsReceive0(Session session, String message) { + try { + EzyWsHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(session); + if(handlerGroup != null) + handlerGroup.fireBytesReceived(message); + } + catch(Exception e) { + logger.info("I/O error at ws-message-received (session: {}): {}({})", session, e.getClass().getName(), e.getMessage()); + } + } + + public void wsReceive(Session session, byte[] payload, int offset, int len) { + ExecutorService executorService = selectedExecutorService(session); + executorService.execute(() -> wsReceive0(session, payload, offset, len)); + } + + private void wsReceive0(Session session, byte[] payload, int offset, int len) { + try { + EzyWsHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(session); + if(handlerGroup != null) + handlerGroup.fireBytesReceived(payload, offset, len); + } + catch(Exception e) { + logger.info("I/O error at ws-message-received (session: {}): {}({})", session, e.getClass().getName(), e.getMessage()); + } + } + + public void wsCloseConnection(Session session) { + EzyWsHandlerGroup handlerGroup = handlerGroupManager.getHandlerGroup(session); + if(handlerGroup != null) + handlerGroup.enqueueDisconnection(); + } + + @Override + public void destroy() { + for(ExecutorService executorService : executorServices) + executorService.shutdownNow(); + } + + private ExecutorService selectedExecutorService(Object channel) { + int index = Math.abs(channel.hashCode() % threadPoolSize); + return executorServices[index]; + } + + private int getMaxBufferSize() { + return EzyCoreConstants.MAX_READ_BUFFER_SIZE; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected int threadPoolSize; + protected EzyHandlerGroupManager handlerGroupManager; + + public Builder threadPoolSize(int threadPoolSize) { + this.threadPoolSize = threadPoolSize; + return this; + } + + public Builder handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { + this.handlerGroupManager = handlerGroupManager; + return this; + } + + @Override + public EzySocketDataReceiver build() { + return new EzySocketDataReceiver(this); + } + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReader.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReader.java index 406d64b7e..0934e513a 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReader.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReader.java @@ -22,88 +22,88 @@ public class EzyNioUdpReader extends EzySocketAbstractEventHandler { - protected final ByteBuffer buffer; - @Setter - protected Selector ownSelector; - @Setter - protected EzyNioUdpDataHandler udpDataHandler; - - public EzyNioUdpReader(int maxBufferSize) { - this.buffer = ByteBuffer.allocateDirect(maxBufferSize); - } - - @Override - public void destroy() { - processWithLogException(() -> ownSelector.close()); - } - - @Override - public void handleEvent() { - try { - processReadyKeys(); - } - catch(Exception e) { - logger.info("I/O error at udp socket-reader: {}({})", e.getClass().getName(), e.getMessage()); - } - } - - private void processReadyKeys() throws Exception { - ownSelector.select(); - Set selectedKeys = this.ownSelector.selectedKeys(); - Iterator iterator = selectedKeys.iterator(); - while(iterator.hasNext()) { - SelectionKey key = iterator.next(); - iterator.remove(); - if(key.isValid()) { - processReadyKey(key); - } - } - } - - private void processReadyKey(SelectionKey key) throws Exception { - if(key.isReadable()) { - processReadableKey(key); - } - } - - private void processReadableKey(SelectionKey key) throws Exception { - DatagramChannel channel = (DatagramChannel) key.channel(); - try { - processReadBytes(channel); - } - catch (ClosedSelectorException e) { - logger.debug("selector has already closed: {}", e.getMessage()); - - } - catch (CancelledKeyException e) { - logger.debug("key has already cancelled: {}", e.getMessage()); - } - catch (IOException e) { - logger.warn("io exception: {}", e.getMessage()); - - } - catch (Exception e) { - logger.error("fatal error at udp socket-reader", e); - } - } - - private void processReadBytes(DatagramChannel channel) throws Exception { - buffer.clear(); - InetSocketAddress address = (InetSocketAddress) channel.receive(buffer); - if(address == null) { - logger.info("has no data in udp channel: {}", channel); - return; - } - int byteCount = buffer.position(); - - if (byteCount > 0) { - buffer.flip(); - byte[] binary = new byte[buffer.limit()]; - buffer.get(binary); - EzyUdpReceivedPacket packet = - new EzySimpleUdpReceivedPacket(channel, address, binary); - udpDataHandler.fireUdpPacketReceived(packet); - } - } - + protected final ByteBuffer buffer; + @Setter + protected Selector ownSelector; + @Setter + protected EzyNioUdpDataHandler udpDataHandler; + + public EzyNioUdpReader(int maxBufferSize) { + this.buffer = ByteBuffer.allocateDirect(maxBufferSize); + } + + @Override + public void destroy() { + processWithLogException(() -> ownSelector.close()); + } + + @Override + public void handleEvent() { + try { + processReadyKeys(); + } + catch(Exception e) { + logger.info("I/O error at udp socket-reader: {}({})", e.getClass().getName(), e.getMessage()); + } + } + + private void processReadyKeys() throws Exception { + ownSelector.select(); + Set selectedKeys = this.ownSelector.selectedKeys(); + Iterator iterator = selectedKeys.iterator(); + while(iterator.hasNext()) { + SelectionKey key = iterator.next(); + iterator.remove(); + if(key.isValid()) { + processReadyKey(key); + } + } + } + + private void processReadyKey(SelectionKey key) throws Exception { + if(key.isReadable()) { + processReadableKey(key); + } + } + + private void processReadableKey(SelectionKey key) throws Exception { + DatagramChannel channel = (DatagramChannel) key.channel(); + try { + processReadBytes(channel); + } + catch (ClosedSelectorException e) { + logger.debug("selector has already closed: {}", e.getMessage()); + + } + catch (CancelledKeyException e) { + logger.debug("key has already cancelled: {}", e.getMessage()); + } + catch (IOException e) { + logger.warn("io exception: {}", e.getMessage()); + + } + catch (Exception e) { + logger.error("fatal error at udp socket-reader", e); + } + } + + private void processReadBytes(DatagramChannel channel) throws Exception { + buffer.clear(); + InetSocketAddress address = (InetSocketAddress) channel.receive(buffer); + if(address == null) { + logger.info("has no data in udp channel: {}", channel); + return; + } + int byteCount = buffer.position(); + + if (byteCount > 0) { + buffer.flip(); + byte[] binary = new byte[buffer.limit()]; + buffer.get(binary); + EzyUdpReceivedPacket packet = + new EzySimpleUdpReceivedPacket(channel, address, binary); + udpDataHandler.fireUdpPacketReceived(packet); + } + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReadingLoopHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReadingLoopHandler.java index 1411e648b..0824c05fe 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReadingLoopHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/udp/EzyNioUdpReadingLoopHandler.java @@ -3,10 +3,10 @@ import com.tvd12.ezyfoxserver.socket.EzySocketEventLoopOneHandler; public class EzyNioUdpReadingLoopHandler extends EzySocketEventLoopOneHandler { - - @Override - protected String getThreadName() { - return "udp-reader"; - } - + + @Override + protected String getThreadName() { + return "udp-reader"; + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsHandlerGroup.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsHandlerGroup.java index a2818e9cb..bf079fc80 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsHandlerGroup.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsHandlerGroup.java @@ -11,110 +11,110 @@ import com.tvd12.ezyfoxserver.socket.EzySocketStream; public class EzySimpleWsHandlerGroup - extends EzyAbstractHandlerGroup - implements EzyWsHandlerGroup { - - private final EzyCallback decodeBytesCallback; - - public EzySimpleWsHandlerGroup(Builder builder) { - super(builder); - this.decodeBytesCallback = newDecodeBytesCallback(); - } - - protected EzyCallback newDecodeBytesCallback() { - return new EzyCallback() { - @Override - public void call(Object data) { - throw new UnsupportedOperationException("should use call(data, dataSize)"); - } - - @Override - public void call(Object data, int dataSize) { - handleReceivedData(data, dataSize); - } - }; - } - - @Override - protected EzyStringDataDecoder newDecoder(Object decoder) { - return new EzySimpleStringDataDecoder((EzyStringToObjectDecoder)decoder); - } - - @Override - public void fireBytesReceived(String bytes) throws Exception { - handleReceivedBytes(bytes); - executeAddReadBytes(bytes.length()); - } - - @Override - public void fireBytesReceived(byte[] bytes, int offset, int len) throws Exception { - handleReceivedBytes(bytes, offset, len); - executeAddReadBytes(len - offset); - } - - @SuppressWarnings("unused") - private void executeHandleReceivedBytes(String bytes) { - handleReceivedBytes(bytes); - } - - @SuppressWarnings("unused") - private void executeHandleReceivedBytes(byte[] bytes) { - handleReceivedBytes(bytes); - } - - private void handleReceivedBytes(String bytes) { - try { - decoder.decode(bytes, decodeBytesCallback); - } - catch(Throwable throwable) { - fireExceptionCaught(throwable); - } - } - - private void handleReceivedBytes(byte[] bytes) { - try { - decoder.decode(bytes, decodeBytesCallback); - } - catch(Throwable throwable) { - fireExceptionCaught(throwable); - } - } - - private void handleReceivedBytes(byte[] bytes, int offset, int len) { - try { - if(len <= 1) return; - byte headerByte = bytes[offset]; - boolean isRawBytes = EzyMessageHeaderReader.readRawBytes(headerByte); - if(isRawBytes) { - boolean sessionStreamingEnable = session.isStreamingEnable(); - if(!streamingEnable || !sessionStreamingEnable) { - return; - } - byte[] rawBytes = EzyBytes.copy(bytes, offset, len); - EzySocketStream stream = new EzySimpleSocketStream(session, rawBytes); - streamQueue.add(stream); - } - else { - int newLen = len - 1; - int newOffset = offset + 1; - byte[] messageBytes = EzyBytes.copy(bytes, newOffset, newLen); - handleReceivedBytes(messageBytes); - } - } - catch(Throwable throwable) { - fireExceptionCaught(throwable); - } - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyAbstractHandlerGroup.Builder { - @Override - public EzyWsHandlerGroup build() { - return new EzySimpleWsHandlerGroup(this); - } - } - + extends EzyAbstractHandlerGroup + implements EzyWsHandlerGroup { + + private final EzyCallback decodeBytesCallback; + + public EzySimpleWsHandlerGroup(Builder builder) { + super(builder); + this.decodeBytesCallback = newDecodeBytesCallback(); + } + + protected EzyCallback newDecodeBytesCallback() { + return new EzyCallback() { + @Override + public void call(Object data) { + throw new UnsupportedOperationException("should use call(data, dataSize)"); + } + + @Override + public void call(Object data, int dataSize) { + handleReceivedData(data, dataSize); + } + }; + } + + @Override + protected EzyStringDataDecoder newDecoder(Object decoder) { + return new EzySimpleStringDataDecoder((EzyStringToObjectDecoder)decoder); + } + + @Override + public void fireBytesReceived(String bytes) throws Exception { + handleReceivedBytes(bytes); + executeAddReadBytes(bytes.length()); + } + + @Override + public void fireBytesReceived(byte[] bytes, int offset, int len) throws Exception { + handleReceivedBytes(bytes, offset, len); + executeAddReadBytes(len - offset); + } + + @SuppressWarnings("unused") + private void executeHandleReceivedBytes(String bytes) { + handleReceivedBytes(bytes); + } + + @SuppressWarnings("unused") + private void executeHandleReceivedBytes(byte[] bytes) { + handleReceivedBytes(bytes); + } + + private void handleReceivedBytes(String bytes) { + try { + decoder.decode(bytes, decodeBytesCallback); + } + catch(Throwable throwable) { + fireExceptionCaught(throwable); + } + } + + private void handleReceivedBytes(byte[] bytes) { + try { + decoder.decode(bytes, decodeBytesCallback); + } + catch(Throwable throwable) { + fireExceptionCaught(throwable); + } + } + + private void handleReceivedBytes(byte[] bytes, int offset, int len) { + try { + if(len <= 1) return; + byte headerByte = bytes[offset]; + boolean isRawBytes = EzyMessageHeaderReader.readRawBytes(headerByte); + if(isRawBytes) { + boolean sessionStreamingEnable = session.isStreamingEnable(); + if(!streamingEnable || !sessionStreamingEnable) { + return; + } + byte[] rawBytes = EzyBytes.copy(bytes, offset, len); + EzySocketStream stream = new EzySimpleSocketStream(session, rawBytes); + streamQueue.add(stream); + } + else { + int newLen = len - 1; + int newOffset = offset + 1; + byte[] messageBytes = EzyBytes.copy(bytes, newOffset, newLen); + handleReceivedBytes(messageBytes); + } + } + catch(Throwable throwable) { + fireExceptionCaught(throwable); + } + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyAbstractHandlerGroup.Builder { + @Override + public EzyWsHandlerGroup build() { + return new EzySimpleWsHandlerGroup(this); + } + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsChannel.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsChannel.java index 461ff5707..ae4d90a77 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsChannel.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsChannel.java @@ -19,83 +19,83 @@ @Getter public class EzyWsChannel implements EzyChannel { - private final Session session; - private volatile boolean opened; - private final SocketAddress serverAddress; - private final SocketAddress clientAddress; - private final static Logger LOGGER = LoggerFactory.getLogger(EzyWsChannel.class); - - public EzyWsChannel(Session session) { - this.opened = true; - this.session = session; - this.serverAddress = session.getLocalAddress(); - this.clientAddress = session.getRemoteAddress(); - } - - @Override - public int write(Object data, boolean binary) throws Exception { - try { - if(binary) - return writeBinary((byte[])data); - return writeString((String)data); - } - catch(WebSocketException e) { - LOGGER.debug("write data: {}, to: {} error", data, clientAddress, e); - return 0; - } - } - - private int writeBinary(byte[] bytes) throws Exception { - int bytesSize = bytes.length; - RemoteEndpoint remote = session.getRemote(); - remote.sendBytes(ByteBuffer.wrap(bytes)); - return bytesSize; - } - - private int writeString(String bytes) throws Exception { - int bytesSize = bytes.length(); - RemoteEndpoint remote = session.getRemote(); - remote.sendString(bytes); - return bytesSize; - } - - @SuppressWarnings("unchecked") - @Override - public Session getConnection() { - return session; - } - - @Override - public EzyConnectionType getConnectionType() { - return EzyConnectionType.WEBSOCKET; - } - - @Override - public boolean isConnected() { - return opened; - } - - public void setClosed() { - this.opened = false; - } - - @Override - public void disconnect() { - try { - session.disconnect(); - } - catch(Exception e) { - LOGGER.warn("disconnect session: {} error", session, e); - } - } - - @Override - public void close() { - try { - session.close(CLOSE_BY_SERVER); - } - catch(Exception e) { - LOGGER.warn("close session: {} error", session, e); - } - } + private final Session session; + private volatile boolean opened; + private final SocketAddress serverAddress; + private final SocketAddress clientAddress; + private final static Logger LOGGER = LoggerFactory.getLogger(EzyWsChannel.class); + + public EzyWsChannel(Session session) { + this.opened = true; + this.session = session; + this.serverAddress = session.getLocalAddress(); + this.clientAddress = session.getRemoteAddress(); + } + + @Override + public int write(Object data, boolean binary) throws Exception { + try { + if(binary) + return writeBinary((byte[])data); + return writeString((String)data); + } + catch(WebSocketException e) { + LOGGER.debug("write data: {}, to: {} error", data, clientAddress, e); + return 0; + } + } + + private int writeBinary(byte[] bytes) throws Exception { + int bytesSize = bytes.length; + RemoteEndpoint remote = session.getRemote(); + remote.sendBytes(ByteBuffer.wrap(bytes)); + return bytesSize; + } + + private int writeString(String bytes) throws Exception { + int bytesSize = bytes.length(); + RemoteEndpoint remote = session.getRemote(); + remote.sendString(bytes); + return bytesSize; + } + + @SuppressWarnings("unchecked") + @Override + public Session getConnection() { + return session; + } + + @Override + public EzyConnectionType getConnectionType() { + return EzyConnectionType.WEBSOCKET; + } + + @Override + public boolean isConnected() { + return opened; + } + + public void setClosed() { + this.opened = false; + } + + @Override + public void disconnect() { + try { + session.disconnect(); + } + catch(Exception e) { + LOGGER.warn("disconnect session: {} error", session, e); + } + } + + @Override + public void close() { + try { + session.close(CLOSE_BY_SERVER); + } + catch(Exception e) { + LOGGER.warn("close session: {} error", session, e); + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsCloseStatus.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsCloseStatus.java index 2100b67e1..739d4be70 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsCloseStatus.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsCloseStatus.java @@ -3,11 +3,11 @@ import org.eclipse.jetty.websocket.api.CloseStatus; public class EzyWsCloseStatus extends CloseStatus { - - public static final EzyWsCloseStatus CLOSE_BY_SERVER = new EzyWsCloseStatus(3000, "Close By Server"); + + public static final EzyWsCloseStatus CLOSE_BY_SERVER = new EzyWsCloseStatus(3000, "Close By Server"); - public EzyWsCloseStatus(int closeCode, String reasonPhrase) { - super(closeCode, reasonPhrase); - } + public EzyWsCloseStatus(int closeCode, String reasonPhrase) { + super(closeCode, reasonPhrase); + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandler.java index 964498f8d..24f2490be 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandler.java @@ -25,111 +25,111 @@ @WebSocket public class EzyWsHandler extends EzyLoggable { - private final EzySocketDataReceiver socketDataReceiver; - private final EzyNioSessionManager sessionManager; - private final EzyHandlerGroupManager handlerGroupManager; - private final EzySessionManagementSetting sessionManagementSetting; - - private static final Set IGNORE_STATUS_CODES = Sets.newHashSet( - CLOSE_BY_SERVER.getCode() - ); - - public EzyWsHandler(Builder builder) { - this.socketDataReceiver = builder.socketDataReceiver; - this.sessionManager = builder.sessionManager; - this.handlerGroupManager = builder.handlerGroupManager; - this.sessionManagementSetting = builder.sessionManagementSetting; - } - - private boolean isIgnoreStatusCode(int statusCode) { - return IGNORE_STATUS_CODES.contains(statusCode); - } - - @OnWebSocketClose - public void onClose(Session session, int statusCode, String reason) { - logger.debug("close session: {}, statusCode = {}, reason = {}", session.getRemoteAddress(), statusCode, reason); - if(isIgnoreStatusCode(statusCode)) - return; - setChannelClosed(session); - socketDataReceiver.wsCloseConnection(session); - } - - @OnWebSocketError - public void onError(Session session, Throwable throwable) { - EzyWsHandlerGroup dataHandler = handlerGroupManager.getHandlerGroup(session); - if(dataHandler == null) { - logger.debug("error on session: {}, but data handler removed", session.getRemoteAddress(), throwable); - } - if (throwable instanceof TimeoutException) { - logger.debug("session {}: Timeout on Read", session.getRemoteAddress()); - } - else if(dataHandler != null) { - logger.debug("error on session: {}", session.getRemoteAddress(), throwable); - dataHandler.fireExceptionCaught(throwable); - } - } - - @OnWebSocketConnect - public void onConnect(Session session) throws Exception { - long sessionMaxIdleTime = sessionManagementSetting.getSessionMaxIdleTime(); - session.setIdleTimeout(sessionMaxIdleTime); - EzyChannel channel = new EzyWsChannel(session); - handlerGroupManager.newHandlerGroup(channel, EzyConnectionType.WEBSOCKET); - } - - @OnWebSocketMessage - public void onMessage(Session session, String message) throws Exception { - socketDataReceiver.wsReceive(session, message); - } - - @OnWebSocketMessage - public void onMessage(Session session, byte[] payload, int offset, int len) throws Exception { - socketDataReceiver.wsReceive(session, payload, offset, len); - } - - private void setChannelClosed(Session connection) { - EzyNioSession session = sessionManager.getSession(connection); - if(session != null) { - EzyWsChannel channel = (EzyWsChannel) session.getChannel(); - if(channel != null) - channel.setClosed(); - } - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - - private EzySocketDataReceiver socketDataReceiver; - private EzyNioSessionManager sessionManager; - private EzyHandlerGroupManager handlerGroupManager; - private EzySessionManagementSetting sessionManagementSetting; - - public Builder socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { - this.socketDataReceiver = socketDataReceiver; - return this; - } - - public Builder sessionManager(EzyNioSessionManager sessionManager) { - this.sessionManager = sessionManager; - return this; - } - - public Builder handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { - this.handlerGroupManager = handlerGroupManager; - return this; - } - - public Builder sessionManagementSetting(EzySessionManagementSetting sessionManagementSetting) { - this.sessionManagementSetting = sessionManagementSetting; - return this; - } - - @Override - public EzyWsHandler build() { - return new EzyWsHandler(this); - } - } + private final EzySocketDataReceiver socketDataReceiver; + private final EzyNioSessionManager sessionManager; + private final EzyHandlerGroupManager handlerGroupManager; + private final EzySessionManagementSetting sessionManagementSetting; + + private static final Set IGNORE_STATUS_CODES = Sets.newHashSet( + CLOSE_BY_SERVER.getCode() + ); + + public EzyWsHandler(Builder builder) { + this.socketDataReceiver = builder.socketDataReceiver; + this.sessionManager = builder.sessionManager; + this.handlerGroupManager = builder.handlerGroupManager; + this.sessionManagementSetting = builder.sessionManagementSetting; + } + + private boolean isIgnoreStatusCode(int statusCode) { + return IGNORE_STATUS_CODES.contains(statusCode); + } + + @OnWebSocketClose + public void onClose(Session session, int statusCode, String reason) { + logger.debug("close session: {}, statusCode = {}, reason = {}", session.getRemoteAddress(), statusCode, reason); + if(isIgnoreStatusCode(statusCode)) + return; + setChannelClosed(session); + socketDataReceiver.wsCloseConnection(session); + } + + @OnWebSocketError + public void onError(Session session, Throwable throwable) { + EzyWsHandlerGroup dataHandler = handlerGroupManager.getHandlerGroup(session); + if(dataHandler == null) { + logger.debug("error on session: {}, but data handler removed", session.getRemoteAddress(), throwable); + } + if (throwable instanceof TimeoutException) { + logger.debug("session {}: Timeout on Read", session.getRemoteAddress()); + } + else if(dataHandler != null) { + logger.debug("error on session: {}", session.getRemoteAddress(), throwable); + dataHandler.fireExceptionCaught(throwable); + } + } + + @OnWebSocketConnect + public void onConnect(Session session) throws Exception { + long sessionMaxIdleTime = sessionManagementSetting.getSessionMaxIdleTime(); + session.setIdleTimeout(sessionMaxIdleTime); + EzyChannel channel = new EzyWsChannel(session); + handlerGroupManager.newHandlerGroup(channel, EzyConnectionType.WEBSOCKET); + } + + @OnWebSocketMessage + public void onMessage(Session session, String message) throws Exception { + socketDataReceiver.wsReceive(session, message); + } + + @OnWebSocketMessage + public void onMessage(Session session, byte[] payload, int offset, int len) throws Exception { + socketDataReceiver.wsReceive(session, payload, offset, len); + } + + private void setChannelClosed(Session connection) { + EzyNioSession session = sessionManager.getSession(connection); + if(session != null) { + EzyWsChannel channel = (EzyWsChannel) session.getChannel(); + if(channel != null) + channel.setClosed(); + } + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private EzySocketDataReceiver socketDataReceiver; + private EzyNioSessionManager sessionManager; + private EzyHandlerGroupManager handlerGroupManager; + private EzySessionManagementSetting sessionManagementSetting; + + public Builder socketDataReceiver(EzySocketDataReceiver socketDataReceiver) { + this.socketDataReceiver = socketDataReceiver; + return this; + } + + public Builder sessionManager(EzyNioSessionManager sessionManager) { + this.sessionManager = sessionManager; + return this; + } + + public Builder handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { + this.handlerGroupManager = handlerGroupManager; + return this; + } + + public Builder sessionManagementSetting(EzySessionManagementSetting sessionManagementSetting) { + this.sessionManagementSetting = sessionManagementSetting; + return this; + } + + @Override + public EzyWsHandler build() { + return new EzyWsHandler(this); + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandlerGroup.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandlerGroup.java index cbc9e232a..811bd93f2 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandlerGroup.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandlerGroup.java @@ -4,8 +4,8 @@ public interface EzyWsHandlerGroup extends EzyHandlerGroup { - void fireBytesReceived(String bytes) throws Exception; - - void fireBytesReceived(byte[] bytes, int offset, int len) throws Exception; - + void fireBytesReceived(String bytes) throws Exception; + + void fireBytesReceived(byte[] bytes, int offset, int len) throws Exception; + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsWritingLoopHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsWritingLoopHandler.java index 0af9f7389..f669c1fba 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsWritingLoopHandler.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsWritingLoopHandler.java @@ -3,10 +3,10 @@ import com.tvd12.ezyfoxserver.socket.EzySocketWritingLoopHandler; public class EzyWsWritingLoopHandler extends EzySocketWritingLoopHandler { - - @Override - protected String getThreadName() { - return "web-socket-writer"; - } - + + @Override + protected String getThreadName() { + return "web-socket-writer"; + } + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManager.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManager.java index 02f17f1be..7376d9993 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManager.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManager.java @@ -12,19 +12,19 @@ import com.tvd12.ezyfoxserver.socket.EzySocketWriterGroupFetcher; public interface EzyHandlerGroupManager - extends EzySocketDataHandlerGroupFetcher, - EzySocketDataHandlerGroupRemover, - EzySocketWriterGroupFetcher, - EzyDestroyable { - - T getHandlerGroup(Object connection); - - T newHandlerGroup(EzyChannel channel, EzyConnectionType type); - - void unmapHandlerGroup(SocketAddress udpAddress); - - void mapSocketChannel(SocketAddress udpAddress, EzySession session); - - Object getSocketChannel(SocketAddress udpAddress); - + extends EzySocketDataHandlerGroupFetcher, + EzySocketDataHandlerGroupRemover, + EzySocketWriterGroupFetcher, + EzyDestroyable { + + T getHandlerGroup(Object connection); + + T newHandlerGroup(EzyChannel channel, EzyConnectionType type); + + void unmapHandlerGroup(SocketAddress udpAddress); + + void mapSocketChannel(SocketAddress udpAddress, EzySession session); + + Object getSocketChannel(SocketAddress udpAddress); + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManagerAware.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManagerAware.java index 6c1e0bc96..2773046cd 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManagerAware.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManagerAware.java @@ -2,6 +2,6 @@ public interface EzyHandlerGroupManagerAware { - void setHandlerGroupManager(EzyHandlerGroupManager manager); - + void setHandlerGroupManager(EzyHandlerGroupManager manager); + } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyHandlerGroupManagerImpl.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyHandlerGroupManagerImpl.java index 5ccda9028..406291305 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyHandlerGroupManagerImpl.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyHandlerGroupManagerImpl.java @@ -16,123 +16,123 @@ import com.tvd12.ezyfoxserver.socket.EzySocketWriterGroup; public class EzyHandlerGroupManagerImpl - extends EzyLoggable - implements EzyHandlerGroupManager { - - private final Map socketChannelByUdpAddress; - private final Map groupsByConnection; - private final EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory; - - public EzyHandlerGroupManagerImpl(Builder builder) { - this.handlerGroupBuilderFactory = builder.handlerGroupBuilderFactory; - this.groupsByConnection = new ConcurrentHashMap<>(); - this.socketChannelByUdpAddress = new ConcurrentHashMap<>(); - } - - @SuppressWarnings("unchecked") - @Override - public T newHandlerGroup(EzyChannel channel, EzyConnectionType type) { - EzyHandlerGroup group = handlerGroupBuilderFactory.newBuilder(channel, type) - .build(); - groupsByConnection.put(channel.getConnection(), group); - return (T) group; - } - - @SuppressWarnings("unchecked") - @Override - public T getHandlerGroup(Object connection) { - return (T) groupsByConnection.get(connection); - } - - @Override - public void unmapHandlerGroup(SocketAddress udpAddress) { - if(udpAddress != null) { - socketChannelByUdpAddress.remove(udpAddress); - logger.debug("unmap socket channel from: {}, socketChannelByUdpAddress.size: {}", udpAddress, socketChannelByUdpAddress.size()); - } - } - - @Override - public void mapSocketChannel(SocketAddress udpAddress, EzySession session) { - if(session == null) - return; - EzyChannel channel = session.getChannel(); - if(channel == null) - return; - Object connection = channel.getConnection(); - if(connection == null) - return; - if(groupsByConnection.containsKey(connection)) - socketChannelByUdpAddress.put(udpAddress, connection); - logger.debug("map socket channel to: {}, socketChannelByUdpAddress.size: {}", udpAddress, socketChannelByUdpAddress.size()); - } - - @Override - public Object getSocketChannel(SocketAddress udpAddress) { - return socketChannelByUdpAddress.get(udpAddress); - } - - @Override - public EzySocketDataHandlerGroup removeHandlerGroup(EzySession session) { - if(session == null) - return null; - EzyChannel channel = session.getChannel(); - if(channel == null) - return null; - Object connection = channel.getConnection(); - if(connection == null) - return null; - EzyHandlerGroup group = groupsByConnection.remove(connection); - SocketAddress udpClientAddress = session.getUdpClientAddress(); - if(udpClientAddress != null) - socketChannelByUdpAddress.remove(udpClientAddress); - logger.debug("remove handler group: {} with session: {}, groupsByConnection.size: {}, socketChannelByUdpAddress.size: {}", group, session, groupsByConnection.size(), socketChannelByUdpAddress.size()); - return group; - } - - private EzyHandlerGroup getHandlerGroup(EzySession session) { - if(session == null) - return null; - EzyChannel channel = session.getChannel(); - if(channel == null) - return null; - Object connection = channel.getConnection(); - if(connection == null) - return null; - EzyHandlerGroup group = groupsByConnection.get(connection); - return group; - } - - @Override - public EzySocketDataHandlerGroup getDataHandlerGroup(EzySession session) { - return getHandlerGroup(session); - } - - @Override - public EzySocketWriterGroup getWriterGroup(EzySession session) { - return getHandlerGroup(session); - } - - @Override - public void destroy() { - groupsByConnection.clear(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - private EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory; - - public Builder handlerGroupBuilderFactory(EzyHandlerGroupBuilderFactory factory) { - this.handlerGroupBuilderFactory = factory; - return this; - } - - @Override - public EzyHandlerGroupManager build() { - return new EzyHandlerGroupManagerImpl(this); - } - } + extends EzyLoggable + implements EzyHandlerGroupManager { + + private final Map socketChannelByUdpAddress; + private final Map groupsByConnection; + private final EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory; + + public EzyHandlerGroupManagerImpl(Builder builder) { + this.handlerGroupBuilderFactory = builder.handlerGroupBuilderFactory; + this.groupsByConnection = new ConcurrentHashMap<>(); + this.socketChannelByUdpAddress = new ConcurrentHashMap<>(); + } + + @SuppressWarnings("unchecked") + @Override + public T newHandlerGroup(EzyChannel channel, EzyConnectionType type) { + EzyHandlerGroup group = handlerGroupBuilderFactory.newBuilder(channel, type) + .build(); + groupsByConnection.put(channel.getConnection(), group); + return (T) group; + } + + @SuppressWarnings("unchecked") + @Override + public T getHandlerGroup(Object connection) { + return (T) groupsByConnection.get(connection); + } + + @Override + public void unmapHandlerGroup(SocketAddress udpAddress) { + if(udpAddress != null) { + socketChannelByUdpAddress.remove(udpAddress); + logger.debug("unmap socket channel from: {}, socketChannelByUdpAddress.size: {}", udpAddress, socketChannelByUdpAddress.size()); + } + } + + @Override + public void mapSocketChannel(SocketAddress udpAddress, EzySession session) { + if(session == null) + return; + EzyChannel channel = session.getChannel(); + if(channel == null) + return; + Object connection = channel.getConnection(); + if(connection == null) + return; + if(groupsByConnection.containsKey(connection)) + socketChannelByUdpAddress.put(udpAddress, connection); + logger.debug("map socket channel to: {}, socketChannelByUdpAddress.size: {}", udpAddress, socketChannelByUdpAddress.size()); + } + + @Override + public Object getSocketChannel(SocketAddress udpAddress) { + return socketChannelByUdpAddress.get(udpAddress); + } + + @Override + public EzySocketDataHandlerGroup removeHandlerGroup(EzySession session) { + if(session == null) + return null; + EzyChannel channel = session.getChannel(); + if(channel == null) + return null; + Object connection = channel.getConnection(); + if(connection == null) + return null; + EzyHandlerGroup group = groupsByConnection.remove(connection); + SocketAddress udpClientAddress = session.getUdpClientAddress(); + if(udpClientAddress != null) + socketChannelByUdpAddress.remove(udpClientAddress); + logger.debug("remove handler group: {} with session: {}, groupsByConnection.size: {}, socketChannelByUdpAddress.size: {}", group, session, groupsByConnection.size(), socketChannelByUdpAddress.size()); + return group; + } + + private EzyHandlerGroup getHandlerGroup(EzySession session) { + if(session == null) + return null; + EzyChannel channel = session.getChannel(); + if(channel == null) + return null; + Object connection = channel.getConnection(); + if(connection == null) + return null; + EzyHandlerGroup group = groupsByConnection.get(connection); + return group; + } + + @Override + public EzySocketDataHandlerGroup getDataHandlerGroup(EzySession session) { + return getHandlerGroup(session); + } + + @Override + public EzySocketWriterGroup getWriterGroup(EzySession session) { + return getHandlerGroup(session); + } + + @Override + public void destroy() { + groupsByConnection.clear(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + private EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory; + + public Builder handlerGroupBuilderFactory(EzyHandlerGroupBuilderFactory factory) { + this.handlerGroupBuilderFactory = factory; + return this; + } + + @Override + public EzyHandlerGroupManager build() { + return new EzyHandlerGroupManagerImpl(this); + } + } } diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyNioSessionManagerImpl.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyNioSessionManagerImpl.java index a30167fd0..38504cf71 100644 --- a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyNioSessionManagerImpl.java +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyNioSessionManagerImpl.java @@ -8,38 +8,38 @@ import static com.tvd12.ezyfoxserver.setting.EzySessionManagementSetting.EzyMaxRequestPerSecond; public class EzyNioSessionManagerImpl - extends EzySimpleSessionManager - implements EzyNioSessionManager { - - protected EzyNioSessionManagerImpl(Builder builder) { - super(builder); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzySimpleSessionManager.Builder { - - protected EzyMaxRequestPerSecond maxRequestPerSecond; - - public Builder maxRequestPerSecond(EzyMaxRequestPerSecond maxRequestPerSecond) { - this.maxRequestPerSecond = maxRequestPerSecond; - return this; - } - - @Override - public EzyNioSessionManagerImpl build() { - return new EzyNioSessionManagerImpl(this); - } - - @Override - protected EzyObjectFactory newObjectFactory() { - EzyNioSessionFactory factory = new EzyNioSessionFactory(); - factory.setMaxRequestPerSecond(maxRequestPerSecond); - return factory; - } - } - - + extends EzySimpleSessionManager + implements EzyNioSessionManager { + + protected EzyNioSessionManagerImpl(Builder builder) { + super(builder); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleSessionManager.Builder { + + protected EzyMaxRequestPerSecond maxRequestPerSecond; + + public Builder maxRequestPerSecond(EzyMaxRequestPerSecond maxRequestPerSecond) { + this.maxRequestPerSecond = maxRequestPerSecond; + return this; + } + + @Override + public EzyNioSessionManagerImpl build() { + return new EzyNioSessionManagerImpl(this); + } + + @Override + protected EzyObjectFactory newObjectFactory() { + EzyNioSessionFactory factory = new EzyNioSessionFactory(); + factory.setMaxRequestPerSecond(maxRequestPerSecond); + return factory; + } + } + + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ByteBufferAndByteArrayTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ByteBufferAndByteArrayTest.java index a9c1c51d3..494c75673 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ByteBufferAndByteArrayTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ByteBufferAndByteArrayTest.java @@ -11,47 +11,47 @@ public class ByteBufferAndByteArrayTest extends BaseTest { - @SuppressWarnings("unused") - @Test - public void test() { - byte[] bc = new byte[200]; - for(int i = 0 ; i < 200 ; ++i) { - bc[i] = 1; - } - long time1 = Performance.create() - .test(() -> { - ByteBuffer byteBuffer = ByteBuffer.allocate(3 + 200); - byteBuffer.put((byte)0); - byteBuffer.putShort((short)47); - byteBuffer.put(bc); - byteBuffer.flip(); - byte[] bytes = new byte[3 + 200]; - byteBuffer.get(bytes); - }) - .getTime(); - long time2 = Performance.create() - .test(() -> { - byte[] bytes = new byte[3 + 200]; - bytes[0] = 0; - EzyArrays.copy(EzyBytes.getBytes((short)47), bytes, 1); - EzyArrays.copy(bc, bytes, 3); - }) - .getTime(); - - long time3 = Performance.create() - .test(() -> { - ByteBuffer byteBuffer = ByteBuffer.allocate(3276); - }).getTime(); - - long time4 = Performance.create() - .test(() -> { - byte[] bytes = new byte[3276]; - }).getTime(); - - System.out.println(time1); - System.out.println(time2); - System.out.println(time3); - System.out.println(time4); - } - + @SuppressWarnings("unused") + @Test + public void test() { + byte[] bc = new byte[200]; + for(int i = 0 ; i < 200 ; ++i) { + bc[i] = 1; + } + long time1 = Performance.create() + .test(() -> { + ByteBuffer byteBuffer = ByteBuffer.allocate(3 + 200); + byteBuffer.put((byte)0); + byteBuffer.putShort((short)47); + byteBuffer.put(bc); + byteBuffer.flip(); + byte[] bytes = new byte[3 + 200]; + byteBuffer.get(bytes); + }) + .getTime(); + long time2 = Performance.create() + .test(() -> { + byte[] bytes = new byte[3 + 200]; + bytes[0] = 0; + EzyArrays.copy(EzyBytes.getBytes((short)47), bytes, 1); + EzyArrays.copy(bc, bytes, 3); + }) + .getTime(); + + long time3 = Performance.create() + .test(() -> { + ByteBuffer byteBuffer = ByteBuffer.allocate(3276); + }).getTime(); + + long time4 = Performance.create() + .test(() -> { + byte[] bytes = new byte[3276]; + }).getTime(); + + System.out.println(time1); + System.out.println(time2); + System.out.println(time3); + System.out.println(time4); + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ConcurrentLinkedListTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ConcurrentLinkedListTest.java index ab33732e3..f30ce7542 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ConcurrentLinkedListTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ConcurrentLinkedListTest.java @@ -4,28 +4,28 @@ public class ConcurrentLinkedListTest { - public static void main(String[] args) { - ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); - Thread write = new Thread(() -> { - int i = 0; - while(true) { - queue.add(i ++); - } - }); - write.start(); - - Thread[] reads = new Thread[200]; - for(int i = 0 ; i < reads.length ; ++i) { - final int index = i; - reads[index] = new Thread(() -> { - while(true) { - System.out.println("thread-" + index + "\t\t" + queue.poll()); - } - }); - } - for(int i = 0 ; i < reads.length ; ++i) { - reads[i].start(); - } - } - + public static void main(String[] args) { + ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); + Thread write = new Thread(() -> { + int i = 0; + while(true) { + queue.add(i ++); + } + }); + write.start(); + + Thread[] reads = new Thread[200]; + for(int i = 0 ; i < reads.length ; ++i) { + final int index = i; + reads[index] = new Thread(() -> { + while(true) { + System.out.println("thread-" + index + "\t\t" + queue.poll()); + } + }); + } + for(int i = 0 ; i < reads.length ; ++i) { + reads[i].start(); + } + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyAbstractSocketServerBootstrapTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyAbstractSocketServerBootstrapTest.java index 56511e477..8a466105f 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyAbstractSocketServerBootstrapTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyAbstractSocketServerBootstrapTest.java @@ -12,36 +12,36 @@ public class EzyAbstractSocketServerBootstrapTest { - @Test - public void destroyTest() { - // given - EzySocketEventLoopHandler writingLoopHandler = mock(EzySocketEventLoopHandler.class); - InternalBoostrap sut = new InternalBoostrap.Builder() - .build(); - FieldUtil.setFieldValue(sut, "writingLoopHandler", writingLoopHandler); - - // when - sut.destroy(); - - // then - verify(writingLoopHandler, times(1)).destroy(); - } - - private static class InternalBoostrap extends EzyAbstractSocketServerBootstrap { + @Test + public void destroyTest() { + // given + EzySocketEventLoopHandler writingLoopHandler = mock(EzySocketEventLoopHandler.class); + InternalBoostrap sut = new InternalBoostrap.Builder() + .build(); + FieldUtil.setFieldValue(sut, "writingLoopHandler", writingLoopHandler); + + // when + sut.destroy(); + + // then + verify(writingLoopHandler, times(1)).destroy(); + } + + private static class InternalBoostrap extends EzyAbstractSocketServerBootstrap { - public InternalBoostrap(Builder builder) { - super(builder); - } - - public static class Builder extends EzyAbstractSocketServerBootstrap.Builder { - @Override - public InternalBoostrap build() { - return new InternalBoostrap(this); - } - } + public InternalBoostrap(Builder builder) { + super(builder); + } + + public static class Builder extends EzyAbstractSocketServerBootstrap.Builder { + @Override + public InternalBoostrap build() { + return new InternalBoostrap(this); + } + } - @Override - public void start() throws Exception { - } - } + @Override + public void start() throws Exception { + } + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyHandlerGroupBuilderFactoryImplTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyHandlerGroupBuilderFactoryImplTest.java index e3cac046e..05f8e44fa 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyHandlerGroupBuilderFactoryImplTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyHandlerGroupBuilderFactoryImplTest.java @@ -11,18 +11,18 @@ public class EzyHandlerGroupBuilderFactoryImplTest { - @Test - public void buildWithSessionCreatorNotNull() { - // given - EzySessionCreator sessionCreator = mock(EzySessionCreator.class); - EzyHandlerGroupBuilderFactoryImpl.Builder builder = - EzyHandlerGroupBuilderFactoryImpl.builder() - .sessionCreator(sessionCreator); - - // when - EzyHandlerGroupBuilderFactory factor = builder.build(); - - // then - Asserts.assertNotNull(factor); - } + @Test + public void buildWithSessionCreatorNotNull() { + // given + EzySessionCreator sessionCreator = mock(EzySessionCreator.class); + EzyHandlerGroupBuilderFactoryImpl.Builder builder = + EzyHandlerGroupBuilderFactoryImpl.builder() + .sessionCreator(sessionCreator); + + // when + EzyHandlerGroupBuilderFactory factor = builder.build(); + + // then + Asserts.assertNotNull(factor); + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioServerBootstrapTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioServerBootstrapTest.java index faafac80d..be2a0e280 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioServerBootstrapTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioServerBootstrapTest.java @@ -45,205 +45,205 @@ public class EzyNioServerBootstrapTest extends BaseTest { - @Test - public void test() throws Exception { - SSLContext sslContext = SSLContext.getDefault(); - EzyResponseApi responseApi = mock(EzyResponseApi.class); - EzyStreamingApi streamingApi = mock(EzyStreamingApi.class); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue websocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - EzySocketDisconnectionQueue socketDisconnectionQueue = new EzySocketDisconnectionQueue() { - - BlockingQueue queue = new LinkedBlockingQueue<>(); - - @Override - public EzySocketDisconnection take() throws InterruptedException { - return queue.take(); - } - - @Override - public int size() { - return 0; - } - - @Override - public void remove(EzySocketDisconnection disconnection) { - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public void clear() { - } - - @Override - public boolean add(EzySocketDisconnection disconnection) { - return false; - } - }; - - EzySimpleConfig config = new EzySimpleConfig(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - settings.getUdp().setActive(true); - EzySimpleServer server = new EzySimpleServer(); - EzyServerControllers serverControllers = EzyServerControllersImpl.builder().build(); - server.setControllers(serverControllers); - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - server.setEventControllers(eventControllers); - server.setConfig(config); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setProperty(EzySocketUserRemovalQueue.class, new EzyBlockingSocketUserRemovalQueue()); - serverContext.setServer(server); - serverContext.init(); - - ExBootstrap localBootstrap = new ExBootstrap(new EzyBootstrap.Builder() - .context(serverContext)); - - EzyNioServerBootstrap bootstrap = new EzyNioServerBootstrap(); - bootstrap.setContext(serverContext); - bootstrap.setLocalBootstrap(localBootstrap); - bootstrap.setSslContext(sslContext); - bootstrap.setResponseApi(responseApi); - bootstrap.setStreamingApi(streamingApi); - bootstrap.setStreamQueue(streamQueue); - bootstrap.setHandlerGroupManager(handlerGroupManager); - bootstrap.setSocketSessionTicketsQueue(socketSessionTicketsQueue); - bootstrap.setWebsocketSessionTicketsQueue(websocketSessionTicketsQueue); - bootstrap.setSocketDisconnectionQueue(socketDisconnectionQueue); - bootstrap.setSocketSessionTicketsRequestQueues(sessionTicketsRequestQueues); - bootstrap.start(); - bootstrap.destroy(); - bootstrap.destroy(); - } - - @Test - public void startSocketServerBootstrapNotActive() { - // given - EzySimpleServer server = new EzySimpleServer(); - EzySimpleSettings settings = new EzySimpleSettings(); - settings.getSocket().setActive(false); - server.setSettings(settings); - - EzyServerContext context = mock(EzyServerContext.class); - when(context.getServer()).thenReturn(server); - - EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); - sut.setContext(context); - - // when - MethodUtil.invokeMethod("startSocketServerBootstrap", sut); - - // then - Asserts.assertNull(FieldUtil.getFieldValue(sut, "socketServerBootstrap")); - } - - @Test - public void startUdpServerBootstrapNotActive() { - // given - EzySimpleServer server = new EzySimpleServer(); - EzySimpleSettings settings = new EzySimpleSettings(); - settings.getUdp().setActive(false); - server.setSettings(settings); - - EzyServerContext context = mock(EzyServerContext.class); - when(context.getServer()).thenReturn(server); - - EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); - sut.setContext(context); - - // when - MethodUtil.invokeMethod("startUdpServerBootstrap", sut); - - // then - Asserts.assertNull(FieldUtil.getFieldValue(sut, "udpServerBootstrap")); - sut.destroy(); - } - - @Test - public void startWebSocketServerBootstrapNotActive() { - // given - EzySimpleServer server = new EzySimpleServer(); - EzySimpleSettings settings = new EzySimpleSettings(); - settings.getWebsocket().setActive(false); - server.setSettings(settings); - - EzyServerContext context = mock(EzyServerContext.class); - when(context.getServer()).thenReturn(server); - - EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); - sut.setContext(context); - - // when - MethodUtil.invokeMethod("startWebSocketServerBootstrap", sut); - - // then - Asserts.assertNull(FieldUtil.getFieldValue(sut, "websocketServerBootstrap")); - } - - @Test - public void startStreamHandlingLoopHandlersNotActive() { - // given - EzySimpleServer server = new EzySimpleServer(); - EzySimpleSettings settings = new EzySimpleSettings(); - settings.getStreaming().setEnable(false); - server.setSettings(settings); - - EzyServerContext context = mock(EzyServerContext.class); - when(context.getServer()).thenReturn(server); - - EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); - sut.setContext(context); - - // when - MethodUtil.invokeMethod("startStreamHandlingLoopHandlers", sut); - - // then - Asserts.assertNull(FieldUtil.getFieldValue(sut, "streamHandlingLoopHandler")); - } - - @Test - public void destroySocketDataReceiver() { - // given - EzySocketDataReceiver dataReceiver = mock(EzySocketDataReceiver.class); - - EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); - sut.setSocketDataReceiver(dataReceiver); - - // when - sut.destroy(); - - // then - verify(dataReceiver, times(1)).destroy(); - } - - public static class ExBootstrap extends EzyBootstrap { - - protected ExBootstrap(Builder builder) { - super(builder); - } - - @Override - public void start() throws Exception { - } - - } - - public static class ExServerReadyController implements EzyServerReadyController { - - @Override - public void handle(EzyServerContext ctx, EzyServerReadyEvent event) { - } - - } - + @Test + public void test() throws Exception { + SSLContext sslContext = SSLContext.getDefault(); + EzyResponseApi responseApi = mock(EzyResponseApi.class); + EzyStreamingApi streamingApi = mock(EzyStreamingApi.class); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue websocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + EzySocketDisconnectionQueue socketDisconnectionQueue = new EzySocketDisconnectionQueue() { + + BlockingQueue queue = new LinkedBlockingQueue<>(); + + @Override + public EzySocketDisconnection take() throws InterruptedException { + return queue.take(); + } + + @Override + public int size() { + return 0; + } + + @Override + public void remove(EzySocketDisconnection disconnection) { + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public void clear() { + } + + @Override + public boolean add(EzySocketDisconnection disconnection) { + return false; + } + }; + + EzySimpleConfig config = new EzySimpleConfig(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + settings.getUdp().setActive(true); + EzySimpleServer server = new EzySimpleServer(); + EzyServerControllers serverControllers = EzyServerControllersImpl.builder().build(); + server.setControllers(serverControllers); + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + server.setEventControllers(eventControllers); + server.setConfig(config); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setProperty(EzySocketUserRemovalQueue.class, new EzyBlockingSocketUserRemovalQueue()); + serverContext.setServer(server); + serverContext.init(); + + ExBootstrap localBootstrap = new ExBootstrap(new EzyBootstrap.Builder() + .context(serverContext)); + + EzyNioServerBootstrap bootstrap = new EzyNioServerBootstrap(); + bootstrap.setContext(serverContext); + bootstrap.setLocalBootstrap(localBootstrap); + bootstrap.setSslContext(sslContext); + bootstrap.setResponseApi(responseApi); + bootstrap.setStreamingApi(streamingApi); + bootstrap.setStreamQueue(streamQueue); + bootstrap.setHandlerGroupManager(handlerGroupManager); + bootstrap.setSocketSessionTicketsQueue(socketSessionTicketsQueue); + bootstrap.setWebsocketSessionTicketsQueue(websocketSessionTicketsQueue); + bootstrap.setSocketDisconnectionQueue(socketDisconnectionQueue); + bootstrap.setSocketSessionTicketsRequestQueues(sessionTicketsRequestQueues); + bootstrap.start(); + bootstrap.destroy(); + bootstrap.destroy(); + } + + @Test + public void startSocketServerBootstrapNotActive() { + // given + EzySimpleServer server = new EzySimpleServer(); + EzySimpleSettings settings = new EzySimpleSettings(); + settings.getSocket().setActive(false); + server.setSettings(settings); + + EzyServerContext context = mock(EzyServerContext.class); + when(context.getServer()).thenReturn(server); + + EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); + sut.setContext(context); + + // when + MethodUtil.invokeMethod("startSocketServerBootstrap", sut); + + // then + Asserts.assertNull(FieldUtil.getFieldValue(sut, "socketServerBootstrap")); + } + + @Test + public void startUdpServerBootstrapNotActive() { + // given + EzySimpleServer server = new EzySimpleServer(); + EzySimpleSettings settings = new EzySimpleSettings(); + settings.getUdp().setActive(false); + server.setSettings(settings); + + EzyServerContext context = mock(EzyServerContext.class); + when(context.getServer()).thenReturn(server); + + EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); + sut.setContext(context); + + // when + MethodUtil.invokeMethod("startUdpServerBootstrap", sut); + + // then + Asserts.assertNull(FieldUtil.getFieldValue(sut, "udpServerBootstrap")); + sut.destroy(); + } + + @Test + public void startWebSocketServerBootstrapNotActive() { + // given + EzySimpleServer server = new EzySimpleServer(); + EzySimpleSettings settings = new EzySimpleSettings(); + settings.getWebsocket().setActive(false); + server.setSettings(settings); + + EzyServerContext context = mock(EzyServerContext.class); + when(context.getServer()).thenReturn(server); + + EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); + sut.setContext(context); + + // when + MethodUtil.invokeMethod("startWebSocketServerBootstrap", sut); + + // then + Asserts.assertNull(FieldUtil.getFieldValue(sut, "websocketServerBootstrap")); + } + + @Test + public void startStreamHandlingLoopHandlersNotActive() { + // given + EzySimpleServer server = new EzySimpleServer(); + EzySimpleSettings settings = new EzySimpleSettings(); + settings.getStreaming().setEnable(false); + server.setSettings(settings); + + EzyServerContext context = mock(EzyServerContext.class); + when(context.getServer()).thenReturn(server); + + EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); + sut.setContext(context); + + // when + MethodUtil.invokeMethod("startStreamHandlingLoopHandlers", sut); + + // then + Asserts.assertNull(FieldUtil.getFieldValue(sut, "streamHandlingLoopHandler")); + } + + @Test + public void destroySocketDataReceiver() { + // given + EzySocketDataReceiver dataReceiver = mock(EzySocketDataReceiver.class); + + EzyNioServerBootstrap sut = new EzyNioServerBootstrap(); + sut.setSocketDataReceiver(dataReceiver); + + // when + sut.destroy(); + + // then + verify(dataReceiver, times(1)).destroy(); + } + + public static class ExBootstrap extends EzyBootstrap { + + protected ExBootstrap(Builder builder) { + super(builder); + } + + @Override + public void start() throws Exception { + } + + } + + public static class ExServerReadyController implements EzyServerReadyController { + + @Override + public void handle(EzyServerContext ctx, EzyServerReadyEvent event) { + } + + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioStarterTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioStarterTest.java index 179dc7282..67bf6ea91 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioStarterTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyNioStarterTest.java @@ -13,46 +13,46 @@ public class EzyNioStarterTest extends BaseTest { - @Test - public void test() throws Exception { - EzyNioStarter starter = (EzyNioStarter) EzyNioStarter.builder() - .build(); - starter = (EzyNioStarter) new ExEzyNioStarter.Builder() - .configFile("test.properties") - .build(); - MethodInvoker.create() - .object(starter) - .method("newServerBootstrapBuilder") - .invoke(); - MethodInvoker.create() - .object(starter) - .method("newSessionManagerBuilder") - .param(EzySettings.class, new EzySimpleSettings()) - .invoke(); - } - - public static class ExEzyNioStarter extends EzyNioStarter { - - @Override - protected EzyConfig readConfig(String configFile) throws Exception { - EzySimpleConfig config = new EzySimpleConfig(); - return config; - } - - @Override - protected void setSystemProperties(EzyConfig config) { - } - - protected ExEzyNioStarter(Builder builder) { - super(builder); - } - - public static class Builder extends EzyNioStarter.Builder { - @Override - public EzyStarter build() { - return new ExEzyNioStarter(this); - } - } - - } + @Test + public void test() throws Exception { + EzyNioStarter starter = (EzyNioStarter) EzyNioStarter.builder() + .build(); + starter = (EzyNioStarter) new ExEzyNioStarter.Builder() + .configFile("test.properties") + .build(); + MethodInvoker.create() + .object(starter) + .method("newServerBootstrapBuilder") + .invoke(); + MethodInvoker.create() + .object(starter) + .method("newSessionManagerBuilder") + .param(EzySettings.class, new EzySimpleSettings()) + .invoke(); + } + + public static class ExEzyNioStarter extends EzyNioStarter { + + @Override + protected EzyConfig readConfig(String configFile) throws Exception { + EzySimpleConfig config = new EzySimpleConfig(); + return config; + } + + @Override + protected void setSystemProperties(EzyConfig config) { + } + + protected ExEzyNioStarter(Builder builder) { + super(builder); + } + + public static class Builder extends EzyNioStarter.Builder { + @Override + public EzyStarter build() { + return new ExEzyNioStarter(this); + } + } + + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyUdpServerBootstrapTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyUdpServerBootstrapTest.java index 975f0ee04..a54f76617 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyUdpServerBootstrapTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyUdpServerBootstrapTest.java @@ -12,22 +12,22 @@ public class EzyUdpServerBootstrapTest { - @Test - public void test() throws Exception { - EzySimpleServerContext context = new EzySimpleServerContext(); - EzySimpleServer server = new EzySimpleServer(); - EzySimpleSettings settings = new EzySimpleSettings(); - server.setSettings(settings); - context.setServer(server); - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzyUdpServerBootstrap bootstrap = EzyUdpServerBootstrap.builder() - .serverContext(context) - .handlerGroupManager(handlerGroupManager) - .build(); - bootstrap.start(); - Thread.sleep(250); - bootstrap.destroy(); - - } - + @Test + public void test() throws Exception { + EzySimpleServerContext context = new EzySimpleServerContext(); + EzySimpleServer server = new EzySimpleServer(); + EzySimpleSettings settings = new EzySimpleSettings(); + server.setSettings(settings); + context.setServer(server); + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzyUdpServerBootstrap bootstrap = EzyUdpServerBootstrap.builder() + .serverContext(context) + .handlerGroupManager(handlerGroupManager) + .build(); + bootstrap.start(); + Thread.sleep(250); + bootstrap.destroy(); + + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyWebSocketServerBootstrapTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyWebSocketServerBootstrapTest.java index 453dfb7d7..48dc82a83 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyWebSocketServerBootstrapTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/EzyWebSocketServerBootstrapTest.java @@ -16,30 +16,30 @@ public class EzyWebSocketServerBootstrapTest { - @Test - public void newSocketServerCreatorWithSSL() { - // given - SSLContext sslContext = mock(SSLContext.class); - - EzyServerContext serverContext = mock(EzyServerContext.class); - - EzySimpleServer server = new EzySimpleServer(); - when(serverContext.getServer()).thenReturn(server); - - EzySimpleSettings settings = new EzySimpleSettings(); - settings.getWebsocket().setSslActive(true); - server.setSettings(settings); - - EzyWebSocketServerBootstrap sut = EzyWebSocketServerBootstrap.builder() - .sslContext(sslContext) - .serverContext(serverContext) - .build(); - - // when - EzyWebSocketServerCreator creator = MethodUtil.invokeMethod("newSocketServerCreator", sut); - - // then - Asserts.assertNotNull(creator); - } - + @Test + public void newSocketServerCreatorWithSSL() { + // given + SSLContext sslContext = mock(SSLContext.class); + + EzyServerContext serverContext = mock(EzyServerContext.class); + + EzySimpleServer server = new EzySimpleServer(); + when(serverContext.getServer()).thenReturn(server); + + EzySimpleSettings settings = new EzySimpleSettings(); + settings.getWebsocket().setSslActive(true); + server.setSettings(settings); + + EzyWebSocketServerBootstrap sut = EzyWebSocketServerBootstrap.builder() + .sslContext(sslContext) + .serverContext(serverContext) + .build(); + + // when + EzyWebSocketServerCreator creator = MethodUtil.invokeMethod("newSocketServerCreator", sut); + + // then + Asserts.assertNotNull(creator); + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/Websock.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/Websock.java index 8c257b0a0..a7b272081 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/Websock.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/Websock.java @@ -13,54 +13,54 @@ import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; public class Websock { - private static class Adapter extends WebSocketAdapter { - @Override - public void onWebSocketConnect(Session sess) { - System.out.print("client connected"); - } - - @Override - public void onWebSocketBinary(byte[] payload, int offset, int len) { - System.out.println("onWebSocketBinary"); - } - - @Override - public void onWebSocketText(String message) { - System.out.println("onWebSocketText"); - } - } + private static class Adapter extends WebSocketAdapter { + @Override + public void onWebSocketConnect(Session sess) { + System.out.print("client connected"); + } - public static void main(String[] args) throws Exception { - Server server = new Server(2208); + @Override + public void onWebSocketBinary(byte[] payload, int offset, int len) { + System.out.println("onWebSocketBinary"); + } - // needed. + @Override + public void onWebSocketText(String message) { + System.out.println("onWebSocketText"); + } + } - ContextHandlerCollection handlerCollection = new ContextHandlerCollection(); - handlerCollection.addHandler(createWebsocketHandler()); + public static void main(String[] args) throws Exception { + Server server = new Server(2208); - server.setHandler(handlerCollection); + // needed. - server.start(); - } + ContextHandlerCollection handlerCollection = new ContextHandlerCollection(); + handlerCollection.addHandler(createWebsocketHandler()); - private static ContextHandler createWebsocketHandler() { - ContextHandler contextHandler = new ContextHandler("/ws"); - contextHandler.setAllowNullPathInfo(true); // disable redirect from /ws - // to /ws/ + server.setHandler(handlerCollection); - final WebSocketCreator webSocketcreator = new WebSocketCreator() { - public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) { - return new Adapter(); - } - }; + server.start(); + } - Handler webSocketHandler = new WebSocketHandler() { - public void configure(WebSocketServletFactory factory) { - factory.setCreator(webSocketcreator); - } - }; + private static ContextHandler createWebsocketHandler() { + ContextHandler contextHandler = new ContextHandler("/ws"); + contextHandler.setAllowNullPathInfo(true); // disable redirect from /ws + // to /ws/ - contextHandler.setHandler(webSocketHandler); - return contextHandler; - } + final WebSocketCreator webSocketcreator = new WebSocketCreator() { + public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) { + return new Adapter(); + } + }; + + Handler webSocketHandler = new WebSocketHandler() { + public void configure(WebSocketServletFactory factory) { + factory.setCreator(webSocketcreator); + } + }; + + contextHandler.setHandler(webSocketHandler); + return contextHandler; + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyNioServerBootstrapBuilderImplTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyNioServerBootstrapBuilderImplTest.java index d645cd76e..ed53c1c07 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyNioServerBootstrapBuilderImplTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyNioServerBootstrapBuilderImplTest.java @@ -11,32 +11,32 @@ public class EzyNioServerBootstrapBuilderImplTest extends BaseTest { - @Test - public void test() { - EzySimpleConfig config = new EzySimpleConfig(); - EzySimpleSettings settings = new EzySimpleSettings(); - settings.getSocket().setCodecCreator(ExCodecCreator.class.getName()); - settings.getWebsocket().setCodecCreator(ExCodecCreator.class.getName()); - EzySimpleServer server = new EzySimpleServer(); - server.setConfig(config); - server.setSettings(settings); - EzyNioServerBootstrapBuilderImpl builder = new EzyNioServerBootstrapBuilderImpl(); - builder.server(server); - builder.build(); - } - - public static class ExCodecCreator implements EzyCodecCreator { - - @Override - public Object newEncoder() { - return null; - } - - @Override - public Object newDecoder(int maxRequestSize) { - return null; - } - - } - + @Test + public void test() { + EzySimpleConfig config = new EzySimpleConfig(); + EzySimpleSettings settings = new EzySimpleSettings(); + settings.getSocket().setCodecCreator(ExCodecCreator.class.getName()); + settings.getWebsocket().setCodecCreator(ExCodecCreator.class.getName()); + EzySimpleServer server = new EzySimpleServer(); + server.setConfig(config); + server.setSettings(settings); + EzyNioServerBootstrapBuilderImpl builder = new EzyNioServerBootstrapBuilderImpl(); + builder.server(server); + builder.build(); + } + + public static class ExCodecCreator implements EzyCodecCreator { + + @Override + public Object newEncoder() { + return null; + } + + @Override + public Object newDecoder(int maxRequestSize) { + return null; + } + + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketSecureServerCreatorTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketSecureServerCreatorTest.java index 1d69b0910..10a56a81b 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketSecureServerCreatorTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketSecureServerCreatorTest.java @@ -13,25 +13,25 @@ public class EzyWebSocketSecureServerCreatorTest extends BaseTest { - @Test - public void test() throws Exception { - SSLContext sslContext = SSLContext.getDefault(); - EzySimpleWebSocketSetting webSocketSetting = new EzySimpleWebSocketSetting(); - EzyWebSocketSecureServerCreator creator = new EzyWebSocketSecureServerCreator(sslContext); - creator.setting(webSocketSetting); - creator.create(); - - EzyWsHandler wsHandler = MethodInvoker.create() - .object(creator) - .method("newWsHandler") - .invoke(EzyWsHandler.class); - - WebSocketCreator webSocketCreator = MethodInvoker.create() - .object(creator) - .method("newWebSocketCreator") - .param(EzyWsHandler.class, wsHandler) - .invoke(WebSocketCreator.class); - webSocketCreator.createWebSocket(null, null); - } - + @Test + public void test() throws Exception { + SSLContext sslContext = SSLContext.getDefault(); + EzySimpleWebSocketSetting webSocketSetting = new EzySimpleWebSocketSetting(); + EzyWebSocketSecureServerCreator creator = new EzyWebSocketSecureServerCreator(sslContext); + creator.setting(webSocketSetting); + creator.create(); + + EzyWsHandler wsHandler = MethodInvoker.create() + .object(creator) + .method("newWsHandler") + .invoke(EzyWsHandler.class); + + WebSocketCreator webSocketCreator = MethodInvoker.create() + .object(creator) + .method("newWebSocketCreator") + .param(EzyWsHandler.class, wsHandler) + .invoke(WebSocketCreator.class); + webSocketCreator.createWebSocket(null, null); + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketServerCreatorTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketServerCreatorTest.java index 5e1b3c0f6..986252e88 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketServerCreatorTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/builder/EzyWebSocketServerCreatorTest.java @@ -15,49 +15,49 @@ public class EzyWebSocketServerCreatorTest { - @Test - public void createManagementTest() { - // given - EzyWebSocketServerCreator creator = new EzyWebSocketServerCreator(); - EzySimpleWebSocketSetting webSocketSetting = new EzySimpleWebSocketSetting(); - webSocketSetting.setManagementEnable(true); - - creator.setting(webSocketSetting); - - // when - creator.create(); - - // then - EzyWsHandler wsHandler = MethodInvoker.create() - .object(creator) - .method("newWsHandler") - .invoke(EzyWsHandler.class); - - WebSocketCreator webSocketCreator = MethodInvoker.create() - .object(creator) - .method("newWebSocketCreator") - .param(EzyWsHandler.class, wsHandler) - .invoke(WebSocketCreator.class); - webSocketCreator.createWebSocket(null, null); - } - - @Test - public void healthCheckServletTest() { - // given - HealthCheckServlet sut = new HealthCheckServlet(); - - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - - // when - MethodInvoker.create() - .object(sut) - .method("doGet") - .param(HttpServletRequest.class, request) - .param(HttpServletResponse.class, response) - .call(); - - // then - verify(response, times(1)).setStatus(200); - } + @Test + public void createManagementTest() { + // given + EzyWebSocketServerCreator creator = new EzyWebSocketServerCreator(); + EzySimpleWebSocketSetting webSocketSetting = new EzySimpleWebSocketSetting(); + webSocketSetting.setManagementEnable(true); + + creator.setting(webSocketSetting); + + // when + creator.create(); + + // then + EzyWsHandler wsHandler = MethodInvoker.create() + .object(creator) + .method("newWsHandler") + .invoke(EzyWsHandler.class); + + WebSocketCreator webSocketCreator = MethodInvoker.create() + .object(creator) + .method("newWebSocketCreator") + .param(EzyWsHandler.class, wsHandler) + .invoke(WebSocketCreator.class); + webSocketCreator.createWebSocket(null, null); + } + + @Test + public void healthCheckServletTest() { + // given + HealthCheckServlet sut = new HealthCheckServlet(); + + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + + // when + MethodInvoker.create() + .object(sut) + .method("doGet") + .param(HttpServletRequest.class, request) + .param(HttpServletResponse.class, response) + .call(); + + // then + verify(response, times(1)).setStatus(200); + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzyAbstractHandlerGroupTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzyAbstractHandlerGroupTest.java index 441dd84eb..4f92edba4 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzyAbstractHandlerGroupTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzyAbstractHandlerGroupTest.java @@ -61,332 +61,332 @@ public class EzyAbstractHandlerGroupTest extends BaseTest { - @SuppressWarnings("rawtypes") - @Test - public void test() throws Exception { - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - when(channel.write(any(ByteBuffer.class), anyBoolean())).thenReturn(123456); - - ExHandlerGroup group = (ExHandlerGroup) new ExHandlerGroup.Builder() - .session(session) - .decoder(decoder) - .sessionCount(new AtomicInteger()) - .networkStats((EzyNetworkStats) statistics.getSocketStats().getNetworkStats()) - .sessionStats((EzySessionStats) statistics.getSocketStats().getSessionStats()) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - - EzyChannel channelX = mock(EzyChannel.class); - MethodInvoker.create() - .object(group) - .method("canWriteBytes") - .param(EzyChannel.class, null) - .invoke(); - MethodInvoker.create() - .object(group) - .method("canWriteBytes") - .param(EzyChannel.class, channelX) - .invoke(); - - sessionTicketsRequestQueues = mock(EzySessionTicketsRequestQueues.class); - when(sessionTicketsRequestQueues.addRequest(any())).thenReturn(false); - group = (ExHandlerGroup) new ExHandlerGroup.Builder() - .session(session) - .decoder(decoder) - .sessionCount(new AtomicInteger()) - .networkStats((EzyNetworkStats) statistics.getSocketStats().getNetworkStats()) - .sessionStats((EzySessionStats) statistics.getSocketStats().getSessionStats()) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - - MethodInvoker.create() - .object(group) - .method("handleReceivedData") - .param(Object.class, EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .append(EzyEntityFactory.EMPTY_OBJECT) - .build()) - .param(int.class, 100) - .invoke(); - - ((EzyDatagramChannelPoolAware)session).setDatagramChannelPool(new EzyDatagramChannelPool(1)); - ((EzyUdpClientAddressAware)session).setUdpClientAddress(new InetSocketAddress("127.0.0.1", 12348)); - - EzyPacket packet = mock(EzyPacket.class); - when(packet.getData()).thenReturn(new byte[] {1, 2, 3}); - ByteBuffer buffer = ByteBuffer.allocate(100); - MethodInvoker.create() - .object(group) - .method("executeSendingPacket") - .param(EzyPacket.class, packet) - .param(Object.class, buffer) - .invoke(); - - MethodInvoker.create() - .object(group) - .method("executeSendingPacket") - .param(EzyPacket.class, packet) - .param(Object.class, new Object()) - .invoke(); - - Asserts.assertNotNull(group.getSession()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void fireChannelInactiveException() throws Exception { - // given - ExHandlerGroup sut = newHandlerGroup(); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - - EzyNioDataHandler handler = FieldUtil.getFieldValue(sut, "handler"); - EzySessionManager sessionManager = FieldUtil.getFieldValue(handler, "sessionManager"); - doThrow(new RuntimeException()).when(sessionManager).clearSession(session); - - // when - sut.fireChannelInactive(EzyDisconnectReason.ADMIN_BAN); - - // then - verify(sessionManager, times(1)).clearSession(session); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void fireExceptionCaughtException() throws Exception { - // given - ExHandlerGroup sut = newHandlerGroup(); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - - EzyNioDataHandler handler = FieldUtil.getFieldValue(sut, "handler"); - EzySessionManager sessionManager = FieldUtil.getFieldValue(handler, "sessionManager"); - doThrow(new RuntimeException()).when(sessionManager).removeSession(session, MAX_REQUEST_SIZE); - - EzyMaxRequestSizeException exception = new EzyMaxRequestSizeException("just test"); - - // when - sut.fireExceptionCaught(exception); - - // then - verify(sessionManager, times(1)).removeSession(session, MAX_REQUEST_SIZE); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void hasMaxRequestPerSecondTest() throws Exception { - // given - ExHandlerGroup sut = newHandlerGroup(); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - when(session.addReceviedRequests(1)).thenReturn(true); - - EzyNioDataHandler handler = FieldUtil.getFieldValue(sut, "handler"); - EzySessionManager sessionManager = FieldUtil.getFieldValue(handler, "sessionManager"); - - EzySimpleMaxRequestPerSecond maxRequestPerSecond = - FieldUtil.getFieldValue(handler, "maxRequestPerSecond"); - - maxRequestPerSecond.setAction(EzyMaxRequestPerSecondAction.DISCONNECT_SESSION); - - EzyArray data = EzyEntityFactory.newArray(); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedData") - .param(Object.class, data) - .param(int.class, 100) - .call(); - - // then - verify(sessionManager, times(1)).removeSession(session, MAX_REQUEST_PER_SECOND); - } - - @Test - public void handleReceivedDataNotSuccess() throws Exception { - // given - ExHandlerGroup sut = newHandlerGroup(); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - when(session.addReceviedRequests(1)).thenReturn(false); - when(session.isActivated()).thenReturn(true); - - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = - FieldUtil.getFieldValue(sut, "sessionTicketsRequestQueues"); - - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.APP_ACCESS.getId()) - .append(EzyEntityFactory.newArray()) - .build(); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedData") - .param(Object.class, data) - .param(int.class, 100) - .call(); - - // then - verify(sessionTicketsRequestQueues, times(1)).addRequest(any()); - } - - @Test - public void executeSendingPacketCanNotWriteBytes() throws Exception { - // given - ExHandlerGroup sut = newHandlerGroup(); - EzyPacket packet = mock(EzyPacket.class); - ByteBuffer writeBuffer = ByteBuffer.wrap(new byte[0]); - - // when - MethodInvoker.create() - .object(sut) - .method("executeSendingPacket") - .param(EzyPacket.class, packet) - .param(Object.class, writeBuffer) - .call(); - - // then - EzySession session = FieldUtil.getFieldValue(sut, "session"); - verify(session, times(3)).getChannel(); - } - - @Test - public void writeUdpPacketToSocketClientAddress() throws Exception { - // given - ExHandlerGroup sut = newHandlerGroup(); - EzyPacket packet = mock(EzyPacket.class); - ByteBuffer writeBuffer = ByteBuffer.wrap(new byte[0]); - - EzyDatagramChannelPool udpChannelPool = mock(EzyDatagramChannelPool.class); - EzySession session = FieldUtil.getFieldValue(sut, "session"); - when(session.getDatagramChannelPool()).thenReturn(udpChannelPool); - - // when - MethodInvoker.create() - .object(sut) - .method("writeUdpPacketToSocket") - .param(EzyPacket.class, packet) - .param(Object.class, writeBuffer) - .call(); - - // then - verify(session, times(1)).getDatagramChannelPool(); - } - - @Test - public void getWriteBufferMaxTest() throws Exception { - // given - ExHandlerGroup sut = newHandlerGroup(); - ByteBuffer fixed = ByteBuffer.allocate(1); - int bytesToWrite = 10; - - // when - ByteBuffer buffer = MethodInvoker.create() - .object(sut) - .method("getWriteBuffer") - .param(ByteBuffer.class, fixed) - .param(int.class, bytesToWrite) - .call(); - - // then - Asserts.assertEquals(bytesToWrite, buffer.capacity()); - } - - @SuppressWarnings("rawtypes") - private ExHandlerGroup newHandlerGroup() throws Exception { - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - - EzySimpleSession session = mock(EzySimpleSession.class); - - EzySessionManager sessionManager = mock(EzySessionManager.class); - server.setSessionManager(sessionManager); - - EzyResponseApi responseApi = mock(EzyResponseApi.class); - server.setResponseApi(responseApi); - - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = mock(EzySessionTicketsRequestQueues.class); - - when(channel.write(any(ByteBuffer.class), anyBoolean())).thenReturn(123456); - - ExHandlerGroup group = (ExHandlerGroup) new ExHandlerGroup.Builder() - .session(session) - .decoder(decoder) - .sessionCount(new AtomicInteger()) - .networkStats((EzyNetworkStats) statistics.getSocketStats().getNetworkStats()) - .sessionStats((EzySessionStats) statistics.getSocketStats().getSessionStats()) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - return group; - } - - @SuppressWarnings("rawtypes") - public static class ExHandlerGroup - extends EzyAbstractHandlerGroup - implements EzyHandlerGroup { - - @Override - protected EzyDestroyable newDecoder(Object decoder) { - return null; - } - - protected ExHandlerGroup(Builder builder) { - super(builder); - } - - public static class Builder extends EzyAbstractHandlerGroup.Builder { - - @Override - public ExHandlerGroup build() { - return new ExHandlerGroup(this); - } - - } - - } - + @SuppressWarnings("rawtypes") + @Test + public void test() throws Exception { + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + when(channel.write(any(ByteBuffer.class), anyBoolean())).thenReturn(123456); + + ExHandlerGroup group = (ExHandlerGroup) new ExHandlerGroup.Builder() + .session(session) + .decoder(decoder) + .sessionCount(new AtomicInteger()) + .networkStats((EzyNetworkStats) statistics.getSocketStats().getNetworkStats()) + .sessionStats((EzySessionStats) statistics.getSocketStats().getSessionStats()) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + + EzyChannel channelX = mock(EzyChannel.class); + MethodInvoker.create() + .object(group) + .method("canWriteBytes") + .param(EzyChannel.class, null) + .invoke(); + MethodInvoker.create() + .object(group) + .method("canWriteBytes") + .param(EzyChannel.class, channelX) + .invoke(); + + sessionTicketsRequestQueues = mock(EzySessionTicketsRequestQueues.class); + when(sessionTicketsRequestQueues.addRequest(any())).thenReturn(false); + group = (ExHandlerGroup) new ExHandlerGroup.Builder() + .session(session) + .decoder(decoder) + .sessionCount(new AtomicInteger()) + .networkStats((EzyNetworkStats) statistics.getSocketStats().getNetworkStats()) + .sessionStats((EzySessionStats) statistics.getSocketStats().getSessionStats()) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + + MethodInvoker.create() + .object(group) + .method("handleReceivedData") + .param(Object.class, EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .append(EzyEntityFactory.EMPTY_OBJECT) + .build()) + .param(int.class, 100) + .invoke(); + + ((EzyDatagramChannelPoolAware)session).setDatagramChannelPool(new EzyDatagramChannelPool(1)); + ((EzyUdpClientAddressAware)session).setUdpClientAddress(new InetSocketAddress("127.0.0.1", 12348)); + + EzyPacket packet = mock(EzyPacket.class); + when(packet.getData()).thenReturn(new byte[] {1, 2, 3}); + ByteBuffer buffer = ByteBuffer.allocate(100); + MethodInvoker.create() + .object(group) + .method("executeSendingPacket") + .param(EzyPacket.class, packet) + .param(Object.class, buffer) + .invoke(); + + MethodInvoker.create() + .object(group) + .method("executeSendingPacket") + .param(EzyPacket.class, packet) + .param(Object.class, new Object()) + .invoke(); + + Asserts.assertNotNull(group.getSession()); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void fireChannelInactiveException() throws Exception { + // given + ExHandlerGroup sut = newHandlerGroup(); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + + EzyNioDataHandler handler = FieldUtil.getFieldValue(sut, "handler"); + EzySessionManager sessionManager = FieldUtil.getFieldValue(handler, "sessionManager"); + doThrow(new RuntimeException()).when(sessionManager).clearSession(session); + + // when + sut.fireChannelInactive(EzyDisconnectReason.ADMIN_BAN); + + // then + verify(sessionManager, times(1)).clearSession(session); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void fireExceptionCaughtException() throws Exception { + // given + ExHandlerGroup sut = newHandlerGroup(); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + + EzyNioDataHandler handler = FieldUtil.getFieldValue(sut, "handler"); + EzySessionManager sessionManager = FieldUtil.getFieldValue(handler, "sessionManager"); + doThrow(new RuntimeException()).when(sessionManager).removeSession(session, MAX_REQUEST_SIZE); + + EzyMaxRequestSizeException exception = new EzyMaxRequestSizeException("just test"); + + // when + sut.fireExceptionCaught(exception); + + // then + verify(sessionManager, times(1)).removeSession(session, MAX_REQUEST_SIZE); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void hasMaxRequestPerSecondTest() throws Exception { + // given + ExHandlerGroup sut = newHandlerGroup(); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + when(session.addReceviedRequests(1)).thenReturn(true); + + EzyNioDataHandler handler = FieldUtil.getFieldValue(sut, "handler"); + EzySessionManager sessionManager = FieldUtil.getFieldValue(handler, "sessionManager"); + + EzySimpleMaxRequestPerSecond maxRequestPerSecond = + FieldUtil.getFieldValue(handler, "maxRequestPerSecond"); + + maxRequestPerSecond.setAction(EzyMaxRequestPerSecondAction.DISCONNECT_SESSION); + + EzyArray data = EzyEntityFactory.newArray(); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedData") + .param(Object.class, data) + .param(int.class, 100) + .call(); + + // then + verify(sessionManager, times(1)).removeSession(session, MAX_REQUEST_PER_SECOND); + } + + @Test + public void handleReceivedDataNotSuccess() throws Exception { + // given + ExHandlerGroup sut = newHandlerGroup(); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + when(session.addReceviedRequests(1)).thenReturn(false); + when(session.isActivated()).thenReturn(true); + + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = + FieldUtil.getFieldValue(sut, "sessionTicketsRequestQueues"); + + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.APP_ACCESS.getId()) + .append(EzyEntityFactory.newArray()) + .build(); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedData") + .param(Object.class, data) + .param(int.class, 100) + .call(); + + // then + verify(sessionTicketsRequestQueues, times(1)).addRequest(any()); + } + + @Test + public void executeSendingPacketCanNotWriteBytes() throws Exception { + // given + ExHandlerGroup sut = newHandlerGroup(); + EzyPacket packet = mock(EzyPacket.class); + ByteBuffer writeBuffer = ByteBuffer.wrap(new byte[0]); + + // when + MethodInvoker.create() + .object(sut) + .method("executeSendingPacket") + .param(EzyPacket.class, packet) + .param(Object.class, writeBuffer) + .call(); + + // then + EzySession session = FieldUtil.getFieldValue(sut, "session"); + verify(session, times(3)).getChannel(); + } + + @Test + public void writeUdpPacketToSocketClientAddress() throws Exception { + // given + ExHandlerGroup sut = newHandlerGroup(); + EzyPacket packet = mock(EzyPacket.class); + ByteBuffer writeBuffer = ByteBuffer.wrap(new byte[0]); + + EzyDatagramChannelPool udpChannelPool = mock(EzyDatagramChannelPool.class); + EzySession session = FieldUtil.getFieldValue(sut, "session"); + when(session.getDatagramChannelPool()).thenReturn(udpChannelPool); + + // when + MethodInvoker.create() + .object(sut) + .method("writeUdpPacketToSocket") + .param(EzyPacket.class, packet) + .param(Object.class, writeBuffer) + .call(); + + // then + verify(session, times(1)).getDatagramChannelPool(); + } + + @Test + public void getWriteBufferMaxTest() throws Exception { + // given + ExHandlerGroup sut = newHandlerGroup(); + ByteBuffer fixed = ByteBuffer.allocate(1); + int bytesToWrite = 10; + + // when + ByteBuffer buffer = MethodInvoker.create() + .object(sut) + .method("getWriteBuffer") + .param(ByteBuffer.class, fixed) + .param(int.class, bytesToWrite) + .call(); + + // then + Asserts.assertEquals(bytesToWrite, buffer.capacity()); + } + + @SuppressWarnings("rawtypes") + private ExHandlerGroup newHandlerGroup() throws Exception { + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + + EzySimpleSession session = mock(EzySimpleSession.class); + + EzySessionManager sessionManager = mock(EzySessionManager.class); + server.setSessionManager(sessionManager); + + EzyResponseApi responseApi = mock(EzyResponseApi.class); + server.setResponseApi(responseApi); + + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = mock(EzySessionTicketsRequestQueues.class); + + when(channel.write(any(ByteBuffer.class), anyBoolean())).thenReturn(123456); + + ExHandlerGroup group = (ExHandlerGroup) new ExHandlerGroup.Builder() + .session(session) + .decoder(decoder) + .sessionCount(new AtomicInteger()) + .networkStats((EzyNetworkStats) statistics.getSocketStats().getNetworkStats()) + .sessionStats((EzySessionStats) statistics.getSocketStats().getSessionStats()) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + return group; + } + + @SuppressWarnings("rawtypes") + public static class ExHandlerGroup + extends EzyAbstractHandlerGroup + implements EzyHandlerGroup { + + @Override + protected EzyDestroyable newDecoder(Object decoder) { + return null; + } + + protected ExHandlerGroup(Builder builder) { + super(builder); + } + + public static class Builder extends EzyAbstractHandlerGroup.Builder { + + @Override + public ExHandlerGroup build() { + return new ExHandlerGroup(this); + } + + } + + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioHandlerGroupTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioHandlerGroupTest.java index 9fc880ac6..6c2be4f80 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioHandlerGroupTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioHandlerGroupTest.java @@ -61,468 +61,468 @@ public class EzySimpleNioHandlerGroupTest extends BaseTest { - @SuppressWarnings("rawtypes") - @Test - public void test() throws Exception { - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .codecFactory(new ExCodecFactory()) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .build(); - - EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.SOCKET) - .build(); - - group.fireBytesReceived("hello".getBytes()); - EzySimplePacket packet = new EzySimplePacket(); - packet.setBinary(true); - packet.setData("world".getBytes()); - packet.setTransportType(EzyTransportType.TCP); - ByteBuffer writeBuffer = ByteBuffer.allocate(1024); - group.firePacketSend(packet, writeBuffer); - group.sendPacketNow(packet); - group.fireChannelRead(EzyCommand.PING, EzyEntityArrays.newArray(EzyCommand.PING.getId(), EzyEntityFactory.EMPTY_ARRAY)); - group.fireStreamBytesReceived(new byte[] {0, 1, 2}); - EzyPacket droppedPacket = mock(EzyPacket.class); - when(droppedPacket.getSize()).thenReturn(12); - group.addDroppedPacket(droppedPacket); - EzyPacket failedPacket = mock(EzyPacket.class); - when(failedPacket.getData()).thenReturn(new byte[] {1, 2, 3}); - when(failedPacket.isBinary()).thenReturn(true); - when(channel.write(any(ByteBuffer.class), anyBoolean())).thenThrow(new IllegalStateException("maintain")); - group.firePacketSend(failedPacket, writeBuffer); - group.fireChannelInactive(); - Thread.sleep(2000); - group.destroy(); - group.destroy(); - - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.SOCKET) - .session(session) - .streamQueue(streamQueue) - .decoder(new ExStreamEzyByteToObjectDecoder()) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - ((EzyAbstractSession)session).setStreamingEnable(false); - group.fireBytesReceived("hello".getBytes()); - Thread.sleep(500); - ((EzyAbstractSession)session).setStreamingEnable(true); - group.fireBytesReceived("hello".getBytes()); - Thread.sleep(1000); - - streamQueue = mock(EzySocketStreamQueue.class); - when(streamQueue.add(any())).thenThrow(new IllegalStateException("maintain")); - group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.SOCKET) - .session(session) - .streamQueue(streamQueue) - .decoder(new ExStreamEzyByteToObjectDecoder()) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - group.fireBytesReceived("hello".getBytes()); - Thread.sleep(1000); - - group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.SOCKET) - .session(session) - .decoder(new ErrorEzyByteToObjectDecoder()) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - group.fireBytesReceived("hello".getBytes()); - group.fireMessageReceived(mock(EzyMessage.class)); - Thread.sleep(300); - } - - @SuppressWarnings("rawtypes") - @Test - public void writeSuccessTest() throws Exception { - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - when(channel.write(any(ByteBuffer.class), anyBoolean())).thenReturn(123456); - - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .codecFactory(new ExCodecFactory()) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .build(); - - EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.SOCKET) - .session(session) - .decoder(decoder) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - EzySimplePacket packet = new EzySimplePacket(); - packet.setBinary(true); - packet.setData("world".getBytes()); - packet.setTransportType(EzyTransportType.TCP); - ByteBuffer writeBuffer = ByteBuffer.allocate(1024); - group.firePacketSend(packet, writeBuffer); - Thread.sleep(1000); - } - - @SuppressWarnings("rawtypes") - @Test - public void writeFailureTest() throws Exception { - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - SelectionKey selectionKey = mock(SelectionKey.class); - when(selectionKey.isValid()).thenReturn(true); - session.setProperty(EzyNioSession.SELECTION_KEY, selectionKey); - - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .codecFactory(new ExCodecFactory()) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .build(); - - EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.SOCKET) - .session(session) - .decoder(decoder) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - EzySimplePacket packet = new EzySimplePacket(); - packet.setBinary(true); - packet.setData("world".getBytes()); - packet.setTransportType(EzyTransportType.TCP); - ByteBuffer writeBuffer = ByteBuffer.allocate(1024); - group.firePacketSend(packet, writeBuffer); - Thread.sleep(1000); - } - - @Test - public void handleReceivedMesssageHeaderIsNotRawBytes() throws Exception { - // given - EzySimpleNioHandlerGroup sut = newHandlerGroup(); - - EzyMessage message = mock(EzyMessage.class); - EzyMessageHeader header = mock(EzyMessageHeader.class); - when(message.getHeader()).thenReturn(header); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedMesssage") - .param(EzyMessage.class, message) - .call(); - - // then - verify(header, times(1)).isRawBytes(); - - EzySimpleMessageDataDecoder decoder = FieldUtil.getFieldValue(sut, "decoder"); - EzyByteToObjectDecoder d = FieldUtil.getFieldValue(decoder, "decoder"); - EzySession session = FieldUtil.getFieldValue(sut, "session"); - verify(d, times(1)).decode(message, session.getSessionKey()); - } - - @Test - public void handleReceivedMesssageStreamingNotEnable() throws Exception { - // given - EzySimpleNioHandlerGroup sut = newHandlerGroup(false); - - EzyMessage message = mock(EzyMessage.class); - EzyMessageHeader header = mock(EzyMessageHeader.class); - when(header.isRawBytes()).thenReturn(true); - when(message.getHeader()).thenReturn(header); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedMesssage") - .param(EzyMessage.class, message) - .call(); - - // then - verify(header, times(1)).isRawBytes(); - } - - @Test - public void handleReceivedMesssageSessionStreamingNotEnable() throws Exception { - // given - EzySimpleNioHandlerGroup sut = newHandlerGroup(); - - EzyMessage message = mock(EzyMessage.class); - EzyMessageHeader header = mock(EzyMessageHeader.class); - when(header.isRawBytes()).thenReturn(true); - when(message.getHeader()).thenReturn(header); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - when(session.isStreamingEnable()).thenReturn(false); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedMesssage") - .param(EzyMessage.class, message) - .call(); - - // then - verify(header, times(1)).isRawBytes(); - verify(session, times(1)).isStreamingEnable(); - } - - @Test - public void writePacketToSocketSessionKeyIsInvalid() throws Exception { - // given - EzySimpleNioHandlerGroup sut = newHandlerGroup(); - - EzyNioSession session = FieldUtil.getFieldValue(sut, "session"); - SelectionKey selectionKey = mock(SelectionKey.class); - when(session.getSelectionKey()).thenReturn(selectionKey); - when(selectionKey.isValid()).thenReturn(false); - - - EzyPacket packet = mock(EzyPacket.class); - when(packet.getData()).thenReturn(new byte[] {1, 2, 3, 5}); - when(packet.isBinary()).thenReturn(true); - - ByteBuffer writeBuffer = ByteBuffer.allocate(5); - - // when - MethodInvoker.create() - .object(sut) - .method("writePacketToSocket") - .param(EzyPacket.class, packet) - .param(Object.class, writeBuffer) - .call(); - - // then - verify(session, times(1)).getSelectionKey(); - verify(selectionKey, times(1)).isValid(); - } - - private EzySimpleNioHandlerGroup newHandlerGroup() throws IOException { - return newHandlerGroup(true); - } - - @SuppressWarnings("rawtypes") - private EzySimpleNioHandlerGroup newHandlerGroup(boolean streamEnable) throws IOException { - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(streamEnable); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); - EzySimpleSession session = mock(EzySimpleSession.class); - when(session.getChannel()).thenReturn(channel); - - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - SelectionKey selectionKey = mock(SelectionKey.class); - when(selectionKey.isValid()).thenReturn(true); - when(session.getProperty(EzyNioSession.SELECTION_KEY)).thenReturn(selectionKey); - - EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); - EzyByteToObjectDecoder decoder = mock(EzyByteToObjectDecoder.class); - when(codecFactory.newDecoder(any())).thenReturn(decoder); - - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .codecFactory(codecFactory) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .build(); - - EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.SOCKET) - .session(session) - .decoder(decoder) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - return group; - } - - public static class ExEzyByteToObjectDecoder implements EzyByteToObjectDecoder { - - @Override - public void reset() {} - - @Override - public Object decode(EzyMessage message) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - @Override - public void decode(ByteBuffer bytes, Queue queue) throws Exception { - EzyMessageHeader header = new EzySimpleMessageHeader(false, false, false, false, false, false); - byte[] content = new byte[bytes.remaining()]; - bytes.get(content); - EzyMessage message = new EzySimpleMessage(header, content, content.length); - queue.add(message); - } - - } - - public static class ExStreamEzyByteToObjectDecoder implements EzyByteToObjectDecoder { - - @Override - public void reset() {} - - @Override - public Object decode(EzyMessage message) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - @Override - public void decode(ByteBuffer bytes, Queue queue) throws Exception { - EzyMessageHeader header = new EzySimpleMessageHeader(true, true, true, true, true, false); - byte[] content = new byte[bytes.remaining()]; - bytes.get(content); - EzyMessage message = new EzySimpleMessage(header, content, content.length); - queue.add(message); - } - - } - - public static class ExCodecFactory implements EzyCodecFactory { - @Override - public Object newDecoder(EzyConstant type) { - return new ExEzyByteToObjectDecoder(); - } - - @Override - public Object newEncoder(EzyConstant type) { - return null; - } - } - - public static class ErrorEzyByteToObjectDecoder implements EzyByteToObjectDecoder { - - @Override - public void reset() {} - - @Override - public Object decode(EzyMessage message) throws Exception { - throw new IllegalStateException("maintain"); - } - - @Override - public void decode(ByteBuffer bytes, Queue queue) throws Exception { - throw new IllegalStateException("maintain"); - } - - } + @SuppressWarnings("rawtypes") + @Test + public void test() throws Exception { + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .codecFactory(new ExCodecFactory()) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .build(); + + EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.SOCKET) + .build(); + + group.fireBytesReceived("hello".getBytes()); + EzySimplePacket packet = new EzySimplePacket(); + packet.setBinary(true); + packet.setData("world".getBytes()); + packet.setTransportType(EzyTransportType.TCP); + ByteBuffer writeBuffer = ByteBuffer.allocate(1024); + group.firePacketSend(packet, writeBuffer); + group.sendPacketNow(packet); + group.fireChannelRead(EzyCommand.PING, EzyEntityArrays.newArray(EzyCommand.PING.getId(), EzyEntityFactory.EMPTY_ARRAY)); + group.fireStreamBytesReceived(new byte[] {0, 1, 2}); + EzyPacket droppedPacket = mock(EzyPacket.class); + when(droppedPacket.getSize()).thenReturn(12); + group.addDroppedPacket(droppedPacket); + EzyPacket failedPacket = mock(EzyPacket.class); + when(failedPacket.getData()).thenReturn(new byte[] {1, 2, 3}); + when(failedPacket.isBinary()).thenReturn(true); + when(channel.write(any(ByteBuffer.class), anyBoolean())).thenThrow(new IllegalStateException("maintain")); + group.firePacketSend(failedPacket, writeBuffer); + group.fireChannelInactive(); + Thread.sleep(2000); + group.destroy(); + group.destroy(); + + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.SOCKET) + .session(session) + .streamQueue(streamQueue) + .decoder(new ExStreamEzyByteToObjectDecoder()) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + ((EzyAbstractSession)session).setStreamingEnable(false); + group.fireBytesReceived("hello".getBytes()); + Thread.sleep(500); + ((EzyAbstractSession)session).setStreamingEnable(true); + group.fireBytesReceived("hello".getBytes()); + Thread.sleep(1000); + + streamQueue = mock(EzySocketStreamQueue.class); + when(streamQueue.add(any())).thenThrow(new IllegalStateException("maintain")); + group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.SOCKET) + .session(session) + .streamQueue(streamQueue) + .decoder(new ExStreamEzyByteToObjectDecoder()) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + group.fireBytesReceived("hello".getBytes()); + Thread.sleep(1000); + + group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.SOCKET) + .session(session) + .decoder(new ErrorEzyByteToObjectDecoder()) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + group.fireBytesReceived("hello".getBytes()); + group.fireMessageReceived(mock(EzyMessage.class)); + Thread.sleep(300); + } + + @SuppressWarnings("rawtypes") + @Test + public void writeSuccessTest() throws Exception { + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + when(channel.write(any(ByteBuffer.class), anyBoolean())).thenReturn(123456); + + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .codecFactory(new ExCodecFactory()) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .build(); + + EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.SOCKET) + .session(session) + .decoder(decoder) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + EzySimplePacket packet = new EzySimplePacket(); + packet.setBinary(true); + packet.setData("world".getBytes()); + packet.setTransportType(EzyTransportType.TCP); + ByteBuffer writeBuffer = ByteBuffer.allocate(1024); + group.firePacketSend(packet, writeBuffer); + Thread.sleep(1000); + } + + @SuppressWarnings("rawtypes") + @Test + public void writeFailureTest() throws Exception { + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + SelectionKey selectionKey = mock(SelectionKey.class); + when(selectionKey.isValid()).thenReturn(true); + session.setProperty(EzyNioSession.SELECTION_KEY, selectionKey); + + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .codecFactory(new ExCodecFactory()) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .build(); + + EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.SOCKET) + .session(session) + .decoder(decoder) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + EzySimplePacket packet = new EzySimplePacket(); + packet.setBinary(true); + packet.setData("world".getBytes()); + packet.setTransportType(EzyTransportType.TCP); + ByteBuffer writeBuffer = ByteBuffer.allocate(1024); + group.firePacketSend(packet, writeBuffer); + Thread.sleep(1000); + } + + @Test + public void handleReceivedMesssageHeaderIsNotRawBytes() throws Exception { + // given + EzySimpleNioHandlerGroup sut = newHandlerGroup(); + + EzyMessage message = mock(EzyMessage.class); + EzyMessageHeader header = mock(EzyMessageHeader.class); + when(message.getHeader()).thenReturn(header); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedMesssage") + .param(EzyMessage.class, message) + .call(); + + // then + verify(header, times(1)).isRawBytes(); + + EzySimpleMessageDataDecoder decoder = FieldUtil.getFieldValue(sut, "decoder"); + EzyByteToObjectDecoder d = FieldUtil.getFieldValue(decoder, "decoder"); + EzySession session = FieldUtil.getFieldValue(sut, "session"); + verify(d, times(1)).decode(message, session.getSessionKey()); + } + + @Test + public void handleReceivedMesssageStreamingNotEnable() throws Exception { + // given + EzySimpleNioHandlerGroup sut = newHandlerGroup(false); + + EzyMessage message = mock(EzyMessage.class); + EzyMessageHeader header = mock(EzyMessageHeader.class); + when(header.isRawBytes()).thenReturn(true); + when(message.getHeader()).thenReturn(header); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedMesssage") + .param(EzyMessage.class, message) + .call(); + + // then + verify(header, times(1)).isRawBytes(); + } + + @Test + public void handleReceivedMesssageSessionStreamingNotEnable() throws Exception { + // given + EzySimpleNioHandlerGroup sut = newHandlerGroup(); + + EzyMessage message = mock(EzyMessage.class); + EzyMessageHeader header = mock(EzyMessageHeader.class); + when(header.isRawBytes()).thenReturn(true); + when(message.getHeader()).thenReturn(header); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + when(session.isStreamingEnable()).thenReturn(false); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedMesssage") + .param(EzyMessage.class, message) + .call(); + + // then + verify(header, times(1)).isRawBytes(); + verify(session, times(1)).isStreamingEnable(); + } + + @Test + public void writePacketToSocketSessionKeyIsInvalid() throws Exception { + // given + EzySimpleNioHandlerGroup sut = newHandlerGroup(); + + EzyNioSession session = FieldUtil.getFieldValue(sut, "session"); + SelectionKey selectionKey = mock(SelectionKey.class); + when(session.getSelectionKey()).thenReturn(selectionKey); + when(selectionKey.isValid()).thenReturn(false); + + + EzyPacket packet = mock(EzyPacket.class); + when(packet.getData()).thenReturn(new byte[] {1, 2, 3, 5}); + when(packet.isBinary()).thenReturn(true); + + ByteBuffer writeBuffer = ByteBuffer.allocate(5); + + // when + MethodInvoker.create() + .object(sut) + .method("writePacketToSocket") + .param(EzyPacket.class, packet) + .param(Object.class, writeBuffer) + .call(); + + // then + verify(session, times(1)).getSelectionKey(); + verify(selectionKey, times(1)).isValid(); + } + + private EzySimpleNioHandlerGroup newHandlerGroup() throws IOException { + return newHandlerGroup(true); + } + + @SuppressWarnings("rawtypes") + private EzySimpleNioHandlerGroup newHandlerGroup(boolean streamEnable) throws IOException { + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(streamEnable); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.SOCKET); + EzySimpleSession session = mock(EzySimpleSession.class); + when(session.getChannel()).thenReturn(channel); + + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + SelectionKey selectionKey = mock(SelectionKey.class); + when(selectionKey.isValid()).thenReturn(true); + when(session.getProperty(EzyNioSession.SELECTION_KEY)).thenReturn(selectionKey); + + EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); + EzyByteToObjectDecoder decoder = mock(EzyByteToObjectDecoder.class); + when(codecFactory.newDecoder(any())).thenReturn(decoder); + + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .codecFactory(codecFactory) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .build(); + + EzySimpleNioHandlerGroup group = (EzySimpleNioHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.SOCKET) + .session(session) + .decoder(decoder) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + return group; + } + + public static class ExEzyByteToObjectDecoder implements EzyByteToObjectDecoder { + + @Override + public void reset() {} + + @Override + public Object decode(EzyMessage message) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + @Override + public void decode(ByteBuffer bytes, Queue queue) throws Exception { + EzyMessageHeader header = new EzySimpleMessageHeader(false, false, false, false, false, false); + byte[] content = new byte[bytes.remaining()]; + bytes.get(content); + EzyMessage message = new EzySimpleMessage(header, content, content.length); + queue.add(message); + } + + } + + public static class ExStreamEzyByteToObjectDecoder implements EzyByteToObjectDecoder { + + @Override + public void reset() {} + + @Override + public Object decode(EzyMessage message) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + @Override + public void decode(ByteBuffer bytes, Queue queue) throws Exception { + EzyMessageHeader header = new EzySimpleMessageHeader(true, true, true, true, true, false); + byte[] content = new byte[bytes.remaining()]; + bytes.get(content); + EzyMessage message = new EzySimpleMessage(header, content, content.length); + queue.add(message); + } + + } + + public static class ExCodecFactory implements EzyCodecFactory { + @Override + public Object newDecoder(EzyConstant type) { + return new ExEzyByteToObjectDecoder(); + } + + @Override + public Object newEncoder(EzyConstant type) { + return null; + } + } + + public static class ErrorEzyByteToObjectDecoder implements EzyByteToObjectDecoder { + + @Override + public void reset() {} + + @Override + public Object decode(EzyMessage message) throws Exception { + throw new IllegalStateException("maintain"); + } + + @Override + public void decode(ByteBuffer bytes, Queue queue) throws Exception { + throw new IllegalStateException("maintain"); + } + + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioUdpDataHandlerTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioUdpDataHandlerTest.java index 7bc467c0d..343665623 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioUdpDataHandlerTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/handler/EzySimpleNioUdpDataHandlerTest.java @@ -36,430 +36,430 @@ public class EzySimpleNioUdpDataHandlerTest { - @SuppressWarnings("rawtypes") - @Test - public void test() throws Exception { - String sessionToken = "12345678"; - long sessionId = 12345L; - EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); - int tokenSize = sessionToken.length(); - int messageSize = 0; - messageSize += 8; // sessionIdSize - messageSize += 2; // tokenLengthSize - messageSize += tokenSize; // messageSize - ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); - byte header = 0; - header |= 1 << 5; - buffer.put(header); - buffer.putShort((short)messageSize); - buffer.putLong(sessionId); - buffer.putShort((short)tokenSize); - buffer.put(sessionToken.getBytes()); - buffer.flip(); - byte[] bytes = EzyByteBuffers.getBytes(buffer); - EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( - DatagramChannel.open(), - new InetSocketAddress(12345), - bytes); - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySessionManager sessionManager = mock(EzySessionManager.class); - EzySession session = spy(EzyAbstractSession.class); - session.setToken(sessionToken); - when(sessionManager.getSession(sessionId)).thenReturn(session); - EzyResponseApi responseApi = mock(EzyResponseApi.class); - EzyDatagramChannelPool channelPool = new EzyDatagramChannelPool(1); - handler.setHandlerGroupManager(handlerGroupManager); - handler.setSessionManager(sessionManager); - handler.setResponseApi(responseApi); - handler.setDatagramChannelPool(channelPool); - handler.fireUdpPacketReceived(packet); - Thread.sleep(200); - handler.destroy(); - } - - @Test - public void handleUdpHandshakeContentLengthLessThan11() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - DatagramChannel channel = mock(DatagramChannel.class); - InetSocketAddress address = new InetSocketAddress(3005); - EzyMessage message = mock(EzyMessage.class); - when(message.getContent()).thenReturn(new byte[0]); - - // when - MethodInvoker.create() - .object(sut) - .method("handleUdpHandshake") - .param(DatagramChannel.class, channel) - .param(InetSocketAddress.class, address) - .param(EzyMessage.class, message) - .call(); + @SuppressWarnings("rawtypes") + @Test + public void test() throws Exception { + String sessionToken = "12345678"; + long sessionId = 12345L; + EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); + int tokenSize = sessionToken.length(); + int messageSize = 0; + messageSize += 8; // sessionIdSize + messageSize += 2; // tokenLengthSize + messageSize += tokenSize; // messageSize + ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); + byte header = 0; + header |= 1 << 5; + buffer.put(header); + buffer.putShort((short)messageSize); + buffer.putLong(sessionId); + buffer.putShort((short)tokenSize); + buffer.put(sessionToken.getBytes()); + buffer.flip(); + byte[] bytes = EzyByteBuffers.getBytes(buffer); + EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( + DatagramChannel.open(), + new InetSocketAddress(12345), + bytes); + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySessionManager sessionManager = mock(EzySessionManager.class); + EzySession session = spy(EzyAbstractSession.class); + session.setToken(sessionToken); + when(sessionManager.getSession(sessionId)).thenReturn(session); + EzyResponseApi responseApi = mock(EzyResponseApi.class); + EzyDatagramChannelPool channelPool = new EzyDatagramChannelPool(1); + handler.setHandlerGroupManager(handlerGroupManager); + handler.setSessionManager(sessionManager); + handler.setResponseApi(responseApi); + handler.setDatagramChannelPool(channelPool); + handler.fireUdpPacketReceived(packet); + Thread.sleep(200); + handler.destroy(); + } + + @Test + public void handleUdpHandshakeContentLengthLessThan11() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + DatagramChannel channel = mock(DatagramChannel.class); + InetSocketAddress address = new InetSocketAddress(3005); + EzyMessage message = mock(EzyMessage.class); + when(message.getContent()).thenReturn(new byte[0]); + + // when + MethodInvoker.create() + .object(sut) + .method("handleUdpHandshake") + .param(DatagramChannel.class, channel) + .param(InetSocketAddress.class, address) + .param(EzyMessage.class, message) + .call(); - // then - verify(message, times(1)).getContent(); - sut.destroy(); - } - - @Test - public void handleUdpHandshakeTokenSizeGreaterThan512() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - DatagramChannel channel = mock(DatagramChannel.class); - InetSocketAddress address = new InetSocketAddress(3005); - EzyMessage message = mock(EzyMessage.class); - - String sessionToken = RandomUtil.randomAlphabetString(514); - long sessionId = 12345L; - int tokenSize = sessionToken.length(); - int messageSize = 0; - messageSize += 8; // sessionIdSize - messageSize += 2; // tokenLengthSize - messageSize += tokenSize; // messageSize - ByteBuffer buffer = ByteBuffer.allocate(messageSize); - buffer.putLong(sessionId); - buffer.putShort((short)tokenSize); - buffer.put(sessionToken.getBytes()); - buffer.flip(); - byte[] bytes = EzyByteBuffers.getBytes(buffer); - when(message.getContent()).thenReturn(bytes); - - // when - MethodInvoker.create() - .object(sut) - .method("handleUdpHandshake") - .param(DatagramChannel.class, channel) - .param(InetSocketAddress.class, address) - .param(EzyMessage.class, message) - .call(); + // then + verify(message, times(1)).getContent(); + sut.destroy(); + } + + @Test + public void handleUdpHandshakeTokenSizeGreaterThan512() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + DatagramChannel channel = mock(DatagramChannel.class); + InetSocketAddress address = new InetSocketAddress(3005); + EzyMessage message = mock(EzyMessage.class); + + String sessionToken = RandomUtil.randomAlphabetString(514); + long sessionId = 12345L; + int tokenSize = sessionToken.length(); + int messageSize = 0; + messageSize += 8; // sessionIdSize + messageSize += 2; // tokenLengthSize + messageSize += tokenSize; // messageSize + ByteBuffer buffer = ByteBuffer.allocate(messageSize); + buffer.putLong(sessionId); + buffer.putShort((short)tokenSize); + buffer.put(sessionToken.getBytes()); + buffer.flip(); + byte[] bytes = EzyByteBuffers.getBytes(buffer); + when(message.getContent()).thenReturn(bytes); + + // when + MethodInvoker.create() + .object(sut) + .method("handleUdpHandshake") + .param(DatagramChannel.class, channel) + .param(InetSocketAddress.class, address) + .param(EzyMessage.class, message) + .call(); - // then - verify(message, times(1)).getContent(); - sut.destroy(); - } - - @SuppressWarnings("rawtypes") - @Test - public void handleUdpHandshakeSessionIsNull() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - DatagramChannel channel = mock(DatagramChannel.class); - InetSocketAddress address = new InetSocketAddress(3005); - EzyMessage message = mock(EzyMessage.class); - - String sessionToken = RandomUtil.randomAlphabetString(8); - long sessionId = 12345L; - int tokenSize = sessionToken.length(); - int messageSize = 0; - messageSize += 8; // sessionIdSize - messageSize += 2; // tokenLengthSize - messageSize += tokenSize; // messageSize - ByteBuffer buffer = ByteBuffer.allocate(messageSize); - buffer.putLong(sessionId); - buffer.putShort((short)tokenSize); - buffer.put(sessionToken.getBytes()); - buffer.flip(); - byte[] bytes = EzyByteBuffers.getBytes(buffer); - when(message.getContent()).thenReturn(bytes); - - EzySessionManager sessionManager = mock(EzySessionManager.class); - sut.setSessionManager(sessionManager); - - // when - MethodInvoker.create() - .object(sut) - .method("handleUdpHandshake") - .param(DatagramChannel.class, channel) - .param(InetSocketAddress.class, address) - .param(EzyMessage.class, message) - .call(); + // then + verify(message, times(1)).getContent(); + sut.destroy(); + } + + @SuppressWarnings("rawtypes") + @Test + public void handleUdpHandshakeSessionIsNull() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + DatagramChannel channel = mock(DatagramChannel.class); + InetSocketAddress address = new InetSocketAddress(3005); + EzyMessage message = mock(EzyMessage.class); + + String sessionToken = RandomUtil.randomAlphabetString(8); + long sessionId = 12345L; + int tokenSize = sessionToken.length(); + int messageSize = 0; + messageSize += 8; // sessionIdSize + messageSize += 2; // tokenLengthSize + messageSize += tokenSize; // messageSize + ByteBuffer buffer = ByteBuffer.allocate(messageSize); + buffer.putLong(sessionId); + buffer.putShort((short)tokenSize); + buffer.put(sessionToken.getBytes()); + buffer.flip(); + byte[] bytes = EzyByteBuffers.getBytes(buffer); + when(message.getContent()).thenReturn(bytes); + + EzySessionManager sessionManager = mock(EzySessionManager.class); + sut.setSessionManager(sessionManager); + + // when + MethodInvoker.create() + .object(sut) + .method("handleUdpHandshake") + .param(DatagramChannel.class, channel) + .param(InetSocketAddress.class, address) + .param(EzyMessage.class, message) + .call(); - // then - verify(message, times(1)).getContent(); - verify(sessionManager, times(1)).getSession(sessionId); - sut.destroy(); - } - - @SuppressWarnings("rawtypes") - @Test - public void handleUdpHandshakeSessionTokenIsNotMatch() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - DatagramChannel channel = mock(DatagramChannel.class); - InetSocketAddress address = new InetSocketAddress(3005); - EzyMessage message = mock(EzyMessage.class); - - String sessionToken = RandomUtil.randomAlphabetString(8); - long sessionId = 12345L; - int tokenSize = sessionToken.length(); - int messageSize = 0; - messageSize += 8; // sessionIdSize - messageSize += 2; // tokenLengthSize - messageSize += tokenSize; // messageSize - ByteBuffer buffer = ByteBuffer.allocate(messageSize); - buffer.putLong(sessionId); - buffer.putShort((short)tokenSize); - buffer.put(sessionToken.getBytes()); - buffer.flip(); - byte[] bytes = EzyByteBuffers.getBytes(buffer); - when(message.getContent()).thenReturn(bytes); - - EzySessionManager sessionManager = mock(EzySessionManager.class); - sut.setSessionManager(sessionManager); - - EzySession session = mock(EzySession.class); - when(session.getToken()).thenReturn(RandomUtil.randomShortAlphabetString()); - when(sessionManager.getSession(sessionId)).thenReturn(session); - - EzyResponseApi responseApi = mock(EzyResponseApi.class); - sut.setResponseApi(responseApi); - - // when - MethodInvoker.create() - .object(sut) - .method("handleUdpHandshake") - .param(DatagramChannel.class, channel) - .param(InetSocketAddress.class, address) - .param(EzyMessage.class, message) - .call(); + // then + verify(message, times(1)).getContent(); + verify(sessionManager, times(1)).getSession(sessionId); + sut.destroy(); + } + + @SuppressWarnings("rawtypes") + @Test + public void handleUdpHandshakeSessionTokenIsNotMatch() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + DatagramChannel channel = mock(DatagramChannel.class); + InetSocketAddress address = new InetSocketAddress(3005); + EzyMessage message = mock(EzyMessage.class); + + String sessionToken = RandomUtil.randomAlphabetString(8); + long sessionId = 12345L; + int tokenSize = sessionToken.length(); + int messageSize = 0; + messageSize += 8; // sessionIdSize + messageSize += 2; // tokenLengthSize + messageSize += tokenSize; // messageSize + ByteBuffer buffer = ByteBuffer.allocate(messageSize); + buffer.putLong(sessionId); + buffer.putShort((short)tokenSize); + buffer.put(sessionToken.getBytes()); + buffer.flip(); + byte[] bytes = EzyByteBuffers.getBytes(buffer); + when(message.getContent()).thenReturn(bytes); + + EzySessionManager sessionManager = mock(EzySessionManager.class); + sut.setSessionManager(sessionManager); + + EzySession session = mock(EzySession.class); + when(session.getToken()).thenReturn(RandomUtil.randomShortAlphabetString()); + when(sessionManager.getSession(sessionId)).thenReturn(session); + + EzyResponseApi responseApi = mock(EzyResponseApi.class); + sut.setResponseApi(responseApi); + + // when + MethodInvoker.create() + .object(sut) + .method("handleUdpHandshake") + .param(DatagramChannel.class, channel) + .param(InetSocketAddress.class, address) + .param(EzyMessage.class, message) + .call(); - // then - verify(message, times(1)).getContent(); - verify(sessionManager, times(1)).getSession(sessionId); - verify(session, times(1)).getToken(); - verify(responseApi, times(1)).response(any()); - sut.destroy(); - } - - @Test - public void testNotHandshakeCase() throws Exception { - String sessionToken = "12345678"; - long sessionId = 12345L; - EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); - int tokenSize = sessionToken.length(); - int messageSize = 0; - messageSize += 8; // sessionIdSize - messageSize += 2; // tokenLengthSize - messageSize += tokenSize; // messageSize - ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); - byte header = 0; - buffer.put(header); - buffer.putShort((short)messageSize); - buffer.putLong(sessionId); - buffer.putShort((short)tokenSize); - buffer.put(sessionToken.getBytes()); - buffer.flip(); - byte[] bytes = EzyByteBuffers.getBytes(buffer); - EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( - DatagramChannel.open(), - new InetSocketAddress(12345), - bytes); - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); - when(handlerGroupManager.getHandlerGroup(packet.getAddress())).thenReturn(handlerGroup); - EzyNioSession session = new EzySimpleSession(); - session.setToken(sessionToken); - EzyChannel channel = mock(EzyChannel.class); - when(channel.getClientAddress()).thenReturn(new InetSocketAddress(12345)); - session.setChannel(channel); - when(handlerGroup.getSession()).thenReturn(session); - handler.setHandlerGroupManager(handlerGroupManager); - handler.fireUdpPacketReceived(packet); - Thread.sleep(200); - handler.destroy(); - } - - @Test - public void testExceptionCase() throws Exception { - String sessionToken = "12345678"; - long sessionId = 12345L; - EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); - int tokenSize = sessionToken.length(); - int messageSize = 0; - messageSize += 8; // sessionIdSize - messageSize += 2; // tokenLengthSize - messageSize += tokenSize; // messageSize - ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); - byte header = 0; - buffer.put(header); - buffer.putShort((short)messageSize); - buffer.putLong(sessionId); - buffer.putShort((short)tokenSize); - buffer.put(sessionToken.getBytes()); - buffer.flip(); - byte[] bytes = EzyByteBuffers.getBytes(buffer); - EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( - DatagramChannel.open(), - new InetSocketAddress(12345), - bytes); - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - when(handlerGroupManager.getHandlerGroup(packet.getAddress())).thenThrow(new IllegalArgumentException("test")); - handler.setHandlerGroupManager(handlerGroupManager); - handler.fireUdpPacketReceived(packet); - Thread.sleep(200); - handler.destroy(); - } - - @Test - public void testInvalidMessageCase() throws Exception { - EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); - byte[] bytes = new byte[] {1, 2, 3}; - EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( - DatagramChannel.open(), - new InetSocketAddress(12345), - bytes); - handler.fireUdpPacketReceived(packet); - Thread.sleep(200); - handler.destroy(); - } - - @Test - public void handleReceivedUdpPacketTest() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - byte[] messageBytes = messageBytes(); - - InetSocketAddress udpAddress = new InetSocketAddress(3005); - InetSocketAddress tcpAddress = new InetSocketAddress(123); - EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); - when(packet.getBytes()).thenReturn(messageBytes); - when(packet.getAddress()).thenReturn(udpAddress); - - SocketChannel socketChannel = mock(SocketChannel.class); - when(socketChannel.getRemoteAddress()).thenReturn(tcpAddress); - - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - when(handlerGroupManager.getSocketChannel(udpAddress)).thenReturn(socketChannel); - sut.setHandlerGroupManager(handlerGroupManager); - - EzySocketDataReceiver socketDataReceiver = mock(EzySocketDataReceiver.class); - sut.setSocketDataReceiver(socketDataReceiver); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedUdpPacket") - .param(EzyUdpReceivedPacket.class, packet) - .call(); - - // then - verify(handlerGroupManager, times(1)).getSocketChannel(udpAddress); - verify(socketChannel, times(1)).getRemoteAddress(); - verify(socketDataReceiver, times(1)).udpReceive(any(SocketChannel.class), any(EzyMessage.class)); - sut.destroy(); - } - - @Test - public void handleReceivedUdpPacketWithSessionTest() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - byte[] messageBytes = messageBytes(); - - InetSocketAddress udpAddress = new InetSocketAddress(3005); - InetSocketAddress tcpAddress = new InetSocketAddress(123); - EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); - when(packet.getBytes()).thenReturn(messageBytes); - when(packet.getAddress()).thenReturn(udpAddress); - - Session session = mock(Session.class); - when(session.getRemoteAddress()).thenReturn(tcpAddress); - - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - when(handlerGroupManager.getSocketChannel(udpAddress)).thenReturn(session); - sut.setHandlerGroupManager(handlerGroupManager); - - EzySocketDataReceiver socketDataReceiver = mock(EzySocketDataReceiver.class); - sut.setSocketDataReceiver(socketDataReceiver); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedUdpPacket") - .param(EzyUdpReceivedPacket.class, packet) - .call(); - - // then - verify(handlerGroupManager, times(1)).getSocketChannel(udpAddress); - verify(session, times(1)).getRemoteAddress(); - verify(socketDataReceiver, times(1)).udpReceive(any(SocketChannel.class), any(EzyMessage.class)); - sut.destroy(); - } - - @Test - public void handleReceivedUdpPacketIsNotOneClientTest() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - byte[] messageBytes = messageBytes(); - - InetSocketAddress udpAddress = new InetSocketAddress("client1", 3005); - InetSocketAddress tcpAddress = new InetSocketAddress("client2", 123); - EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); - when(packet.getBytes()).thenReturn(messageBytes); - when(packet.getAddress()).thenReturn(udpAddress); - - SocketChannel socketChannel = mock(SocketChannel.class); - when(socketChannel.getRemoteAddress()).thenReturn(tcpAddress); - - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - when(handlerGroupManager.getSocketChannel(udpAddress)).thenReturn(socketChannel); - sut.setHandlerGroupManager(handlerGroupManager); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedUdpPacket") - .param(EzyUdpReceivedPacket.class, packet) - .call(); - - // then - verify(handlerGroupManager, times(1)).getSocketChannel(udpAddress); - verify(socketChannel, times(1)).getRemoteAddress(); - sut.destroy(); - } - - @Test - public void handleReceivedUdpPacketInvalidMessageTest() throws Exception { - // given - EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); - - byte[] messageBytes = new byte[0]; - - EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); - when(packet.getBytes()).thenReturn(messageBytes); - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedUdpPacket") - .param(EzyUdpReceivedPacket.class, packet) - .call(); - - // then - sut.destroy(); - } - - private byte[] messageBytes() { - String sessionToken = "12345678"; - long sessionId = 12345L; - int tokenSize = sessionToken.length(); - int messageSize = 0; - messageSize += 8; // sessionIdSize - messageSize += 2; // tokenLengthSize - messageSize += tokenSize; // messageSize - ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); - byte header = 0; - buffer.put(header); - buffer.putShort((short)messageSize); - buffer.putLong(sessionId); - buffer.putShort((short)tokenSize); - buffer.put(sessionToken.getBytes()); - buffer.flip(); - return EzyByteBuffers.getBytes(buffer); - } + // then + verify(message, times(1)).getContent(); + verify(sessionManager, times(1)).getSession(sessionId); + verify(session, times(1)).getToken(); + verify(responseApi, times(1)).response(any()); + sut.destroy(); + } + + @Test + public void testNotHandshakeCase() throws Exception { + String sessionToken = "12345678"; + long sessionId = 12345L; + EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); + int tokenSize = sessionToken.length(); + int messageSize = 0; + messageSize += 8; // sessionIdSize + messageSize += 2; // tokenLengthSize + messageSize += tokenSize; // messageSize + ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); + byte header = 0; + buffer.put(header); + buffer.putShort((short)messageSize); + buffer.putLong(sessionId); + buffer.putShort((short)tokenSize); + buffer.put(sessionToken.getBytes()); + buffer.flip(); + byte[] bytes = EzyByteBuffers.getBytes(buffer); + EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( + DatagramChannel.open(), + new InetSocketAddress(12345), + bytes); + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); + when(handlerGroupManager.getHandlerGroup(packet.getAddress())).thenReturn(handlerGroup); + EzyNioSession session = new EzySimpleSession(); + session.setToken(sessionToken); + EzyChannel channel = mock(EzyChannel.class); + when(channel.getClientAddress()).thenReturn(new InetSocketAddress(12345)); + session.setChannel(channel); + when(handlerGroup.getSession()).thenReturn(session); + handler.setHandlerGroupManager(handlerGroupManager); + handler.fireUdpPacketReceived(packet); + Thread.sleep(200); + handler.destroy(); + } + + @Test + public void testExceptionCase() throws Exception { + String sessionToken = "12345678"; + long sessionId = 12345L; + EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); + int tokenSize = sessionToken.length(); + int messageSize = 0; + messageSize += 8; // sessionIdSize + messageSize += 2; // tokenLengthSize + messageSize += tokenSize; // messageSize + ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); + byte header = 0; + buffer.put(header); + buffer.putShort((short)messageSize); + buffer.putLong(sessionId); + buffer.putShort((short)tokenSize); + buffer.put(sessionToken.getBytes()); + buffer.flip(); + byte[] bytes = EzyByteBuffers.getBytes(buffer); + EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( + DatagramChannel.open(), + new InetSocketAddress(12345), + bytes); + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + when(handlerGroupManager.getHandlerGroup(packet.getAddress())).thenThrow(new IllegalArgumentException("test")); + handler.setHandlerGroupManager(handlerGroupManager); + handler.fireUdpPacketReceived(packet); + Thread.sleep(200); + handler.destroy(); + } + + @Test + public void testInvalidMessageCase() throws Exception { + EzySimpleNioUdpDataHandler handler = new EzySimpleNioUdpDataHandler(1); + byte[] bytes = new byte[] {1, 2, 3}; + EzyUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( + DatagramChannel.open(), + new InetSocketAddress(12345), + bytes); + handler.fireUdpPacketReceived(packet); + Thread.sleep(200); + handler.destroy(); + } + + @Test + public void handleReceivedUdpPacketTest() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + byte[] messageBytes = messageBytes(); + + InetSocketAddress udpAddress = new InetSocketAddress(3005); + InetSocketAddress tcpAddress = new InetSocketAddress(123); + EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); + when(packet.getBytes()).thenReturn(messageBytes); + when(packet.getAddress()).thenReturn(udpAddress); + + SocketChannel socketChannel = mock(SocketChannel.class); + when(socketChannel.getRemoteAddress()).thenReturn(tcpAddress); + + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + when(handlerGroupManager.getSocketChannel(udpAddress)).thenReturn(socketChannel); + sut.setHandlerGroupManager(handlerGroupManager); + + EzySocketDataReceiver socketDataReceiver = mock(EzySocketDataReceiver.class); + sut.setSocketDataReceiver(socketDataReceiver); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedUdpPacket") + .param(EzyUdpReceivedPacket.class, packet) + .call(); + + // then + verify(handlerGroupManager, times(1)).getSocketChannel(udpAddress); + verify(socketChannel, times(1)).getRemoteAddress(); + verify(socketDataReceiver, times(1)).udpReceive(any(SocketChannel.class), any(EzyMessage.class)); + sut.destroy(); + } + + @Test + public void handleReceivedUdpPacketWithSessionTest() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + byte[] messageBytes = messageBytes(); + + InetSocketAddress udpAddress = new InetSocketAddress(3005); + InetSocketAddress tcpAddress = new InetSocketAddress(123); + EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); + when(packet.getBytes()).thenReturn(messageBytes); + when(packet.getAddress()).thenReturn(udpAddress); + + Session session = mock(Session.class); + when(session.getRemoteAddress()).thenReturn(tcpAddress); + + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + when(handlerGroupManager.getSocketChannel(udpAddress)).thenReturn(session); + sut.setHandlerGroupManager(handlerGroupManager); + + EzySocketDataReceiver socketDataReceiver = mock(EzySocketDataReceiver.class); + sut.setSocketDataReceiver(socketDataReceiver); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedUdpPacket") + .param(EzyUdpReceivedPacket.class, packet) + .call(); + + // then + verify(handlerGroupManager, times(1)).getSocketChannel(udpAddress); + verify(session, times(1)).getRemoteAddress(); + verify(socketDataReceiver, times(1)).udpReceive(any(SocketChannel.class), any(EzyMessage.class)); + sut.destroy(); + } + + @Test + public void handleReceivedUdpPacketIsNotOneClientTest() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + byte[] messageBytes = messageBytes(); + + InetSocketAddress udpAddress = new InetSocketAddress("client1", 3005); + InetSocketAddress tcpAddress = new InetSocketAddress("client2", 123); + EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); + when(packet.getBytes()).thenReturn(messageBytes); + when(packet.getAddress()).thenReturn(udpAddress); + + SocketChannel socketChannel = mock(SocketChannel.class); + when(socketChannel.getRemoteAddress()).thenReturn(tcpAddress); + + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + when(handlerGroupManager.getSocketChannel(udpAddress)).thenReturn(socketChannel); + sut.setHandlerGroupManager(handlerGroupManager); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedUdpPacket") + .param(EzyUdpReceivedPacket.class, packet) + .call(); + + // then + verify(handlerGroupManager, times(1)).getSocketChannel(udpAddress); + verify(socketChannel, times(1)).getRemoteAddress(); + sut.destroy(); + } + + @Test + public void handleReceivedUdpPacketInvalidMessageTest() throws Exception { + // given + EzySimpleNioUdpDataHandler sut = new EzySimpleNioUdpDataHandler(1); + + byte[] messageBytes = new byte[0]; + + EzyUdpReceivedPacket packet = mock(EzyUdpReceivedPacket.class); + when(packet.getBytes()).thenReturn(messageBytes); + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedUdpPacket") + .param(EzyUdpReceivedPacket.class, packet) + .call(); + + // then + sut.destroy(); + } + + private byte[] messageBytes() { + String sessionToken = "12345678"; + long sessionId = 12345L; + int tokenSize = sessionToken.length(); + int messageSize = 0; + messageSize += 8; // sessionIdSize + messageSize += 2; // tokenLengthSize + messageSize += tokenSize; // messageSize + ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + messageSize); + byte header = 0; + buffer.put(header); + buffer.putShort((short)messageSize); + buffer.putLong(sessionId); + buffer.putShort((short)tokenSize); + buffer.put(sessionToken.getBytes()); + buffer.flip(); + return EzyByteBuffers.getBytes(buffer); + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketAcceptorTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketAcceptorTest.java index e8baaaf20..12d3d0d47 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketAcceptorTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketAcceptorTest.java @@ -62,191 +62,191 @@ public class EzyNioSocketAcceptorTest extends BaseTest { - @Test - public void test() throws Exception { - EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); - - Selector ownSelector = spy(ExSelector.class); - SelectionKey selectionKey1 = spy(ExSelectionKey.class); - SelectionKey selectionKey2 = spy(ExSelectionKey.class); - when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet( - selectionKey1, selectionKey2)); - when(selectionKey1.isValid()).thenReturn(true); - when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_ACCEPT); - ExServerSocketChannel serverChannel1 = spy(ExServerSocketChannel.class); - when(selectionKey1.channel()).thenReturn(serverChannel1); - SocketChannel channel1 = spy(ExSocketChannel.class); - when(serverChannel1.accept()).thenReturn(channel1); - Socket socket1 = new Socket(); - when(channel1.socket()).thenReturn(socket1); - - Selector readSelector = spy(ExSelector.class); - - channel1.configureBlocking(false); - when(channel1.register(readSelector, SelectionKey.OP_READ)).thenReturn(selectionKey1); - - EzyNioSocketAcceptor acceptor = new EzyNioSocketAcceptor(); - acceptor.setAcceptableConnections(new ArrayList<>()); - acceptor.setHandlerGroupManager(handlerGroupManager); - acceptor.setOwnSelector(ownSelector); - acceptor.setReadSelector(readSelector); - acceptor.handleEvent(); - List acceptableConnections = FieldUtil.getFieldValue(acceptor, "acceptableConnections"); - assert acceptableConnections.size() == 1; - acceptor.handleAcceptableConnections(); - assert acceptableConnections.size() == 0; - } - - @Test - public void acceptConnectionExceptionCase() throws Exception { - EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); - - Selector ownSelector = spy(ExSelector.class); - SelectionKey selectionKey1 = spy(ExSelectionKey.class); - SelectionKey selectionKey2 = spy(ExSelectionKey.class); - when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet( - selectionKey1, selectionKey2)); - when(selectionKey1.isValid()).thenReturn(true); - when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_ACCEPT); - ExServerSocketChannel serverChannel1 = spy(ExServerSocketChannel.class); - when(selectionKey1.channel()).thenReturn(serverChannel1); - SocketChannel channel1 = spy(ExSocketChannel.class); - when(serverChannel1.accept()).thenReturn(channel1); - when(channel1.socket()).thenThrow(new IllegalStateException("server maintain")); - - Selector readSelector = spy(ExSelector.class); - - EzyNioSocketAcceptor acceptor = new EzyNioSocketAcceptor(); - acceptor.setAcceptableConnections(new ArrayList<>()); - acceptor.setHandlerGroupManager(handlerGroupManager); - acceptor.setOwnSelector(ownSelector); - acceptor.setReadSelector(readSelector); - acceptor.handleEvent(); - List acceptableConnections = FieldUtil.getFieldValue(acceptor, "acceptableConnections"); - assert acceptableConnections.size() == 1; - acceptor.handleAcceptableConnections(); - assert acceptableConnections.size() == 0; - } - - - private EzyHandlerGroupManager newHandlerGroupManager() { - EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); - when(codecFactory.newDecoder(any())).thenReturn(decoder); - ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue) - .disconnectionQueue(disconnectionQueue) - .codecFactory(codecFactory) - .serverContext(serverContext) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - - EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() - .handlerGroupBuilderFactory(handlerGroupBuilderFactory) - .build(); - return handlerGroupManager; - } - - @Test - public void acceptConnectionTest() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); - - Selector readSelector = Selector.open(); - EzyNioSocketAcceptor sut = new EzyNioSocketAcceptor(); - sut.setReadSelector(readSelector); - SocketChannel clientChannel = SocketChannel.open(); - - when(handlerGroupManager.newHandlerGroup(any(), any())).thenReturn(handlerGroup); - sut.setHandlerGroupManager(handlerGroupManager); - - EzyNioSession session = mock(EzyNioSession.class); - when(handlerGroup.getSession()).thenReturn(session); - - // when - MethodInvoker.create() - .object(sut) - .method("acceptConnection") - .param(SocketChannel.class, clientChannel) - .call(); - - // then - verify(handlerGroupManager, times(1)).newHandlerGroup(any(), any()); - } - - public static abstract class ExServerSocketChannel extends ServerSocketChannel { - public ExServerSocketChannel() { - super(SelectorProvider.provider()); - } - } - - - public static abstract class ExSocketChannel extends SocketChannel { - - public ExSocketChannel() { - super(SelectorProvider.provider()); - } - - } - - public static abstract class ExSelector extends AbstractSelector { - public ExSelector() { - super(SelectorProvider.provider()); - } - } - - public static abstract class ExSelectionKey extends SelectionKey { - public ExSelectionKey() {} - } - - public static class ExEzyByteToObjectDecoder implements EzyByteToObjectDecoder { - - @Override - public void reset() {} - - @Override - public Object decode(EzyMessage message) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - @Override - public void decode(ByteBuffer bytes, Queue queue) throws Exception { - EzyMessageHeader header = new EzySimpleMessageHeader(false, false, false, false, false, false); - byte[] content = new byte[bytes.remaining()]; - bytes.get(content); - EzyMessage message = new EzySimpleMessage(header, content, content.length); - queue.add(message); - } - - } + @Test + public void test() throws Exception { + EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); + + Selector ownSelector = spy(ExSelector.class); + SelectionKey selectionKey1 = spy(ExSelectionKey.class); + SelectionKey selectionKey2 = spy(ExSelectionKey.class); + when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet( + selectionKey1, selectionKey2)); + when(selectionKey1.isValid()).thenReturn(true); + when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_ACCEPT); + ExServerSocketChannel serverChannel1 = spy(ExServerSocketChannel.class); + when(selectionKey1.channel()).thenReturn(serverChannel1); + SocketChannel channel1 = spy(ExSocketChannel.class); + when(serverChannel1.accept()).thenReturn(channel1); + Socket socket1 = new Socket(); + when(channel1.socket()).thenReturn(socket1); + + Selector readSelector = spy(ExSelector.class); + + channel1.configureBlocking(false); + when(channel1.register(readSelector, SelectionKey.OP_READ)).thenReturn(selectionKey1); + + EzyNioSocketAcceptor acceptor = new EzyNioSocketAcceptor(); + acceptor.setAcceptableConnections(new ArrayList<>()); + acceptor.setHandlerGroupManager(handlerGroupManager); + acceptor.setOwnSelector(ownSelector); + acceptor.setReadSelector(readSelector); + acceptor.handleEvent(); + List acceptableConnections = FieldUtil.getFieldValue(acceptor, "acceptableConnections"); + assert acceptableConnections.size() == 1; + acceptor.handleAcceptableConnections(); + assert acceptableConnections.size() == 0; + } + + @Test + public void acceptConnectionExceptionCase() throws Exception { + EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); + + Selector ownSelector = spy(ExSelector.class); + SelectionKey selectionKey1 = spy(ExSelectionKey.class); + SelectionKey selectionKey2 = spy(ExSelectionKey.class); + when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet( + selectionKey1, selectionKey2)); + when(selectionKey1.isValid()).thenReturn(true); + when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_ACCEPT); + ExServerSocketChannel serverChannel1 = spy(ExServerSocketChannel.class); + when(selectionKey1.channel()).thenReturn(serverChannel1); + SocketChannel channel1 = spy(ExSocketChannel.class); + when(serverChannel1.accept()).thenReturn(channel1); + when(channel1.socket()).thenThrow(new IllegalStateException("server maintain")); + + Selector readSelector = spy(ExSelector.class); + + EzyNioSocketAcceptor acceptor = new EzyNioSocketAcceptor(); + acceptor.setAcceptableConnections(new ArrayList<>()); + acceptor.setHandlerGroupManager(handlerGroupManager); + acceptor.setOwnSelector(ownSelector); + acceptor.setReadSelector(readSelector); + acceptor.handleEvent(); + List acceptableConnections = FieldUtil.getFieldValue(acceptor, "acceptableConnections"); + assert acceptableConnections.size() == 1; + acceptor.handleAcceptableConnections(); + assert acceptableConnections.size() == 0; + } + + + private EzyHandlerGroupManager newHandlerGroupManager() { + EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); + when(codecFactory.newDecoder(any())).thenReturn(decoder); + ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue) + .disconnectionQueue(disconnectionQueue) + .codecFactory(codecFactory) + .serverContext(serverContext) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + + EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() + .handlerGroupBuilderFactory(handlerGroupBuilderFactory) + .build(); + return handlerGroupManager; + } + + @Test + public void acceptConnectionTest() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); + + Selector readSelector = Selector.open(); + EzyNioSocketAcceptor sut = new EzyNioSocketAcceptor(); + sut.setReadSelector(readSelector); + SocketChannel clientChannel = SocketChannel.open(); + + when(handlerGroupManager.newHandlerGroup(any(), any())).thenReturn(handlerGroup); + sut.setHandlerGroupManager(handlerGroupManager); + + EzyNioSession session = mock(EzyNioSession.class); + when(handlerGroup.getSession()).thenReturn(session); + + // when + MethodInvoker.create() + .object(sut) + .method("acceptConnection") + .param(SocketChannel.class, clientChannel) + .call(); + + // then + verify(handlerGroupManager, times(1)).newHandlerGroup(any(), any()); + } + + public static abstract class ExServerSocketChannel extends ServerSocketChannel { + public ExServerSocketChannel() { + super(SelectorProvider.provider()); + } + } + + + public static abstract class ExSocketChannel extends SocketChannel { + + public ExSocketChannel() { + super(SelectorProvider.provider()); + } + + } + + public static abstract class ExSelector extends AbstractSelector { + public ExSelector() { + super(SelectorProvider.provider()); + } + } + + public static abstract class ExSelectionKey extends SelectionKey { + public ExSelectionKey() {} + } + + public static class ExEzyByteToObjectDecoder implements EzyByteToObjectDecoder { + + @Override + public void reset() {} + + @Override + public Object decode(EzyMessage message) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + @Override + public void decode(ByteBuffer bytes, Queue queue) throws Exception { + EzyMessageHeader header = new EzySimpleMessageHeader(false, false, false, false, false, false); + byte[] content = new byte[bytes.remaining()]; + bytes.get(content); + EzyMessage message = new EzySimpleMessage(header, content, content.length); + queue.add(message); + } + + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketChannelTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketChannelTest.java index a5dc414fa..8e7a92462 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketChannelTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketChannelTest.java @@ -12,27 +12,27 @@ public class EzyNioSocketChannelTest extends BaseTest { - @Test - public void test() throws Exception { - ExSocketChannel socketChannel = spy(ExSocketChannel.class); - EzyNioSocketChannel channel = new EzyNioSocketChannel(socketChannel); - System.out.println(channel.getChannel()); - System.out.println(channel.getServerAddress()); - System.out.println(channel.isConnected()); - channel.disconnect(); - channel.close(); - ByteBuffer buffer = ByteBuffer.allocate(5); - buffer.put("hello".getBytes()); - buffer.flip(); - channel.write(buffer, true); - } - - public static abstract class ExSocketChannel extends SocketChannel { - - public ExSocketChannel() { - super(SelectorProvider.provider()); - } - - } - + @Test + public void test() throws Exception { + ExSocketChannel socketChannel = spy(ExSocketChannel.class); + EzyNioSocketChannel channel = new EzyNioSocketChannel(socketChannel); + System.out.println(channel.getChannel()); + System.out.println(channel.getServerAddress()); + System.out.println(channel.isConnected()); + channel.disconnect(); + channel.close(); + ByteBuffer buffer = ByteBuffer.allocate(5); + buffer.put("hello".getBytes()); + buffer.flip(); + channel.write(buffer, true); + } + + public static abstract class ExSocketChannel extends SocketChannel { + + public ExSocketChannel() { + super(SelectorProvider.provider()); + } + + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketReaderTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketReaderTest.java index acbac3d0b..54b875616 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketReaderTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketReaderTest.java @@ -60,203 +60,203 @@ public class EzyNioSocketReaderTest extends BaseTest { - @Test - public void test() throws Exception { - EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); - EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder() - .threadPoolSize(1) - .handlerGroupManager(handlerGroupManager) - .build(); - - Selector ownSelector = spy(ExSelector.class); - when(ownSelector.selectNow()).thenReturn(1); - SelectionKey selectionKey1 = spy(ExSelectionKey.class); - SelectionKey selectionKey2 = spy(ExSelectionKey.class); - SelectionKey selectionKey3 = spy(ExSelectionKey.class); - SelectionKey selectionKey4 = spy(ExSelectionKey.class); - SelectionKey selectionKey5 = spy(ExSelectionKey.class); - when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet( - selectionKey1, - selectionKey2, - selectionKey3, selectionKey4, selectionKey5)); - when(selectionKey1.isValid()).thenReturn(true); - when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_READ); - when(selectionKey2.isValid()).thenReturn(true); - when(selectionKey2.readyOps()).thenReturn(SelectionKey.OP_WRITE); - when(selectionKey3.isValid()).thenReturn(false); - when(selectionKey4.isValid()).thenReturn(true); - when(selectionKey4.readyOps()).thenReturn(SelectionKey.OP_READ); - when(selectionKey5.isValid()).thenReturn(true); - when(selectionKey5.readyOps()).thenReturn(SelectionKey.OP_READ); - - SocketChannel socketChannel1 = mock(SocketChannel.class); - EzyChannel channel1 = new EzyNioSocketChannel(socketChannel1); - - handlerGroupManager.newHandlerGroup(channel1, EzyConnectionType.SOCKET); - - when(selectionKey1.channel()).thenReturn(socketChannel1); - when(socketChannel1.isConnected()).thenReturn(true); - when(socketChannel1.read(any(ByteBuffer.class))).then(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - ByteBuffer buffer = invocation.getArgumentAt(0, ByteBuffer.class); - buffer.put("hello".getBytes()); - return "hello".length(); - } - }); - - SocketChannel socketChannel4 = mock(SocketChannel.class); - when(selectionKey4.channel()).thenReturn(socketChannel4); - - SocketChannel socketChannel5 = spy(ExSocketChannel.class); - EzyChannel channel5 = new EzyNioSocketChannel(socketChannel5); - when(selectionKey5.channel()).thenReturn(socketChannel5); - doNothing().when(socketChannel5).close(); - - handlerGroupManager.newHandlerGroup(channel5, EzyConnectionType.SOCKET); - - when(selectionKey5.channel()).thenReturn(socketChannel5); - when(socketChannel5.isConnected()).thenReturn(true); - when(socketChannel5.read(any(ByteBuffer.class))).then(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - return -1; - } - }); - - EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor(); - socketAcceptor.setReadSelector(ownSelector); - socketAcceptor.setHandlerGroupManager(handlerGroupManager); - socketAcceptor.setAcceptableConnections(new ArrayList<>()); - - EzyNioSocketReader socketReader = new EzyNioSocketReader(); - socketReader.setOwnSelector(ownSelector); - socketReader.setAcceptableConnectionsHandler(socketAcceptor); - socketReader.setSocketDataReceiver(socketDataReceiver); - socketReader.handleEvent(); - } - - @Test - public void testExceptionCase() throws Exception { - EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); - EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder() - .threadPoolSize(1) - .handlerGroupManager(handlerGroupManager) - .build(); - - Selector ownSelector = spy(ExSelector.class); - when(ownSelector.selectNow()).thenReturn(1); - SelectionKey selectionKey1 = spy(ExSelectionKey.class); - when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey1)); - when(selectionKey1.isValid()).thenReturn(true); - when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_READ); - - SocketChannel socketChannel1 = mock(SocketChannel.class); - EzyChannel channel1 = new EzyNioSocketChannel(socketChannel1); - - handlerGroupManager.newHandlerGroup(channel1, EzyConnectionType.SOCKET); - - when(selectionKey1.channel()).thenReturn(socketChannel1); - when(socketChannel1.isConnected()).thenReturn(true); - when(socketChannel1.read(any(ByteBuffer.class))).then(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - throw new IllegalStateException("server maintain"); - } - }); - - EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor(); - socketAcceptor.setReadSelector(ownSelector); - socketAcceptor.setHandlerGroupManager(handlerGroupManager); - socketAcceptor.setAcceptableConnections(new ArrayList<>()); - - EzyNioSocketReader socketReader = new EzyNioSocketReader(); - socketReader.setOwnSelector(ownSelector); - socketReader.setAcceptableConnectionsHandler(socketAcceptor); - socketReader.setSocketDataReceiver(socketDataReceiver); - socketReader.handleEvent(); - } - - private EzyHandlerGroupManager newHandlerGroupManager() { - EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); - when(codecFactory.newDecoder(any())).thenReturn(decoder); - ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue) - .disconnectionQueue(disconnectionQueue) - .codecFactory(codecFactory) - .serverContext(serverContext) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - - EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() - .handlerGroupBuilderFactory(handlerGroupBuilderFactory) - .build(); - return handlerGroupManager; - } - - public static abstract class ExSocketChannel extends SocketChannel { - - public ExSocketChannel() { - super(SelectorProvider.provider()); - } - - } - - public static abstract class ExSelector extends Selector { - public ExSelector() {} - } - - public static abstract class ExSelectionKey extends SelectionKey { - public ExSelectionKey() {} - } - - public static class ExEzyByteToObjectDecoder implements EzyByteToObjectDecoder { - - @Override - public void reset() {} - - @Override - public Object decode(EzyMessage message) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - @Override - public void decode(ByteBuffer bytes, Queue queue) throws Exception { - EzyMessageHeader header = new EzySimpleMessageHeader(false, false, false, false, false, false); - byte[] content = new byte[bytes.remaining()]; - bytes.get(content); - EzyMessage message = new EzySimpleMessage(header, content, content.length); - queue.add(message); - } - - } + @Test + public void test() throws Exception { + EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); + EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder() + .threadPoolSize(1) + .handlerGroupManager(handlerGroupManager) + .build(); + + Selector ownSelector = spy(ExSelector.class); + when(ownSelector.selectNow()).thenReturn(1); + SelectionKey selectionKey1 = spy(ExSelectionKey.class); + SelectionKey selectionKey2 = spy(ExSelectionKey.class); + SelectionKey selectionKey3 = spy(ExSelectionKey.class); + SelectionKey selectionKey4 = spy(ExSelectionKey.class); + SelectionKey selectionKey5 = spy(ExSelectionKey.class); + when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet( + selectionKey1, + selectionKey2, + selectionKey3, selectionKey4, selectionKey5)); + when(selectionKey1.isValid()).thenReturn(true); + when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_READ); + when(selectionKey2.isValid()).thenReturn(true); + when(selectionKey2.readyOps()).thenReturn(SelectionKey.OP_WRITE); + when(selectionKey3.isValid()).thenReturn(false); + when(selectionKey4.isValid()).thenReturn(true); + when(selectionKey4.readyOps()).thenReturn(SelectionKey.OP_READ); + when(selectionKey5.isValid()).thenReturn(true); + when(selectionKey5.readyOps()).thenReturn(SelectionKey.OP_READ); + + SocketChannel socketChannel1 = mock(SocketChannel.class); + EzyChannel channel1 = new EzyNioSocketChannel(socketChannel1); + + handlerGroupManager.newHandlerGroup(channel1, EzyConnectionType.SOCKET); + + when(selectionKey1.channel()).thenReturn(socketChannel1); + when(socketChannel1.isConnected()).thenReturn(true); + when(socketChannel1.read(any(ByteBuffer.class))).then(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer buffer = invocation.getArgumentAt(0, ByteBuffer.class); + buffer.put("hello".getBytes()); + return "hello".length(); + } + }); + + SocketChannel socketChannel4 = mock(SocketChannel.class); + when(selectionKey4.channel()).thenReturn(socketChannel4); + + SocketChannel socketChannel5 = spy(ExSocketChannel.class); + EzyChannel channel5 = new EzyNioSocketChannel(socketChannel5); + when(selectionKey5.channel()).thenReturn(socketChannel5); + doNothing().when(socketChannel5).close(); + + handlerGroupManager.newHandlerGroup(channel5, EzyConnectionType.SOCKET); + + when(selectionKey5.channel()).thenReturn(socketChannel5); + when(socketChannel5.isConnected()).thenReturn(true); + when(socketChannel5.read(any(ByteBuffer.class))).then(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return -1; + } + }); + + EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor(); + socketAcceptor.setReadSelector(ownSelector); + socketAcceptor.setHandlerGroupManager(handlerGroupManager); + socketAcceptor.setAcceptableConnections(new ArrayList<>()); + + EzyNioSocketReader socketReader = new EzyNioSocketReader(); + socketReader.setOwnSelector(ownSelector); + socketReader.setAcceptableConnectionsHandler(socketAcceptor); + socketReader.setSocketDataReceiver(socketDataReceiver); + socketReader.handleEvent(); + } + + @Test + public void testExceptionCase() throws Exception { + EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager(); + EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder() + .threadPoolSize(1) + .handlerGroupManager(handlerGroupManager) + .build(); + + Selector ownSelector = spy(ExSelector.class); + when(ownSelector.selectNow()).thenReturn(1); + SelectionKey selectionKey1 = spy(ExSelectionKey.class); + when(ownSelector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey1)); + when(selectionKey1.isValid()).thenReturn(true); + when(selectionKey1.readyOps()).thenReturn(SelectionKey.OP_READ); + + SocketChannel socketChannel1 = mock(SocketChannel.class); + EzyChannel channel1 = new EzyNioSocketChannel(socketChannel1); + + handlerGroupManager.newHandlerGroup(channel1, EzyConnectionType.SOCKET); + + when(selectionKey1.channel()).thenReturn(socketChannel1); + when(socketChannel1.isConnected()).thenReturn(true); + when(socketChannel1.read(any(ByteBuffer.class))).then(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + throw new IllegalStateException("server maintain"); + } + }); + + EzyNioSocketAcceptor socketAcceptor = new EzyNioSocketAcceptor(); + socketAcceptor.setReadSelector(ownSelector); + socketAcceptor.setHandlerGroupManager(handlerGroupManager); + socketAcceptor.setAcceptableConnections(new ArrayList<>()); + + EzyNioSocketReader socketReader = new EzyNioSocketReader(); + socketReader.setOwnSelector(ownSelector); + socketReader.setAcceptableConnectionsHandler(socketAcceptor); + socketReader.setSocketDataReceiver(socketDataReceiver); + socketReader.handleEvent(); + } + + private EzyHandlerGroupManager newHandlerGroupManager() { + EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); + when(codecFactory.newDecoder(any())).thenReturn(decoder); + ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue) + .disconnectionQueue(disconnectionQueue) + .codecFactory(codecFactory) + .serverContext(serverContext) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + + EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() + .handlerGroupBuilderFactory(handlerGroupBuilderFactory) + .build(); + return handlerGroupManager; + } + + public static abstract class ExSocketChannel extends SocketChannel { + + public ExSocketChannel() { + super(SelectorProvider.provider()); + } + + } + + public static abstract class ExSelector extends Selector { + public ExSelector() {} + } + + public static abstract class ExSelectionKey extends SelectionKey { + public ExSelectionKey() {} + } + + public static class ExEzyByteToObjectDecoder implements EzyByteToObjectDecoder { + + @Override + public void reset() {} + + @Override + public Object decode(EzyMessage message) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + @Override + public void decode(ByteBuffer bytes, Queue queue) throws Exception { + EzyMessageHeader header = new EzySimpleMessageHeader(false, false, false, false, false, false); + byte[] content = new byte[bytes.remaining()]; + bytes.get(content); + EzyMessage message = new EzySimpleMessage(header, content, content.length); + queue.add(message); + } + + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketWriterTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketWriterTest.java index 0f3da3c83..740a1e9e5 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketWriterTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzyNioSocketWriterTest.java @@ -10,14 +10,14 @@ public class EzyNioSocketWriterTest extends BaseTest { - @Test - public void test() { - EzyNioSocketWriter writer = new EzyNioSocketWriter(); - ByteBuffer writeBuffer = MethodInvoker.create() - .object(writer) - .method("getWriteBuffer") - .invoke(ByteBuffer.class); - assert writeBuffer != null; - } - + @Test + public void test() { + EzyNioSocketWriter writer = new EzyNioSocketWriter(); + ByteBuffer writeBuffer = MethodInvoker.create() + .object(writer) + .method("getWriteBuffer") + .invoke(ByteBuffer.class); + assert writeBuffer != null; + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzySocketDataReceiverTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzySocketDataReceiverTest.java index 0440e1a4e..3f690b8b5 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzySocketDataReceiverTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/socket/EzySocketDataReceiverTest.java @@ -23,186 +23,186 @@ public class EzySocketDataReceiverTest { - @Test - public void tcpReadBytesClosedChannelException() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySocketDataReceiver sut = EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .build(); - - ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3}); - - SocketChannel channel = mock(SocketChannel.class); - when(channel.read(buffer)).thenThrow(new ClosedChannelException()); - - // when - MethodInvoker.create() - .object(sut) - .method("tcpReadBytes") - .param(SocketChannel.class, channel) - .param(ByteBuffer.class, buffer) - .call(); - - // then - verify(handlerGroupManager, times(1)).getHandlerGroup(channel); - } - - @Test - public void processReadBytesHandlerGroupIsNull() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySocketDataReceiver sut = EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .build(); - - ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3}); - - SocketChannel channel = mock(SocketChannel.class); - when(channel.read(buffer)).thenThrow(new ClosedChannelException()); - - // when - MethodInvoker.create() - .object(sut) - .method("processReadBytes") - .param(SocketChannel.class, channel) - .param(ByteBuffer.class, buffer) - .call(); - - // then - verify(handlerGroupManager, times(1)).getHandlerGroup(channel); - } - - @Test - public void udpReceiveTest() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySocketDataReceiver sut = EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .threadPoolSize(1) - .build(); - - SocketChannel channel = mock(SocketChannel.class); - - EzyMessage message = mock(EzyMessage.class); - - EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); - when(handlerGroupManager.getHandlerGroup(channel)).thenReturn(handlerGroup); - - // when - sut.udpReceive(channel, message); - Thread.sleep(120); - - // then - verify(handlerGroupManager, times(1)).getHandlerGroup(channel); - verify(handlerGroup, times(1)).fireMessageReceived(message); - sut.destroy(); - } - - @Test - public void udpReceiveButHandlerGroupNullTest() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySocketDataReceiver sut = EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .threadPoolSize(1) - .build(); - - SocketChannel channel = mock(SocketChannel.class); - - EzyMessage message = mock(EzyMessage.class); - - // when - sut.udpReceive(channel, message); - Thread.sleep(120); - - // then - verify(handlerGroupManager, times(1)).getHandlerGroup(channel); - sut.destroy(); - } - - @Test - public void udpReceiveButExceptionTest() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySocketDataReceiver sut = EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .threadPoolSize(1) - .build(); - - SocketChannel channel = mock(SocketChannel.class); - - EzyMessage message = mock(EzyMessage.class); - - EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); - doThrow(new RuntimeException()).when(handlerGroup).fireMessageReceived(message); - when(handlerGroupManager.getHandlerGroup(channel)).thenReturn(handlerGroup); - - // when - sut.udpReceive(channel, message); - Thread.sleep(120); - - // then - verify(handlerGroupManager, times(1)).getHandlerGroup(channel); - verify(handlerGroup, times(1)).fireMessageReceived(message); - sut.destroy(); - } - - @Test - public void wsReceive0ButException() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySocketDataReceiver sut = EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .build(); - - Session session = mock(Session.class); - String message = RandomUtil.randomShortAlphabetString(); - - EzyWsHandlerGroup handlerGroup = mock(EzyWsHandlerGroup.class); - doThrow(new RuntimeException()).when(handlerGroup).fireBytesReceived(message); - when(handlerGroupManager.getHandlerGroup(session)).thenReturn(handlerGroup); - - // when - MethodInvoker.create() - .object(sut) - .method("wsReceive0") - .param(Session.class, session) - .param(String.class, message) - .call(); - - // then - verify(handlerGroupManager, times(1)).getHandlerGroup(session); - verify(handlerGroup, times(1)).fireBytesReceived(message); - } - - @Test - public void wsReceive02ButException() throws Exception { - // given - EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); - EzySocketDataReceiver sut = EzySocketDataReceiver.builder() - .handlerGroupManager(handlerGroupManager) - .build(); - - Session session = mock(Session.class); - byte[] payload = new byte[] {1, 2, 3}; - - EzyWsHandlerGroup handlerGroup = mock(EzyWsHandlerGroup.class); - doThrow(new RuntimeException()).when(handlerGroup).fireBytesReceived(payload, 0, payload.length); - when(handlerGroupManager.getHandlerGroup(session)).thenReturn(handlerGroup); - - // when - MethodInvoker.create() - .object(sut) - .method("wsReceive0") - .param(Session.class, session) - .param(byte[].class, payload) - .param(int.class, 0) - .param(int.class, payload.length) - .call(); - - // then - verify(handlerGroupManager, times(1)).getHandlerGroup(session); - verify(handlerGroup, times(1)).fireBytesReceived(payload, 0, payload.length); - } + @Test + public void tcpReadBytesClosedChannelException() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySocketDataReceiver sut = EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .build(); + + ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3}); + + SocketChannel channel = mock(SocketChannel.class); + when(channel.read(buffer)).thenThrow(new ClosedChannelException()); + + // when + MethodInvoker.create() + .object(sut) + .method("tcpReadBytes") + .param(SocketChannel.class, channel) + .param(ByteBuffer.class, buffer) + .call(); + + // then + verify(handlerGroupManager, times(1)).getHandlerGroup(channel); + } + + @Test + public void processReadBytesHandlerGroupIsNull() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySocketDataReceiver sut = EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .build(); + + ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3}); + + SocketChannel channel = mock(SocketChannel.class); + when(channel.read(buffer)).thenThrow(new ClosedChannelException()); + + // when + MethodInvoker.create() + .object(sut) + .method("processReadBytes") + .param(SocketChannel.class, channel) + .param(ByteBuffer.class, buffer) + .call(); + + // then + verify(handlerGroupManager, times(1)).getHandlerGroup(channel); + } + + @Test + public void udpReceiveTest() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySocketDataReceiver sut = EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .threadPoolSize(1) + .build(); + + SocketChannel channel = mock(SocketChannel.class); + + EzyMessage message = mock(EzyMessage.class); + + EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); + when(handlerGroupManager.getHandlerGroup(channel)).thenReturn(handlerGroup); + + // when + sut.udpReceive(channel, message); + Thread.sleep(120); + + // then + verify(handlerGroupManager, times(1)).getHandlerGroup(channel); + verify(handlerGroup, times(1)).fireMessageReceived(message); + sut.destroy(); + } + + @Test + public void udpReceiveButHandlerGroupNullTest() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySocketDataReceiver sut = EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .threadPoolSize(1) + .build(); + + SocketChannel channel = mock(SocketChannel.class); + + EzyMessage message = mock(EzyMessage.class); + + // when + sut.udpReceive(channel, message); + Thread.sleep(120); + + // then + verify(handlerGroupManager, times(1)).getHandlerGroup(channel); + sut.destroy(); + } + + @Test + public void udpReceiveButExceptionTest() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySocketDataReceiver sut = EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .threadPoolSize(1) + .build(); + + SocketChannel channel = mock(SocketChannel.class); + + EzyMessage message = mock(EzyMessage.class); + + EzyNioHandlerGroup handlerGroup = mock(EzyNioHandlerGroup.class); + doThrow(new RuntimeException()).when(handlerGroup).fireMessageReceived(message); + when(handlerGroupManager.getHandlerGroup(channel)).thenReturn(handlerGroup); + + // when + sut.udpReceive(channel, message); + Thread.sleep(120); + + // then + verify(handlerGroupManager, times(1)).getHandlerGroup(channel); + verify(handlerGroup, times(1)).fireMessageReceived(message); + sut.destroy(); + } + + @Test + public void wsReceive0ButException() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySocketDataReceiver sut = EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .build(); + + Session session = mock(Session.class); + String message = RandomUtil.randomShortAlphabetString(); + + EzyWsHandlerGroup handlerGroup = mock(EzyWsHandlerGroup.class); + doThrow(new RuntimeException()).when(handlerGroup).fireBytesReceived(message); + when(handlerGroupManager.getHandlerGroup(session)).thenReturn(handlerGroup); + + // when + MethodInvoker.create() + .object(sut) + .method("wsReceive0") + .param(Session.class, session) + .param(String.class, message) + .call(); + + // then + verify(handlerGroupManager, times(1)).getHandlerGroup(session); + verify(handlerGroup, times(1)).fireBytesReceived(message); + } + + @Test + public void wsReceive02ButException() throws Exception { + // given + EzyHandlerGroupManager handlerGroupManager = mock(EzyHandlerGroupManager.class); + EzySocketDataReceiver sut = EzySocketDataReceiver.builder() + .handlerGroupManager(handlerGroupManager) + .build(); + + Session session = mock(Session.class); + byte[] payload = new byte[] {1, 2, 3}; + + EzyWsHandlerGroup handlerGroup = mock(EzyWsHandlerGroup.class); + doThrow(new RuntimeException()).when(handlerGroup).fireBytesReceived(payload, 0, payload.length); + when(handlerGroupManager.getHandlerGroup(session)).thenReturn(handlerGroup); + + // when + MethodInvoker.create() + .object(sut) + .method("wsReceive0") + .param(Session.class, session) + .param(byte[].class, payload) + .param(int.class, 0) + .param(int.class, payload.length) + .call(); + + // then + verify(handlerGroupManager, times(1)).getHandlerGroup(session); + verify(handlerGroup, times(1)).fireBytesReceived(payload, 0, payload.length); + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/udp/EzyNioUdpReaderTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/udp/EzyNioUdpReaderTest.java index 2fa5372a9..db7cfbbf6 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/udp/EzyNioUdpReaderTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/udp/EzyNioUdpReaderTest.java @@ -30,183 +30,183 @@ public class EzyNioUdpReaderTest { - @Test - public void test() throws Exception { - EzyNioUdpReader reader = new EzyNioUdpReader(1); - Selector selector = spy(Selector.class); - when(selector.select()).thenReturn(1); - reader.setOwnSelector(selector); - EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); - reader.setUdpDataHandler(dataHandler); - SelectionKey selectionKey = spy(SelectionKey.class); - when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); - when(selectionKey.isValid()).thenReturn(true); - when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); - MyDatagramChannel channel = mock(MyDatagramChannel.class); - when(selectionKey.channel()).thenReturn(channel); - when(channel.receive(any(ByteBuffer.class))).thenAnswer(new Answer() { - @Override - public InetSocketAddress answer(InvocationOnMock invocation) throws Throwable { - ByteBuffer buffer = invocation.getArgumentAt(0, ByteBuffer.class); - buffer.put((byte)0); - return new InetSocketAddress(12346); - } - }); - reader.handleEvent(); - } - - @Test - public void testAddressNull() throws Exception { - EzyNioUdpReader reader = new EzyNioUdpReader(1); - Selector selector = spy(Selector.class); - when(selector.select()).thenReturn(1); - reader.setOwnSelector(selector); - EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); - reader.setUdpDataHandler(dataHandler); - SelectionKey selectionKey = spy(SelectionKey.class); - when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); - when(selectionKey.isValid()).thenReturn(true); - when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); - MyDatagramChannel channel = mock(MyDatagramChannel.class); - when(selectionKey.channel()).thenReturn(channel); - reader.handleEvent(); - } - - @Test - public void testClosedSelectorExceptionCase() throws Exception { - EzyNioUdpReader reader = new EzyNioUdpReader(1); - Selector selector = spy(Selector.class); - when(selector.select()).thenReturn(1); - reader.setOwnSelector(selector); - EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); - reader.setUdpDataHandler(dataHandler); - SelectionKey selectionKey = spy(SelectionKey.class); - when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); - when(selectionKey.isValid()).thenReturn(true); - when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); - MyDatagramChannel channel = mock(MyDatagramChannel.class); - when(selectionKey.channel()).thenReturn(channel); - when(channel.receive(any(ByteBuffer.class))).thenThrow(new ClosedSelectorException()); - reader.handleEvent(); - } - - @Test - public void testCancelledKeyExceptionCase() throws Exception { - EzyNioUdpReader reader = new EzyNioUdpReader(1); - Selector selector = spy(Selector.class); - when(selector.select()).thenReturn(1); - reader.setOwnSelector(selector); - EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); - reader.setUdpDataHandler(dataHandler); - SelectionKey selectionKey = spy(SelectionKey.class); - when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); - when(selectionKey.isValid()).thenReturn(true); - when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); - MyDatagramChannel channel = mock(MyDatagramChannel.class); - when(selectionKey.channel()).thenReturn(channel); - when(channel.receive(any(ByteBuffer.class))).thenThrow(new CancelledKeyException()); - reader.handleEvent(); - } - - @Test - public void testIOExceptionCase() throws Exception { - EzyNioUdpReader reader = new EzyNioUdpReader(1); - Selector selector = spy(Selector.class); - when(selector.select()).thenReturn(1); - reader.setOwnSelector(selector); - EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); - reader.setUdpDataHandler(dataHandler); - SelectionKey selectionKey = spy(SelectionKey.class); - when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); - when(selectionKey.isValid()).thenReturn(true); - when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); - MyDatagramChannel channel = mock(MyDatagramChannel.class); - when(selectionKey.channel()).thenReturn(channel); - when(channel.receive(any(ByteBuffer.class))).thenThrow(new IOException("test")); - reader.handleEvent(); - } - - @Test - public void testExceptionCase() throws Exception { - EzyNioUdpReader reader = new EzyNioUdpReader(1); - Selector selector = spy(Selector.class); - when(selector.select()).thenReturn(1); - reader.setOwnSelector(selector); - EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); - reader.setUdpDataHandler(dataHandler); - SelectionKey selectionKey = spy(SelectionKey.class); - when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); - when(selectionKey.isValid()).thenReturn(true); - when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); - MyDatagramChannel channel = mock(MyDatagramChannel.class); - when(selectionKey.channel()).thenReturn(channel); - when(channel.receive(any(ByteBuffer.class))).thenThrow(new IllegalStateException("test")); - reader.handleEvent(); - } - - @Test - public void processReadyKeysKeyInvalid() throws IOException { - // given - Selector ownSelector = mock(Selector.class); - EzyNioUdpReader sut = new EzyNioUdpReader(1024); - sut.setOwnSelector(ownSelector); - - SelectionKey selectionKey = mock(SelectionKey.class); - when(selectionKey.isValid()).thenReturn(false); - Set selectionKeys = Sets.newHashSet(selectionKey); - when(ownSelector.selectedKeys()).thenReturn(selectionKeys); - - // when - MethodUtil.invokeMethod("processReadyKeys", sut); - - // then - verify(selectionKey, times(1)).isValid(); - } - - @Test - public void processReadyKeyNotReadable() throws IOException { - // given - EzyNioUdpReader sut = new EzyNioUdpReader(1024); - - SelectionKey selectionKey = mock(SelectionKey.class); - when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE); - - // when - MethodInvoker.create() - .object(sut) - .method("processReadyKey") - .param(SelectionKey.class, selectionKey) - .call(); - - // then - verify(selectionKey, times(1)).readyOps(); - } - - @Test - public void processReadBytesByteCountLessIsZero() throws IOException { - // given - EzyNioUdpReader sut = new EzyNioUdpReader(1024); - - DatagramChannel channel = mock(DatagramChannel.class); - InetSocketAddress address = new InetSocketAddress(3005); - when(channel.receive(any())).thenReturn(address); - - // when - MethodInvoker.create() - .object(sut) - .method("processReadBytes") - .param(DatagramChannel.class, channel) - .call(); - - // then - verify(channel, times(1)).receive(any()); - } - - public abstract static class MyDatagramChannel extends DatagramChannel { - - protected MyDatagramChannel() { - super(SelectorProvider.provider()); - } - - } + @Test + public void test() throws Exception { + EzyNioUdpReader reader = new EzyNioUdpReader(1); + Selector selector = spy(Selector.class); + when(selector.select()).thenReturn(1); + reader.setOwnSelector(selector); + EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); + reader.setUdpDataHandler(dataHandler); + SelectionKey selectionKey = spy(SelectionKey.class); + when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); + when(selectionKey.isValid()).thenReturn(true); + when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); + MyDatagramChannel channel = mock(MyDatagramChannel.class); + when(selectionKey.channel()).thenReturn(channel); + when(channel.receive(any(ByteBuffer.class))).thenAnswer(new Answer() { + @Override + public InetSocketAddress answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer buffer = invocation.getArgumentAt(0, ByteBuffer.class); + buffer.put((byte)0); + return new InetSocketAddress(12346); + } + }); + reader.handleEvent(); + } + + @Test + public void testAddressNull() throws Exception { + EzyNioUdpReader reader = new EzyNioUdpReader(1); + Selector selector = spy(Selector.class); + when(selector.select()).thenReturn(1); + reader.setOwnSelector(selector); + EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); + reader.setUdpDataHandler(dataHandler); + SelectionKey selectionKey = spy(SelectionKey.class); + when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); + when(selectionKey.isValid()).thenReturn(true); + when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); + MyDatagramChannel channel = mock(MyDatagramChannel.class); + when(selectionKey.channel()).thenReturn(channel); + reader.handleEvent(); + } + + @Test + public void testClosedSelectorExceptionCase() throws Exception { + EzyNioUdpReader reader = new EzyNioUdpReader(1); + Selector selector = spy(Selector.class); + when(selector.select()).thenReturn(1); + reader.setOwnSelector(selector); + EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); + reader.setUdpDataHandler(dataHandler); + SelectionKey selectionKey = spy(SelectionKey.class); + when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); + when(selectionKey.isValid()).thenReturn(true); + when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); + MyDatagramChannel channel = mock(MyDatagramChannel.class); + when(selectionKey.channel()).thenReturn(channel); + when(channel.receive(any(ByteBuffer.class))).thenThrow(new ClosedSelectorException()); + reader.handleEvent(); + } + + @Test + public void testCancelledKeyExceptionCase() throws Exception { + EzyNioUdpReader reader = new EzyNioUdpReader(1); + Selector selector = spy(Selector.class); + when(selector.select()).thenReturn(1); + reader.setOwnSelector(selector); + EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); + reader.setUdpDataHandler(dataHandler); + SelectionKey selectionKey = spy(SelectionKey.class); + when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); + when(selectionKey.isValid()).thenReturn(true); + when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); + MyDatagramChannel channel = mock(MyDatagramChannel.class); + when(selectionKey.channel()).thenReturn(channel); + when(channel.receive(any(ByteBuffer.class))).thenThrow(new CancelledKeyException()); + reader.handleEvent(); + } + + @Test + public void testIOExceptionCase() throws Exception { + EzyNioUdpReader reader = new EzyNioUdpReader(1); + Selector selector = spy(Selector.class); + when(selector.select()).thenReturn(1); + reader.setOwnSelector(selector); + EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); + reader.setUdpDataHandler(dataHandler); + SelectionKey selectionKey = spy(SelectionKey.class); + when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); + when(selectionKey.isValid()).thenReturn(true); + when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); + MyDatagramChannel channel = mock(MyDatagramChannel.class); + when(selectionKey.channel()).thenReturn(channel); + when(channel.receive(any(ByteBuffer.class))).thenThrow(new IOException("test")); + reader.handleEvent(); + } + + @Test + public void testExceptionCase() throws Exception { + EzyNioUdpReader reader = new EzyNioUdpReader(1); + Selector selector = spy(Selector.class); + when(selector.select()).thenReturn(1); + reader.setOwnSelector(selector); + EzyNioUdpDataHandler dataHandler = mock(EzyNioUdpDataHandler.class); + reader.setUdpDataHandler(dataHandler); + SelectionKey selectionKey = spy(SelectionKey.class); + when(selector.selectedKeys()).thenReturn(Sets.newHashSet(selectionKey)); + when(selectionKey.isValid()).thenReturn(true); + when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_READ); + MyDatagramChannel channel = mock(MyDatagramChannel.class); + when(selectionKey.channel()).thenReturn(channel); + when(channel.receive(any(ByteBuffer.class))).thenThrow(new IllegalStateException("test")); + reader.handleEvent(); + } + + @Test + public void processReadyKeysKeyInvalid() throws IOException { + // given + Selector ownSelector = mock(Selector.class); + EzyNioUdpReader sut = new EzyNioUdpReader(1024); + sut.setOwnSelector(ownSelector); + + SelectionKey selectionKey = mock(SelectionKey.class); + when(selectionKey.isValid()).thenReturn(false); + Set selectionKeys = Sets.newHashSet(selectionKey); + when(ownSelector.selectedKeys()).thenReturn(selectionKeys); + + // when + MethodUtil.invokeMethod("processReadyKeys", sut); + + // then + verify(selectionKey, times(1)).isValid(); + } + + @Test + public void processReadyKeyNotReadable() throws IOException { + // given + EzyNioUdpReader sut = new EzyNioUdpReader(1024); + + SelectionKey selectionKey = mock(SelectionKey.class); + when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE); + + // when + MethodInvoker.create() + .object(sut) + .method("processReadyKey") + .param(SelectionKey.class, selectionKey) + .call(); + + // then + verify(selectionKey, times(1)).readyOps(); + } + + @Test + public void processReadBytesByteCountLessIsZero() throws IOException { + // given + EzyNioUdpReader sut = new EzyNioUdpReader(1024); + + DatagramChannel channel = mock(DatagramChannel.class); + InetSocketAddress address = new InetSocketAddress(3005); + when(channel.receive(any())).thenReturn(address); + + // when + MethodInvoker.create() + .object(sut) + .method("processReadBytes") + .param(DatagramChannel.class, channel) + .call(); + + // then + verify(channel, times(1)).receive(any()); + } + + public abstract static class MyDatagramChannel extends DatagramChannel { + + protected MyDatagramChannel() { + super(SelectorProvider.provider()); + } + + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzySimpleWsHandlerGroupTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzySimpleWsHandlerGroupTest.java index 1e2a8acc1..8b96c2f2d 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzySimpleWsHandlerGroupTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzySimpleWsHandlerGroupTest.java @@ -62,340 +62,340 @@ public class EzySimpleWsHandlerGroupTest extends BaseTest { - @SuppressWarnings("rawtypes") - @Test - public void test() throws Exception { - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - - EzyServerControllers controllers = mock(EzyServerControllers.class); - server.setControllers(controllers); - - EzyInterceptor interceptor = mock(EzyInterceptor.class); - when(controllers.getInterceptor(EzyCommand.PING)).thenReturn(interceptor); - - EzyController controller = mock(EzyController.class); - when(controllers.getController(EzyCommand.PING)).thenReturn(controller); - - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); - EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue) - .codecFactory(new ExCodecFactory()) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .build(); - - EzySimpleWsHandlerGroup group = (EzySimpleWsHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.WEBSOCKET) - .build(); - - group.fireBytesReceived("hello"); - group.fireBytesReceived(new byte[] {127, 2, 3, 4, 5, 6}, 0, 5); - ((EzyAbstractSession)session).setStreamingEnable(true); - group.fireBytesReceived(new byte[] {127, 2, 3, 4, 5, 6}, 0, 5); - EzySimplePacket packet = new EzySimplePacket(); - packet.setBinary(false); - packet.setData("world".getBytes()); - packet.setTransportType(EzyTransportType.TCP); - ByteBuffer writeBuffer = ByteBuffer.allocate(1024); - group.firePacketSend(packet, writeBuffer); - group.sendPacketNow(packet); - group.fireChannelRead(EzyCommand.PING, EzyEntityArrays.newArray(EzyCommand.PING.getId(), EzyEntityFactory.EMPTY_ARRAY)); - - EzyInterceptor streamInterceptor = mock(EzyInterceptor.class); - when(controllers.getStreamingInterceptor()).thenReturn(streamInterceptor); - - EzyStreamingController streamController = mock(EzyStreamingController.class); - when(controllers.getStreamingController()).thenReturn(streamController); - - group.fireStreamBytesReceived(new byte[] {0, 1, 2}); - - EzyPacket droppedPacket = mock(EzyPacket.class); - when(droppedPacket.getSize()).thenReturn(12); - group.addDroppedPacket(droppedPacket); - EzyPacket failedPacket = mock(EzyPacket.class); - when(failedPacket.getData()).thenReturn(new byte[] {1, 2, 3}); - when(failedPacket.isBinary()).thenReturn(false); - when(channel.write(any(ByteBuffer.class), anyBoolean())).thenThrow(new IllegalStateException("maintain")); - group.firePacketSend(failedPacket, writeBuffer); - - MethodInvoker.create() - .object(group) - .method("executeHandleReceivedBytes") - .param("hello") - .invoke(); - - MethodInvoker.create() - .object(group) - .method("executeHandleReceivedBytes") - .param("hello".getBytes()) - .invoke(); - - group.fireChannelInactive(); - Thread.sleep(2000); - group.destroy(); - group.destroy(); - - EzySocketStreamQueue streamQueue1 = mock(EzySocketStreamQueue.class); - when(streamQueue1.add(any())).thenThrow(new IllegalStateException("queue full")); - group = (EzySimpleWsHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.WEBSOCKET) - .session(session) - .decoder(decoder) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue1) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - group.fireBytesReceived(new byte[] {127, 2, 3, 4, 5, 6}, 0, 5); - } - - @Test - public void newDecodeBytesCallbackCallTest() throws Exception { - // given - EzyWsHandlerGroup sut = newHandlerGroup(); - - EzyCallback decodeBytesCallback = FieldUtil.getFieldValue(sut, "decodeBytesCallback"); - - // when - Throwable e = Asserts.assertThrows(() -> decodeBytesCallback.call(new Object())); - - // then - Asserts.assertEquals(UnsupportedOperationException.class, e.getClass()); - } - - @Test - public void handleReceivedBytesLenLowerThan1() throws Exception { - // given - EzyWsHandlerGroup sut = newHandlerGroup(); - - byte[] bytes = new byte[0]; - int offset = 0; - int len = 0; - - // when - // then - MethodInvoker.create() - .object(sut) - .method("handleReceivedBytes") - .param(byte[].class, bytes) - .param(int.class, offset) - .param(int.class, len) - .call(); - } - - @Test - public void handleReceivedStreamNotEnable() throws Exception { - // given - EzyWsHandlerGroup sut = newHandlerGroup(false); - - byte[] bytes = new byte[] {1 << 4, 2, 3}; - int offset = 0; - int len = 3; - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedBytes") - .param(byte[].class, bytes) - .param(int.class, offset) - .param(int.class, len) - .call(); - - // then - EzySession session = FieldUtil.getFieldValue(sut, "session"); - verify(session, times(1)).isStreamingEnable(); - } - - @Test - public void handleReceivedStreamEnableAndSessionStream() throws Exception { - // given - EzyWsHandlerGroup sut = newHandlerGroup(); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - when(session.isStreamingEnable()).thenReturn(true); - - byte[] bytes = new byte[] {1 << 4, 2, 3}; - int offset = 0; - int len = 3; - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedBytes") - .param(byte[].class, bytes) - .param(int.class, offset) - .param(int.class, len) - .call(); - - // then - verify(session, times(1)).isStreamingEnable(); - } - - @Test - public void handleReceivedSessionStreamNotEnable() throws Exception { - // given - EzyWsHandlerGroup sut = newHandlerGroup(); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - - byte[] bytes = new byte[] {1 << 4, 2, 3}; - int offset = 0; - int len = 3; - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedBytes") - .param(byte[].class, bytes) - .param(int.class, offset) - .param(int.class, len) - .call(); - - // then - verify(session, times(1)).isStreamingEnable(); - } - - @Test - public void handleReceivedSessionStreamEnable() throws Exception { - // given - EzyWsHandlerGroup sut = newHandlerGroup(); - - EzySession session = FieldUtil.getFieldValue(sut, "session"); - when(session.isStreamingEnable()).thenReturn(true); - - byte[] bytes = new byte[] {1 << 4, 2, 3}; - int offset = 0; - int len = 3; - - // when - MethodInvoker.create() - .object(sut) - .method("handleReceivedBytes") - .param(byte[].class, bytes) - .param(int.class, offset) - .param(int.class, len) - .call(); - - // then - verify(session, times(1)).isStreamingEnable(); - } - - private EzySimpleWsHandlerGroup newHandlerGroup() throws IOException { - return newHandlerGroup(true); - } - - @SuppressWarnings("rawtypes") - private EzySimpleWsHandlerGroup newHandlerGroup(boolean streamEnable) throws IOException { - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(streamEnable); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - - EzyServerControllers controllers = mock(EzyServerControllers.class); - server.setControllers(controllers); - - EzySimpleConfig config = new EzySimpleConfig(); - server.setConfig(config); - - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzyChannel channel = mock(EzyChannel.class); - when(channel.isConnected()).thenReturn(true); - when(channel.getConnection()).thenReturn(SocketChannel.open()); - when(channel.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); - ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzySimpleSession session = mock(EzySimpleSession.class); - when(session.getChannel()).thenReturn(channel); - - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .serverContext(serverContext) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue) - .codecFactory(new ExCodecFactory()) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .build(); - - EzySimpleWsHandlerGroup group = (EzySimpleWsHandlerGroup) handlerGroupBuilderFactory - .newBuilder(channel, EzyConnectionType.WEBSOCKET) - .session(session) - .build(); - return group; - } - - public static class ExCodecFactory implements EzyCodecFactory { - @Override - public Object newDecoder(EzyConstant type) { - return new ExEzyByteToObjectDecoder(); - } - - @Override - public Object newEncoder(EzyConstant type) { - return null; - } - } - - public static class ExEzyByteToObjectDecoder implements EzyStringToObjectDecoder { - - @Override - public Object decode(String bytes) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - @Override - public Object decode(byte[] bytes) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - } - + @SuppressWarnings("rawtypes") + @Test + public void test() throws Exception { + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + + EzyServerControllers controllers = mock(EzyServerControllers.class); + server.setControllers(controllers); + + EzyInterceptor interceptor = mock(EzyInterceptor.class); + when(controllers.getInterceptor(EzyCommand.PING)).thenReturn(interceptor); + + EzyController controller = mock(EzyController.class); + when(controllers.getController(EzyCommand.PING)).thenReturn(controller); + + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); + EzyNioSession session = (EzyNioSession) sessionManager.provideSession(channel); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue) + .codecFactory(new ExCodecFactory()) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .build(); + + EzySimpleWsHandlerGroup group = (EzySimpleWsHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.WEBSOCKET) + .build(); + + group.fireBytesReceived("hello"); + group.fireBytesReceived(new byte[] {127, 2, 3, 4, 5, 6}, 0, 5); + ((EzyAbstractSession)session).setStreamingEnable(true); + group.fireBytesReceived(new byte[] {127, 2, 3, 4, 5, 6}, 0, 5); + EzySimplePacket packet = new EzySimplePacket(); + packet.setBinary(false); + packet.setData("world".getBytes()); + packet.setTransportType(EzyTransportType.TCP); + ByteBuffer writeBuffer = ByteBuffer.allocate(1024); + group.firePacketSend(packet, writeBuffer); + group.sendPacketNow(packet); + group.fireChannelRead(EzyCommand.PING, EzyEntityArrays.newArray(EzyCommand.PING.getId(), EzyEntityFactory.EMPTY_ARRAY)); + + EzyInterceptor streamInterceptor = mock(EzyInterceptor.class); + when(controllers.getStreamingInterceptor()).thenReturn(streamInterceptor); + + EzyStreamingController streamController = mock(EzyStreamingController.class); + when(controllers.getStreamingController()).thenReturn(streamController); + + group.fireStreamBytesReceived(new byte[] {0, 1, 2}); + + EzyPacket droppedPacket = mock(EzyPacket.class); + when(droppedPacket.getSize()).thenReturn(12); + group.addDroppedPacket(droppedPacket); + EzyPacket failedPacket = mock(EzyPacket.class); + when(failedPacket.getData()).thenReturn(new byte[] {1, 2, 3}); + when(failedPacket.isBinary()).thenReturn(false); + when(channel.write(any(ByteBuffer.class), anyBoolean())).thenThrow(new IllegalStateException("maintain")); + group.firePacketSend(failedPacket, writeBuffer); + + MethodInvoker.create() + .object(group) + .method("executeHandleReceivedBytes") + .param("hello") + .invoke(); + + MethodInvoker.create() + .object(group) + .method("executeHandleReceivedBytes") + .param("hello".getBytes()) + .invoke(); + + group.fireChannelInactive(); + Thread.sleep(2000); + group.destroy(); + group.destroy(); + + EzySocketStreamQueue streamQueue1 = mock(EzySocketStreamQueue.class); + when(streamQueue1.add(any())).thenThrow(new IllegalStateException("queue full")); + group = (EzySimpleWsHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.WEBSOCKET) + .session(session) + .decoder(decoder) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue1) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + group.fireBytesReceived(new byte[] {127, 2, 3, 4, 5, 6}, 0, 5); + } + + @Test + public void newDecodeBytesCallbackCallTest() throws Exception { + // given + EzyWsHandlerGroup sut = newHandlerGroup(); + + EzyCallback decodeBytesCallback = FieldUtil.getFieldValue(sut, "decodeBytesCallback"); + + // when + Throwable e = Asserts.assertThrows(() -> decodeBytesCallback.call(new Object())); + + // then + Asserts.assertEquals(UnsupportedOperationException.class, e.getClass()); + } + + @Test + public void handleReceivedBytesLenLowerThan1() throws Exception { + // given + EzyWsHandlerGroup sut = newHandlerGroup(); + + byte[] bytes = new byte[0]; + int offset = 0; + int len = 0; + + // when + // then + MethodInvoker.create() + .object(sut) + .method("handleReceivedBytes") + .param(byte[].class, bytes) + .param(int.class, offset) + .param(int.class, len) + .call(); + } + + @Test + public void handleReceivedStreamNotEnable() throws Exception { + // given + EzyWsHandlerGroup sut = newHandlerGroup(false); + + byte[] bytes = new byte[] {1 << 4, 2, 3}; + int offset = 0; + int len = 3; + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedBytes") + .param(byte[].class, bytes) + .param(int.class, offset) + .param(int.class, len) + .call(); + + // then + EzySession session = FieldUtil.getFieldValue(sut, "session"); + verify(session, times(1)).isStreamingEnable(); + } + + @Test + public void handleReceivedStreamEnableAndSessionStream() throws Exception { + // given + EzyWsHandlerGroup sut = newHandlerGroup(); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + when(session.isStreamingEnable()).thenReturn(true); + + byte[] bytes = new byte[] {1 << 4, 2, 3}; + int offset = 0; + int len = 3; + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedBytes") + .param(byte[].class, bytes) + .param(int.class, offset) + .param(int.class, len) + .call(); + + // then + verify(session, times(1)).isStreamingEnable(); + } + + @Test + public void handleReceivedSessionStreamNotEnable() throws Exception { + // given + EzyWsHandlerGroup sut = newHandlerGroup(); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + + byte[] bytes = new byte[] {1 << 4, 2, 3}; + int offset = 0; + int len = 3; + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedBytes") + .param(byte[].class, bytes) + .param(int.class, offset) + .param(int.class, len) + .call(); + + // then + verify(session, times(1)).isStreamingEnable(); + } + + @Test + public void handleReceivedSessionStreamEnable() throws Exception { + // given + EzyWsHandlerGroup sut = newHandlerGroup(); + + EzySession session = FieldUtil.getFieldValue(sut, "session"); + when(session.isStreamingEnable()).thenReturn(true); + + byte[] bytes = new byte[] {1 << 4, 2, 3}; + int offset = 0; + int len = 3; + + // when + MethodInvoker.create() + .object(sut) + .method("handleReceivedBytes") + .param(byte[].class, bytes) + .param(int.class, offset) + .param(int.class, len) + .call(); + + // then + verify(session, times(1)).isStreamingEnable(); + } + + private EzySimpleWsHandlerGroup newHandlerGroup() throws IOException { + return newHandlerGroup(true); + } + + @SuppressWarnings("rawtypes") + private EzySimpleWsHandlerGroup newHandlerGroup(boolean streamEnable) throws IOException { + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionManager sessionManager = EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(streamEnable); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + + EzyServerControllers controllers = mock(EzyServerControllers.class); + server.setControllers(controllers); + + EzySimpleConfig config = new EzySimpleConfig(); + server.setConfig(config); + + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzyChannel channel = mock(EzyChannel.class); + when(channel.isConnected()).thenReturn(true); + when(channel.getConnection()).thenReturn(SocketChannel.open()); + when(channel.getConnectionType()).thenReturn(EzyConnectionType.WEBSOCKET); + ExecutorService statsThreadPool = EzyExecutors.newFixedThreadPool(1, "stats"); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzySimpleSession session = mock(EzySimpleSession.class); + when(session.getChannel()).thenReturn(channel); + + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .serverContext(serverContext) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue) + .codecFactory(new ExCodecFactory()) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .build(); + + EzySimpleWsHandlerGroup group = (EzySimpleWsHandlerGroup) handlerGroupBuilderFactory + .newBuilder(channel, EzyConnectionType.WEBSOCKET) + .session(session) + .build(); + return group; + } + + public static class ExCodecFactory implements EzyCodecFactory { + @Override + public Object newDecoder(EzyConstant type) { + return new ExEzyByteToObjectDecoder(); + } + + @Override + public Object newEncoder(EzyConstant type) { + return null; + } + } + + public static class ExEzyByteToObjectDecoder implements EzyStringToObjectDecoder { + + @Override + public Object decode(String bytes) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + @Override + public Object decode(byte[] bytes) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsChannelTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsChannelTest.java index ce4eeb576..0ec0cbae0 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsChannelTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsChannelTest.java @@ -17,27 +17,27 @@ public class EzyWsChannelTest extends BaseTest { - @Test - public void test() throws Exception { - Session session = mock(Session.class); - when(session.getLocalAddress()).thenReturn(new InetSocketAddress("0.0.0.0", 3005)); - EzyWsChannel channel = new EzyWsChannel(session); - assert channel.getSession() == session; - assert channel.isOpened(); - RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class); - when(session.getRemote()).thenReturn(remoteEndpoint); - System.out.println(channel.getServerAddress()); - assert channel.isConnected(); - channel.write("hello".getBytes(), true); - channel.write("hello", false); - doThrow(new WebSocketException("timeout")).when(remoteEndpoint).sendString("hello"); - channel.write("hello", false); - channel.disconnect(); - channel.close(); - doThrow(new IllegalStateException("maintain")).when(session).disconnect(); - doThrow(new IllegalStateException("maintain")).when(session).close(EzyWsCloseStatus.CLOSE_BY_SERVER); - channel.disconnect(); - channel.close(); - } - + @Test + public void test() throws Exception { + Session session = mock(Session.class); + when(session.getLocalAddress()).thenReturn(new InetSocketAddress("0.0.0.0", 3005)); + EzyWsChannel channel = new EzyWsChannel(session); + assert channel.getSession() == session; + assert channel.isOpened(); + RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class); + when(session.getRemote()).thenReturn(remoteEndpoint); + System.out.println(channel.getServerAddress()); + assert channel.isConnected(); + channel.write("hello".getBytes(), true); + channel.write("hello", false); + doThrow(new WebSocketException("timeout")).when(remoteEndpoint).sendString("hello"); + channel.write("hello", false); + channel.disconnect(); + channel.close(); + doThrow(new IllegalStateException("maintain")).when(session).disconnect(); + doThrow(new IllegalStateException("maintain")).when(session).close(EzyWsCloseStatus.CLOSE_BY_SERVER); + channel.disconnect(); + channel.close(); + } + } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsHandlerTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsHandlerTest.java index d1f50e8b7..147fb0e94 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsHandlerTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/websocket/EzyWsHandlerTest.java @@ -42,99 +42,99 @@ public class EzyWsHandlerTest extends BaseTest { - @Test - public void test() throws Exception { - EzySimpleSessionManagementSetting sessionManagementSetting = new EzySimpleSessionManagementSetting(); - EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); - ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue) - .disconnectionQueue(disconnectionQueue) - .codecFactory(codecFactory) - .serverContext(serverContext) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - - EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() - .handlerGroupBuilderFactory(handlerGroupBuilderFactory) - .build(); - - EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder() - .threadPoolSize(1) - .handlerGroupManager(handlerGroupManager) - .build(); - - EzyWsHandler handler = EzyWsHandler.builder() - .sessionManagementSetting(sessionManagementSetting) - .sessionManager(sessionManager) - .handlerGroupManager(handlerGroupManager) - .socketDataReceiver(socketDataReceiver) - .build(); - - Session session = mock(Session.class); - handler.onConnect(session); - handler.onMessage(session, "hello"); - handler.onMessage(session, "hello".getBytes(), 0, 5); - handler.onError(session, new TimeoutException("timeout")); - handler.onError(session, new IllegalStateException("maintain")); - handler.onClose(session, 39999, "test"); - handler.onClose(session, 3000, "test"); - Session session2 = mock(Session.class); - handler.onMessage(session2, "hello"); - handler.onMessage(session2, "hello".getBytes(), 0, 5); - handler.onError(session2, new TimeoutException("timeout")); - handler.onError(session2, new IllegalStateException("maintain")); - handler.onClose(session2, 39999, "test"); - handler.onClose(session2, 3000, "test"); - } - - @Test - public void setChannelClosedWithChannelNull() { - // given - EzyNioSessionManager sessionManager = mock(EzyNioSessionManager.class); - - EzyWsHandler sut = EzyWsHandler.builder() - .sessionManager(sessionManager) - .build(); - Session connection = mock(Session.class); - EzyNioSession session = mock(EzyNioSession.class); - - when(sessionManager.getSession(connection)).thenReturn(session); - - // when - MethodInvoker.create() - .object(sut) - .method("setChannelClosed") - .param(Session.class, connection) - .call(); - - // then - verify(sessionManager, times(1)).getSession(connection); - verify(session, times(1)).getChannel(); - } + @Test + public void test() throws Exception { + EzySimpleSessionManagementSetting sessionManagementSetting = new EzySimpleSessionManagementSetting(); + EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); + ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue) + .disconnectionQueue(disconnectionQueue) + .codecFactory(codecFactory) + .serverContext(serverContext) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + + EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() + .handlerGroupBuilderFactory(handlerGroupBuilderFactory) + .build(); + + EzySocketDataReceiver socketDataReceiver = EzySocketDataReceiver.builder() + .threadPoolSize(1) + .handlerGroupManager(handlerGroupManager) + .build(); + + EzyWsHandler handler = EzyWsHandler.builder() + .sessionManagementSetting(sessionManagementSetting) + .sessionManager(sessionManager) + .handlerGroupManager(handlerGroupManager) + .socketDataReceiver(socketDataReceiver) + .build(); + + Session session = mock(Session.class); + handler.onConnect(session); + handler.onMessage(session, "hello"); + handler.onMessage(session, "hello".getBytes(), 0, 5); + handler.onError(session, new TimeoutException("timeout")); + handler.onError(session, new IllegalStateException("maintain")); + handler.onClose(session, 39999, "test"); + handler.onClose(session, 3000, "test"); + Session session2 = mock(Session.class); + handler.onMessage(session2, "hello"); + handler.onMessage(session2, "hello".getBytes(), 0, 5); + handler.onError(session2, new TimeoutException("timeout")); + handler.onError(session2, new IllegalStateException("maintain")); + handler.onClose(session2, 39999, "test"); + handler.onClose(session2, 3000, "test"); + } + + @Test + public void setChannelClosedWithChannelNull() { + // given + EzyNioSessionManager sessionManager = mock(EzyNioSessionManager.class); + + EzyWsHandler sut = EzyWsHandler.builder() + .sessionManager(sessionManager) + .build(); + Session connection = mock(Session.class); + EzyNioSession session = mock(EzyNioSession.class); + + when(sessionManager.getSession(connection)).thenReturn(session); + + // when + MethodInvoker.create() + .object(sut) + .method("setChannelClosed") + .param(Session.class, connection) + .call(); + + // then + verify(sessionManager, times(1)).getSession(connection); + verify(session, times(1)).getChannel(); + } } diff --git a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/wrapper/EzyHandlerGroupManagerImplTest.java b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/wrapper/EzyHandlerGroupManagerImplTest.java index b533db5aa..b3617b569 100644 --- a/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/wrapper/EzyHandlerGroupManagerImplTest.java +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/wrapper/EzyHandlerGroupManagerImplTest.java @@ -46,229 +46,229 @@ public class EzyHandlerGroupManagerImplTest extends BaseTest { - @Test - public void test() { - EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); - when(codecFactory.newDecoder(any())).thenReturn(decoder); - ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue) - .disconnectionQueue(disconnectionQueue) - .codecFactory(codecFactory) - .serverContext(serverContext) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .socketSessionTicketsQueue(webSocketSessionTicketsQueue) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - - EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() - .handlerGroupBuilderFactory(handlerGroupBuilderFactory) - .build(); - handlerGroupManager.removeHandlerGroup(null); - EzySession session1 = mock(EzyAbstractSession.class); - handlerGroupManager.removeHandlerGroup(session1); - EzySession session2 = mock(EzyAbstractSession.class); - EzyChannel channel2 = mock(EzyChannel.class); - when(session2.getChannel()).thenReturn(channel2); - handlerGroupManager.removeHandlerGroup(session2); - EzyChannel channel3 = mock(EzyChannel.class); - Session connection3 = mock(Session.class); - when(channel3.getConnection()).thenReturn(connection3); - EzyHandlerGroup handlerGroup3 = handlerGroupManager.newHandlerGroup(channel3, EzyConnectionType.WEBSOCKET); - EzySession session3 = mock(EzyAbstractSession.class); - when(session3.getChannel()).thenReturn(channel3); - assert handlerGroupManager.getDataHandlerGroup(null) == null; - assert handlerGroupManager.getDataHandlerGroup(session1) == null; - assert handlerGroupManager.getDataHandlerGroup(session2) == null; - assert handlerGroupManager.getWriterGroup(session3) == handlerGroup3; - InetSocketAddress udpAddress = new InetSocketAddress("127.0.0.1", 12345); - handlerGroupManager.mapSocketChannel(udpAddress, session3); - assert handlerGroupManager.getSocketChannel(udpAddress) != null; - handlerGroupManager.unmapHandlerGroup(udpAddress); - handlerGroupManager.removeHandlerGroup(session3); - handlerGroupManager.destroy(); - } - - @Test - public void unmapHandlerGroupNullAddress() { - // given - EzyHandlerGroupManager sut = newHandlerGroupManager(); - - // when - // then - sut.unmapHandlerGroup(null); - } - - @Test - public void mapSocketChannelSessionNull() { - // given - EzyHandlerGroupManager sut = newHandlerGroupManager(); - - // when - // then - sut.mapSocketChannel(null, null); - } - - @Test - public void mapSocketChannelChannelNull() { - // given - EzyHandlerGroupManager sut = newHandlerGroupManager(); - - EzySession session = mock(EzySession.class); - - // when - sut.mapSocketChannel(null, session); - - // then - verify(session, times(1)).getChannel(); - } - - @Test - public void mapSocketChannelConnectionNull() { - // given - EzyHandlerGroupManager sut = newHandlerGroupManager(); - - EzySession session = mock(EzySession.class); - EzyChannel channel = mock(EzyChannel.class); - when(session.getChannel()).thenReturn(channel); - - // when - sut.mapSocketChannel(null, session); - - // then - verify(session, times(1)).getChannel(); - } - - @Test - public void mapSocketChannelNonContainsConnection() { - // given - EzyHandlerGroupManager sut = newHandlerGroupManager(); - - EzySession session = mock(EzySession.class); - EzyChannel channel = mock(EzyChannel.class); - when(session.getChannel()).thenReturn(channel); - - Object connection = new Object(); - when(channel.getConnection()).thenReturn(connection); - - // when - sut.mapSocketChannel(null, session); - - // then - verify(session, times(1)).getChannel(); - verify(channel, times(1)).getConnection(); - } - - @Test - public void removeHandlerGroupUdpClientAddressIsNull() { - // given - EzyHandlerGroupManager sut = newHandlerGroupManager(); - - EzySession session = mock(EzySession.class); - EzyChannel channel = mock(EzyChannel.class); - when(session.getChannel()).thenReturn(channel); - - Object connection = new Object(); - when(channel.getConnection()).thenReturn(connection); - - SocketAddress udpClientAddress = mock(SocketAddress.class); - when(session.getUdpClientAddress()).thenReturn(udpClientAddress); - - // when - sut.removeHandlerGroup(session); - - // then - verify(session, times(1)).getChannel(); - verify(session, times(1)).getUdpClientAddress(); - verify(channel, times(1)).getConnection(); - } - - public EzyHandlerGroupManager newHandlerGroupManager() { - EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() - .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) - .tokenGenerator(new EzySimpleSessionTokenGenerator()) - .build(); - ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); - EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); - when(codecFactory.newDecoder(any())).thenReturn(decoder); - ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); - EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); - EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); - EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); - - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleStreamingSetting streaming = settings.getStreaming(); - streaming.setEnable(true); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - server.setSessionManager(sessionManager); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); - EzyStatistics statistics = new EzySimpleStatistics(); - EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() - .statistics(statistics) - .statsThreadPool(statsThreadPool) - .streamQueue(streamQueue) - .disconnectionQueue(disconnectionQueue) - .codecFactory(codecFactory) - .serverContext(serverContext) - .socketSessionTicketsQueue(socketSessionTicketsQueue) - .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) - .socketSessionTicketsQueue(webSocketSessionTicketsQueue) - .sessionTicketsRequestQueues(sessionTicketsRequestQueues) - .build(); - - EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() - .handlerGroupBuilderFactory(handlerGroupBuilderFactory) - .build(); - return handlerGroupManager; - } - - public static class ExEzyByteToObjectDecoder implements EzyStringToObjectDecoder { - - @Override - public Object decode(String bytes) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - @Override - public Object decode(byte[] bytes) throws Exception { - return EzyEntityFactory.newArrayBuilder() - .append(EzyCommand.PING.getId()) - .build(); - } - - } - + @Test + public void test() { + EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); + when(codecFactory.newDecoder(any())).thenReturn(decoder); + ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue) + .disconnectionQueue(disconnectionQueue) + .codecFactory(codecFactory) + .serverContext(serverContext) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .socketSessionTicketsQueue(webSocketSessionTicketsQueue) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + + EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() + .handlerGroupBuilderFactory(handlerGroupBuilderFactory) + .build(); + handlerGroupManager.removeHandlerGroup(null); + EzySession session1 = mock(EzyAbstractSession.class); + handlerGroupManager.removeHandlerGroup(session1); + EzySession session2 = mock(EzyAbstractSession.class); + EzyChannel channel2 = mock(EzyChannel.class); + when(session2.getChannel()).thenReturn(channel2); + handlerGroupManager.removeHandlerGroup(session2); + EzyChannel channel3 = mock(EzyChannel.class); + Session connection3 = mock(Session.class); + when(channel3.getConnection()).thenReturn(connection3); + EzyHandlerGroup handlerGroup3 = handlerGroupManager.newHandlerGroup(channel3, EzyConnectionType.WEBSOCKET); + EzySession session3 = mock(EzyAbstractSession.class); + when(session3.getChannel()).thenReturn(channel3); + assert handlerGroupManager.getDataHandlerGroup(null) == null; + assert handlerGroupManager.getDataHandlerGroup(session1) == null; + assert handlerGroupManager.getDataHandlerGroup(session2) == null; + assert handlerGroupManager.getWriterGroup(session3) == handlerGroup3; + InetSocketAddress udpAddress = new InetSocketAddress("127.0.0.1", 12345); + handlerGroupManager.mapSocketChannel(udpAddress, session3); + assert handlerGroupManager.getSocketChannel(udpAddress) != null; + handlerGroupManager.unmapHandlerGroup(udpAddress); + handlerGroupManager.removeHandlerGroup(session3); + handlerGroupManager.destroy(); + } + + @Test + public void unmapHandlerGroupNullAddress() { + // given + EzyHandlerGroupManager sut = newHandlerGroupManager(); + + // when + // then + sut.unmapHandlerGroup(null); + } + + @Test + public void mapSocketChannelSessionNull() { + // given + EzyHandlerGroupManager sut = newHandlerGroupManager(); + + // when + // then + sut.mapSocketChannel(null, null); + } + + @Test + public void mapSocketChannelChannelNull() { + // given + EzyHandlerGroupManager sut = newHandlerGroupManager(); + + EzySession session = mock(EzySession.class); + + // when + sut.mapSocketChannel(null, session); + + // then + verify(session, times(1)).getChannel(); + } + + @Test + public void mapSocketChannelConnectionNull() { + // given + EzyHandlerGroupManager sut = newHandlerGroupManager(); + + EzySession session = mock(EzySession.class); + EzyChannel channel = mock(EzyChannel.class); + when(session.getChannel()).thenReturn(channel); + + // when + sut.mapSocketChannel(null, session); + + // then + verify(session, times(1)).getChannel(); + } + + @Test + public void mapSocketChannelNonContainsConnection() { + // given + EzyHandlerGroupManager sut = newHandlerGroupManager(); + + EzySession session = mock(EzySession.class); + EzyChannel channel = mock(EzyChannel.class); + when(session.getChannel()).thenReturn(channel); + + Object connection = new Object(); + when(channel.getConnection()).thenReturn(connection); + + // when + sut.mapSocketChannel(null, session); + + // then + verify(session, times(1)).getChannel(); + verify(channel, times(1)).getConnection(); + } + + @Test + public void removeHandlerGroupUdpClientAddressIsNull() { + // given + EzyHandlerGroupManager sut = newHandlerGroupManager(); + + EzySession session = mock(EzySession.class); + EzyChannel channel = mock(EzyChannel.class); + when(session.getChannel()).thenReturn(channel); + + Object connection = new Object(); + when(channel.getConnection()).thenReturn(connection); + + SocketAddress udpClientAddress = mock(SocketAddress.class); + when(session.getUdpClientAddress()).thenReturn(udpClientAddress); + + // when + sut.removeHandlerGroup(session); + + // then + verify(session, times(1)).getChannel(); + verify(session, times(1)).getUdpClientAddress(); + verify(channel, times(1)).getConnection(); + } + + public EzyHandlerGroupManager newHandlerGroupManager() { + EzyNioSessionManager sessionManager = (EzyNioSessionManager)EzyNioSessionManagerImpl.builder() + .maxRequestPerSecond(new EzySimpleSessionManagementSetting.EzySimpleMaxRequestPerSecond()) + .tokenGenerator(new EzySimpleSessionTokenGenerator()) + .build(); + ExEzyByteToObjectDecoder decoder = new ExEzyByteToObjectDecoder(); + EzyCodecFactory codecFactory = mock(EzyCodecFactory.class); + when(codecFactory.newDecoder(any())).thenReturn(decoder); + ExecutorService statsThreadPool = EzyExecutors.newSingleThreadExecutor("stats"); + EzySocketStreamQueue streamQueue = new EzyBlockingSocketStreamQueue(); + EzySocketDisconnectionQueue disconnectionQueue = new EzyBlockingSocketDisconnectionQueue(); + EzySessionTicketsRequestQueues sessionTicketsRequestQueues = new EzySessionTicketsRequestQueues(); + + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleStreamingSetting streaming = settings.getStreaming(); + streaming.setEnable(true); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + server.setSessionManager(sessionManager); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySessionTicketsQueue socketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzySessionTicketsQueue webSocketSessionTicketsQueue = new EzyBlockingSessionTicketsQueue(); + EzyStatistics statistics = new EzySimpleStatistics(); + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = EzyHandlerGroupBuilderFactoryImpl.builder() + .statistics(statistics) + .statsThreadPool(statsThreadPool) + .streamQueue(streamQueue) + .disconnectionQueue(disconnectionQueue) + .codecFactory(codecFactory) + .serverContext(serverContext) + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .webSocketSessionTicketsQueue(webSocketSessionTicketsQueue) + .socketSessionTicketsQueue(webSocketSessionTicketsQueue) + .sessionTicketsRequestQueues(sessionTicketsRequestQueues) + .build(); + + EzyHandlerGroupManager handlerGroupManager = EzyHandlerGroupManagerImpl.builder() + .handlerGroupBuilderFactory(handlerGroupBuilderFactory) + .build(); + return handlerGroupManager; + } + + public static class ExEzyByteToObjectDecoder implements EzyStringToObjectDecoder { + + @Override + public Object decode(String bytes) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + @Override + public Object decode(byte[] bytes) throws Exception { + return EzyEntityFactory.newArrayBuilder() + .append(EzyCommand.PING.getId()) + .build(); + } + + } + } diff --git a/ezyfox-server-nio/src/test/resources/AllTests.tng.xml b/ezyfox-server-nio/src/test/resources/AllTests.tng.xml index fd28f3a6c..c26b5a6e0 100644 --- a/ezyfox-server-nio/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-nio/src/test/resources/AllTests.tng.xml @@ -1,15 +1,15 @@ - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + diff --git a/ezyfox-server-niorunner/assembly.xml b/ezyfox-server-niorunner/assembly.xml index 1a84be639..69e0178eb 100644 --- a/ezyfox-server-niorunner/assembly.xml +++ b/ezyfox-server-niorunner/assembly.xml @@ -1,16 +1,16 @@ - bin - false - - dir - + bin + false + + dir + - - - true - lib - - + + + true + lib + + - \ No newline at end of file + diff --git a/ezyfox-server-niorunner/pom.xml b/ezyfox-server-niorunner/pom.xml index c853217c1..5825362f0 100755 --- a/ezyfox-server-niorunner/pom.xml +++ b/ezyfox-server-niorunner/pom.xml @@ -1,23 +1,23 @@ - 4.0.0 - - com.tvd12 - ezyfox-server - 1.2.3 - - ezyfox-server-niorunner + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + com.tvd12 + ezyfox-server + 1.2.3 + + ezyfox-server-niorunner - ezyfox-server-niorunner - https://youngmonkeys.org/project/ezyfox-sever/ + ezyfox-server-niorunner + https://youngmonkeys.org/project/ezyfox-sever/ - - - com.tvd12 - ezyfox-server-nio - ${project.version} - - + + + com.tvd12 + ezyfox-server-nio + ${project.version} + + diff --git a/ezyfox-server-niorunner/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioRunner.java b/ezyfox-server-niorunner/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioRunner.java index dbc2b8771..d0d8e17df 100644 --- a/ezyfox-server-niorunner/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioRunner.java +++ b/ezyfox-server-niorunner/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioRunner.java @@ -5,13 +5,13 @@ public class EzyNioRunner extends EzyRunner { - public static void main(String[] args) throws Exception { - new EzyNioRunner().run(args); - } - - @Override - protected Builder newStarterBuilder() { - return EzyNioStarter.builder(); - } - + public static void main(String[] args) throws Exception { + new EzyNioRunner().run(args); + } + + @Override + protected Builder newStarterBuilder() { + return EzyNioStarter.builder(); + } + } diff --git a/ezyfox-server-niorunner/src/test/resources/AllTests.tng.xml b/ezyfox-server-niorunner/src/test/resources/AllTests.tng.xml index 1de164721..fe095d02f 100644 --- a/ezyfox-server-niorunner/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-niorunner/src/test/resources/AllTests.tng.xml @@ -1,9 +1,9 @@ - - - - - - \ No newline at end of file + + + + + + diff --git a/ezyfox-server-support/assembly.xml b/ezyfox-server-support/assembly.xml index 1a84be639..69e0178eb 100644 --- a/ezyfox-server-support/assembly.xml +++ b/ezyfox-server-support/assembly.xml @@ -1,16 +1,16 @@ - bin - false - - dir - + bin + false + + dir + - - - true - lib - - + + + true + lib + + - \ No newline at end of file + diff --git a/ezyfox-server-support/pom.xml b/ezyfox-server-support/pom.xml index 5c2f6288b..8789b76ee 100644 --- a/ezyfox-server-support/pom.xml +++ b/ezyfox-server-support/pom.xml @@ -1,36 +1,36 @@ - 4.0.0 - - com.tvd12 - ezyfox-server - 1.2.3 - - ezyfox-server-support - ezyfox-server-support - https://youngmonkeys.org/project/ezyfox-sever/ - - - - com.tvd12 - ezyfox-core - ${ezy.core.version} - - - com.tvd12 - ezyfox-bean - ${project.version} - - - com.tvd12 - ezyfox-binding - ${project.version} - - - com.tvd12 - ezyfox-server-core - ${project.version} - - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + com.tvd12 + ezyfox-server + 1.2.3 + + ezyfox-server-support + ezyfox-server-support + https://youngmonkeys.org/project/ezyfox-sever/ + + + + com.tvd12 + ezyfox-core + ${ezy.core.version} + + + com.tvd12 + ezyfox-bean + ${project.version} + + + com.tvd12 + ezyfox-binding + ${project.version} + + + com.tvd12 + ezyfox-server-core + ${project.version} + + + diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAbstractHandlerImplementer.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAbstractHandlerImplementer.java index 01c8070f5..81870738d 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAbstractHandlerImplementer.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAbstractHandlerImplementer.java @@ -13,99 +13,99 @@ import com.tvd12.ezyfoxserver.support.reflect.EzyHandlerMethod; public class EzyAbstractHandlerImplementer - extends EzyLoggable { - - protected final H handlerMethod; - - protected final static String PARAMETER_PREFIX = "param"; - - public EzyAbstractHandlerImplementer(H handlerMethod) { - this.handlerMethod = handlerMethod; - } + extends EzyLoggable { + + protected final H handlerMethod; + + protected final static String PARAMETER_PREFIX = "param"; + + public EzyAbstractHandlerImplementer(H handlerMethod) { + this.handlerMethod = handlerMethod; + } - protected int prepareHandleMethodArguments(EzyBody body) { - int paramCount = 0; - Class requestDataType = handlerMethod.getRequestDataType(); - Parameter[] parameters = handlerMethod.getParameters(); - for(Parameter parameter : parameters) { - Class parameterType = parameter.getType(); - EzyInstruction instruction = new EzyInstruction("\t", "\n") - .clazz(parameterType) - .append(" ").append(PARAMETER_PREFIX).append(paramCount) - .equal(); - if(parameterType == requestDataType) { - instruction.cast(requestDataType, "arg2"); - } - else if(EzyContext.class.isAssignableFrom(parameterType)) { - instruction.append("arg0"); - } - else if(parameterType == EzyUserSessionEvent.class) { - instruction.append("arg1"); - } - else if(parameterType == EzyUser.class) { - instruction.append("arg1.getUser()"); - } - else if(parameterType == EzySession.class) { - instruction.append("arg1.getSession()"); - } - else if(parameterType == boolean.class) { - instruction.append("false"); - } - else if(parameterType.isPrimitive()) { - instruction.append("0"); - } - else { - instruction.append("null"); - } - body.append(instruction); - ++ paramCount; - } - return paramCount; - } - - protected void appendHandleExceptionMethodArguments( - EzyExceptionHandlerMethod method, - EzyInstruction instruction, - Class exceptionClass, - String commandArg, String dataArg, String exceptionArg) { - int paramCount = 0; - Parameter[] parameters = method.getParameters(); - Class requestDataType = method.getRequestDataType(); - for(Parameter parameter : parameters) { - Class parameterType = parameter.getType(); - if(parameterType == requestDataType) { - instruction.brackets(requestDataType).append(dataArg); - } - else if(EzyContext.class.isAssignableFrom(parameterType)) { - instruction.append("arg0"); - } - else if(parameterType == EzyUserSessionEvent.class) { - instruction.append("arg1"); - } - else if(parameterType == EzyUser.class) { - instruction.append("arg1.getUser()"); - } - else if(parameterType == EzySession.class) { - instruction.append("arg1.getSession()"); - } - else if(parameterType == String.class) { - instruction.append(commandArg); - } - else if(Throwable.class.isAssignableFrom(parameterType)) { - instruction.brackets(exceptionClass).append(exceptionArg); - } - else if(parameterType == boolean.class) { - instruction.append("false"); - } - else if(parameterType.isPrimitive()) { - instruction.append("0"); - } - else { - instruction.append("null"); - } - if((paramCount ++) < (parameters.length - 1)) - instruction.append(", "); - } - } - + protected int prepareHandleMethodArguments(EzyBody body) { + int paramCount = 0; + Class requestDataType = handlerMethod.getRequestDataType(); + Parameter[] parameters = handlerMethod.getParameters(); + for(Parameter parameter : parameters) { + Class parameterType = parameter.getType(); + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .clazz(parameterType) + .append(" ").append(PARAMETER_PREFIX).append(paramCount) + .equal(); + if(parameterType == requestDataType) { + instruction.cast(requestDataType, "arg2"); + } + else if(EzyContext.class.isAssignableFrom(parameterType)) { + instruction.append("arg0"); + } + else if(parameterType == EzyUserSessionEvent.class) { + instruction.append("arg1"); + } + else if(parameterType == EzyUser.class) { + instruction.append("arg1.getUser()"); + } + else if(parameterType == EzySession.class) { + instruction.append("arg1.getSession()"); + } + else if(parameterType == boolean.class) { + instruction.append("false"); + } + else if(parameterType.isPrimitive()) { + instruction.append("0"); + } + else { + instruction.append("null"); + } + body.append(instruction); + ++ paramCount; + } + return paramCount; + } + + protected void appendHandleExceptionMethodArguments( + EzyExceptionHandlerMethod method, + EzyInstruction instruction, + Class exceptionClass, + String commandArg, String dataArg, String exceptionArg) { + int paramCount = 0; + Parameter[] parameters = method.getParameters(); + Class requestDataType = method.getRequestDataType(); + for(Parameter parameter : parameters) { + Class parameterType = parameter.getType(); + if(parameterType == requestDataType) { + instruction.brackets(requestDataType).append(dataArg); + } + else if(EzyContext.class.isAssignableFrom(parameterType)) { + instruction.append("arg0"); + } + else if(parameterType == EzyUserSessionEvent.class) { + instruction.append("arg1"); + } + else if(parameterType == EzyUser.class) { + instruction.append("arg1.getUser()"); + } + else if(parameterType == EzySession.class) { + instruction.append("arg1.getSession()"); + } + else if(parameterType == String.class) { + instruction.append(commandArg); + } + else if(Throwable.class.isAssignableFrom(parameterType)) { + instruction.brackets(exceptionClass).append(exceptionArg); + } + else if(parameterType == boolean.class) { + instruction.append("false"); + } + else if(parameterType.isPrimitive()) { + instruction.append("0"); + } + else { + instruction.append("null"); + } + if((paramCount ++) < (parameters.length - 1)) + instruction.append(", "); + } + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractRequestHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractRequestHandler.java index 5144bde44..9a32b91a9 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractRequestHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractRequestHandler.java @@ -9,37 +9,37 @@ public abstract class EzyAsmAbstractRequestHandler implements EzyAsmRequestHandler { - @Getter - @Setter - protected String command; - - @Setter - protected EzyResponseFactory responseFactory; - - @Override - public void handle( - EzyContext context, EzyUserSessionEvent event, Object data) { - try { - handleRequest(context, event, data); - } - catch (Exception e) { - handleException(context, event, data, e); - } - } - - public abstract void handleRequest( - EzyContext context, EzyUserSessionEvent event, Object data); - - public abstract void handleException( - EzyContext context, - EzyUserSessionEvent event, Object data, Exception exception); - - protected void responseToSession(EzyUserSessionEvent event, Object data) { - responseFactory.newObjectResponse() - .command(command) - .data(data) - .session(event.getSession()) - .execute(); - } - + @Getter + @Setter + protected String command; + + @Setter + protected EzyResponseFactory responseFactory; + + @Override + public void handle( + EzyContext context, EzyUserSessionEvent event, Object data) { + try { + handleRequest(context, event, data); + } + catch (Exception e) { + handleException(context, event, data, e); + } + } + + public abstract void handleRequest( + EzyContext context, EzyUserSessionEvent event, Object data); + + public abstract void handleException( + EzyContext context, + EzyUserSessionEvent event, Object data, Exception exception); + + protected void responseToSession(EzyUserSessionEvent event, Object data) { + responseFactory.newObjectResponse() + .command(command) + .data(data) + .session(event.getSession()) + .execute(); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractUncaughtExceptionHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractUncaughtExceptionHandler.java index 7b683e9f1..d9809a765 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractUncaughtExceptionHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmAbstractUncaughtExceptionHandler.java @@ -3,5 +3,5 @@ import com.tvd12.ezyfoxserver.context.EzyContext; public abstract class EzyAsmAbstractUncaughtExceptionHandler - implements EzyAsmUncaughtExceptionHandler { + implements EzyAsmUncaughtExceptionHandler { } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmRequestHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmRequestHandler.java index 3b5f04402..0568bb9d4 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmRequestHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmRequestHandler.java @@ -5,13 +5,13 @@ @SuppressWarnings("rawtypes") public interface EzyAsmRequestHandler extends EzyUserRequestHandler { - - void setController(Object controller); - - void setResponseFactory(EzyResponseFactory responseFactory); - - String getCommand(); - - void setCommand(String command); - + + void setController(Object controller); + + void setResponseFactory(EzyResponseFactory responseFactory); + + String getCommand(); + + void setCommand(String command); + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmUncaughtExceptionHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmUncaughtExceptionHandler.java index f6bac9409..abac622ef 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmUncaughtExceptionHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyAsmUncaughtExceptionHandler.java @@ -4,8 +4,8 @@ import com.tvd12.ezyfoxserver.support.handler.EzyUncaughtExceptionHandler; public interface EzyAsmUncaughtExceptionHandler - extends EzyUncaughtExceptionHandler { + extends EzyUncaughtExceptionHandler { - void setExceptionHandler(Object exceptionHandler); + void setExceptionHandler(Object exceptionHandler); } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlerImplementer.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlerImplementer.java index dc0e2beb1..e78966e5e 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlerImplementer.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlerImplementer.java @@ -24,138 +24,138 @@ @SuppressWarnings("rawtypes") public class EzyExceptionHandlerImplementer - extends EzyAbstractHandlerImplementer { - - @Setter - private static boolean debug; - protected final EzyExceptionHandlerProxy exceptionHandler; - - protected final static String PARAMETER_PREFIX = "param"; - protected final static AtomicInteger COUNT = new AtomicInteger(0); - - public EzyExceptionHandlerImplementer( - EzyExceptionHandlerProxy exceptionHandler, EzyExceptionHandlerMethod handlerMethod) { - super(handlerMethod); - this.exceptionHandler = exceptionHandler; - } - - public EzyUncaughtExceptionHandler implement() { - try { - return doimplement(); - } - catch(Exception e) { - throw new IllegalStateException(e); - } - } - - protected EzyUncaughtExceptionHandler doimplement() throws Exception { - ClassPool pool = ClassPool.getDefault(); - String implClassName = getImplClassName(); - CtClass implClass = pool.makeClass(implClassName); - EzyClass superClass = new EzyClass(getSuperClass()); - String exceptionHandlerFieldContent = makeExceptionHandlerFieldContent(); - String setExceptionHandlerMethodContent = makeSetExceptionHandlerMethodContent(); - String handleExceptionMethodContent = makeHandleExceptionMethodContent(); - printComponentContent(implClassName); - printComponentContent(exceptionHandlerFieldContent); - printComponentContent(setExceptionHandlerMethodContent); - printComponentContent(handleExceptionMethodContent); - implClass.setSuperclass(pool.get(superClass.getName())); - implClass.addField(CtField.make(exceptionHandlerFieldContent, implClass)); - implClass.addMethod(CtNewMethod.make(setExceptionHandlerMethodContent, implClass)); - implClass.addMethod(CtNewMethod.make(handleExceptionMethodContent, implClass)); - Class answerClass = implClass.toClass(); - implClass.detach(); - EzyAsmUncaughtExceptionHandler handler = (EzyAsmUncaughtExceptionHandler) answerClass.newInstance(); - setRepoComponent(handler); - return handler; - } - - protected void setRepoComponent(EzyAsmUncaughtExceptionHandler handler) { - handler.setExceptionHandler(exceptionHandler.getInstance()); - } - - protected String makeExceptionHandlerFieldContent() { - return new EzyInstruction() - .append("private ") - .append(exceptionHandler.getClazz().getName()) - .append(" exceptionHandler") - .toString(); - } - - protected String makeSetExceptionHandlerMethodContent() { - return new EzyFunction(getSetExceptionHandlerMethod()) - .body() - .append(new EzyInstruction("\t", "\n") - .append("this.exceptionHandler") - .equal() - .brackets(exceptionHandler.getClazz().getClazz()) - .append("arg0")) - .function() - .toString(); - } - - protected String makeHandleExceptionMethodContent() { - EzyMethod method = getHandleExceptionMethod(); - EzyFunction function = new EzyFunction(method) - .throwsException(); - EzyBody body = function.body(); - Class[] exceptionClasses = handlerMethod.getExceptionClasses(); - EzyClassTree exceptionTree = new EzyClassTree(exceptionClasses); - for(Class exceptionClass : exceptionTree.toList()) { - EzyInstruction instructionIf = new EzyInstruction("\t", "\n", false) - .append("if(arg4 instanceof ") - .append(exceptionClass.getName()) - .append(") {"); - body.append(instructionIf); - EzyInstruction instructionHandle = new EzyInstruction("\t\t", "\n"); - instructionHandle - .append("this.exceptionHandler.").append(handlerMethod.getName()) - .bracketopen(); - appendHandleExceptionMethodArguments(instructionHandle, exceptionClass); - instructionHandle - .bracketclose(); - body.append(instructionHandle); - body.append(new EzyInstruction("\t", "\n", false).append("}")); - } - body.append(new EzyInstruction("\t", "\n", false).append("else {")); - body.append(new EzyInstruction("\t\t", "\n").append("throw arg4")); - body.append(new EzyInstruction("\t", "\n", false).append("}")); - return function.toString(); - } - - protected void appendHandleExceptionMethodArguments( - EzyInstruction instruction, Class exceptionClass) { - super.appendHandleExceptionMethodArguments( - handlerMethod, instruction, exceptionClass, "arg2", "arg3", "arg4"); - } - - protected EzyMethod getSetExceptionHandlerMethod() { - Method method = EzyMethods.getMethod( - EzyAsmAbstractUncaughtExceptionHandler.class, "setExceptionHandler", Object.class); - return new EzyMethod(method); - } - - protected EzyMethod getHandleExceptionMethod() { - Method method = EzyMethods.getMethod( - EzyAsmAbstractUncaughtExceptionHandler.class, - "handleException", - EzyContext.class, EzyUserSessionEvent.class, String.class, Object.class, Exception.class); - return new EzyMethod(method); - } - - protected Class getSuperClass() { - return EzyAsmAbstractUncaughtExceptionHandler.class; - } - - protected String getImplClassName() { - return exceptionHandler.getClassSimpleName() - + "$" + handlerMethod.getName() + "$ExceptionHandler$AutoImpl$" + COUNT.incrementAndGet(); - } - - protected void printComponentContent(String componentContent) { - if(debug) - logger.debug("component content: \n{}", componentContent); - } - + extends EzyAbstractHandlerImplementer { + + @Setter + private static boolean debug; + protected final EzyExceptionHandlerProxy exceptionHandler; + + protected final static String PARAMETER_PREFIX = "param"; + protected final static AtomicInteger COUNT = new AtomicInteger(0); + + public EzyExceptionHandlerImplementer( + EzyExceptionHandlerProxy exceptionHandler, EzyExceptionHandlerMethod handlerMethod) { + super(handlerMethod); + this.exceptionHandler = exceptionHandler; + } + + public EzyUncaughtExceptionHandler implement() { + try { + return doimplement(); + } + catch(Exception e) { + throw new IllegalStateException(e); + } + } + + protected EzyUncaughtExceptionHandler doimplement() throws Exception { + ClassPool pool = ClassPool.getDefault(); + String implClassName = getImplClassName(); + CtClass implClass = pool.makeClass(implClassName); + EzyClass superClass = new EzyClass(getSuperClass()); + String exceptionHandlerFieldContent = makeExceptionHandlerFieldContent(); + String setExceptionHandlerMethodContent = makeSetExceptionHandlerMethodContent(); + String handleExceptionMethodContent = makeHandleExceptionMethodContent(); + printComponentContent(implClassName); + printComponentContent(exceptionHandlerFieldContent); + printComponentContent(setExceptionHandlerMethodContent); + printComponentContent(handleExceptionMethodContent); + implClass.setSuperclass(pool.get(superClass.getName())); + implClass.addField(CtField.make(exceptionHandlerFieldContent, implClass)); + implClass.addMethod(CtNewMethod.make(setExceptionHandlerMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(handleExceptionMethodContent, implClass)); + Class answerClass = implClass.toClass(); + implClass.detach(); + EzyAsmUncaughtExceptionHandler handler = (EzyAsmUncaughtExceptionHandler) answerClass.newInstance(); + setRepoComponent(handler); + return handler; + } + + protected void setRepoComponent(EzyAsmUncaughtExceptionHandler handler) { + handler.setExceptionHandler(exceptionHandler.getInstance()); + } + + protected String makeExceptionHandlerFieldContent() { + return new EzyInstruction() + .append("private ") + .append(exceptionHandler.getClazz().getName()) + .append(" exceptionHandler") + .toString(); + } + + protected String makeSetExceptionHandlerMethodContent() { + return new EzyFunction(getSetExceptionHandlerMethod()) + .body() + .append(new EzyInstruction("\t", "\n") + .append("this.exceptionHandler") + .equal() + .brackets(exceptionHandler.getClazz().getClazz()) + .append("arg0")) + .function() + .toString(); + } + + protected String makeHandleExceptionMethodContent() { + EzyMethod method = getHandleExceptionMethod(); + EzyFunction function = new EzyFunction(method) + .throwsException(); + EzyBody body = function.body(); + Class[] exceptionClasses = handlerMethod.getExceptionClasses(); + EzyClassTree exceptionTree = new EzyClassTree(exceptionClasses); + for(Class exceptionClass : exceptionTree.toList()) { + EzyInstruction instructionIf = new EzyInstruction("\t", "\n", false) + .append("if(arg4 instanceof ") + .append(exceptionClass.getName()) + .append(") {"); + body.append(instructionIf); + EzyInstruction instructionHandle = new EzyInstruction("\t\t", "\n"); + instructionHandle + .append("this.exceptionHandler.").append(handlerMethod.getName()) + .bracketopen(); + appendHandleExceptionMethodArguments(instructionHandle, exceptionClass); + instructionHandle + .bracketclose(); + body.append(instructionHandle); + body.append(new EzyInstruction("\t", "\n", false).append("}")); + } + body.append(new EzyInstruction("\t", "\n", false).append("else {")); + body.append(new EzyInstruction("\t\t", "\n").append("throw arg4")); + body.append(new EzyInstruction("\t", "\n", false).append("}")); + return function.toString(); + } + + protected void appendHandleExceptionMethodArguments( + EzyInstruction instruction, Class exceptionClass) { + super.appendHandleExceptionMethodArguments( + handlerMethod, instruction, exceptionClass, "arg2", "arg3", "arg4"); + } + + protected EzyMethod getSetExceptionHandlerMethod() { + Method method = EzyMethods.getMethod( + EzyAsmAbstractUncaughtExceptionHandler.class, "setExceptionHandler", Object.class); + return new EzyMethod(method); + } + + protected EzyMethod getHandleExceptionMethod() { + Method method = EzyMethods.getMethod( + EzyAsmAbstractUncaughtExceptionHandler.class, + "handleException", + EzyContext.class, EzyUserSessionEvent.class, String.class, Object.class, Exception.class); + return new EzyMethod(method); + } + + protected Class getSuperClass() { + return EzyAsmAbstractUncaughtExceptionHandler.class; + } + + protected String getImplClassName() { + return exceptionHandler.getClassSimpleName() + + "$" + handlerMethod.getName() + "$ExceptionHandler$AutoImpl$" + COUNT.incrementAndGet(); + } + + protected void printComponentContent(String componentContent) { + if(debug) + logger.debug("component content: \n{}", componentContent); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlersImplementer.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlersImplementer.java index 4c2a455a4..89a64f8dc 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlersImplementer.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyExceptionHandlersImplementer.java @@ -11,30 +11,30 @@ @SuppressWarnings("rawtypes") public class EzyExceptionHandlersImplementer extends EzyLoggable { - - public Map, EzyUncaughtExceptionHandler> - implement(Collection exceptionHandlers) { - Map, EzyUncaughtExceptionHandler> handlers = new HashMap<>(); - for(Object controller : exceptionHandlers) - handlers.putAll(implement(controller)); - return handlers; - } - - public Map, EzyUncaughtExceptionHandler> implement(Object exceptionHandler) { - Map, EzyUncaughtExceptionHandler> handlers = new HashMap<>(); - EzyExceptionHandlerProxy proxy = new EzyExceptionHandlerProxy(exceptionHandler); - for(EzyExceptionHandlerMethod method : proxy.getExceptionHandlerMethods()) { - EzyExceptionHandlerImplementer implementer = newImplementer(proxy, method); - EzyUncaughtExceptionHandler handler = implementer.implement(); - for(Class exceptionClass : method.getExceptionClasses()) - handlers.put(exceptionClass, handler); - } - return handlers; - } - - protected EzyExceptionHandlerImplementer newImplementer( - EzyExceptionHandlerProxy exceptionHandler, EzyExceptionHandlerMethod method) { - return new EzyExceptionHandlerImplementer(exceptionHandler, method); - } - + + public Map, EzyUncaughtExceptionHandler> + implement(Collection exceptionHandlers) { + Map, EzyUncaughtExceptionHandler> handlers = new HashMap<>(); + for(Object controller : exceptionHandlers) + handlers.putAll(implement(controller)); + return handlers; + } + + public Map, EzyUncaughtExceptionHandler> implement(Object exceptionHandler) { + Map, EzyUncaughtExceptionHandler> handlers = new HashMap<>(); + EzyExceptionHandlerProxy proxy = new EzyExceptionHandlerProxy(exceptionHandler); + for(EzyExceptionHandlerMethod method : proxy.getExceptionHandlerMethods()) { + EzyExceptionHandlerImplementer implementer = newImplementer(proxy, method); + EzyUncaughtExceptionHandler handler = implementer.implement(); + for(Class exceptionClass : method.getExceptionClasses()) + handlers.put(exceptionClass, handler); + } + return handlers; + } + + protected EzyExceptionHandlerImplementer newImplementer( + EzyExceptionHandlerProxy exceptionHandler, EzyExceptionHandlerMethod method) { + return new EzyExceptionHandlerImplementer(exceptionHandler, method); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlerImplementer.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlerImplementer.java index 4e8f50c9e..cba93fd8b 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlerImplementer.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlerImplementer.java @@ -26,216 +26,216 @@ import lombok.Setter; public class EzyRequestHandlerImplementer - extends EzyAbstractHandlerImplementer { + extends EzyAbstractHandlerImplementer { - @Setter - private static boolean debug; - - @Setter + @Setter + private static boolean debug; + + @Setter protected EzyResponseFactory responseFactory; - - protected final EzyRequestControllerProxy controller; - - protected final static AtomicInteger COUNT = new AtomicInteger(0); - - public EzyRequestHandlerImplementer( - EzyRequestControllerProxy controller, EzyRequestHandlerMethod handlerMethod) { - super(handlerMethod); - this.controller = controller; - } - - public EzyAsmRequestHandler implement() { - try { - return doimplement(); - } - catch(Exception e) { - throw new IllegalStateException(e); - } - } - - @SuppressWarnings("rawtypes") - protected EzyAsmRequestHandler doimplement() throws Exception { - ClassPool pool = ClassPool.getDefault(); - String implClassName = getImplClassName(); - CtClass implClass = pool.makeClass(implClassName); - EzyClass superClass = new EzyClass(getSuperClass()); - String controllerFieldContent = makeControllerFieldContent(); - String setControllerMethodContent = makeSetControllerMethodContent(); - String handleRequestMethodContent = makeHandleRequestMethodContent(); - String handleExceptionMethodContent = makeHandleExceptionMethodContent(); - String getRequestDataTypeMethodContent = makeGetRequestDataTypeMethodContent(); - printComponentContent(controllerFieldContent); - printComponentContent(setControllerMethodContent); - printComponentContent(handleRequestMethodContent); - printComponentContent(handleExceptionMethodContent); - printComponentContent(getRequestDataTypeMethodContent); - implClass.setSuperclass(pool.get(superClass.getName())); - implClass.addField(CtField.make(controllerFieldContent, implClass)); - implClass.addMethod(CtNewMethod.make(setControllerMethodContent, implClass)); - implClass.addMethod(CtNewMethod.make(handleRequestMethodContent, implClass)); - implClass.addMethod(CtNewMethod.make(handleExceptionMethodContent, implClass)); - implClass.addMethod(CtNewMethod.make(getRequestDataTypeMethodContent, implClass)); - Class answerClass = implClass.toClass(); - implClass.detach(); - EzyAsmRequestHandler handler = (EzyAsmRequestHandler) answerClass.newInstance(); - handler.setCommand(handlerMethod.getCommand()); - handler.setResponseFactory(responseFactory); - setRepoComponent(handler); - return handler; - } - - protected void setRepoComponent(EzyAsmRequestHandler handler) { - handler.setController(controller.getInstance()); - } - - protected String makeControllerFieldContent() { - return new EzyInstruction() - .append("private ") - .append(controller.getClazz().getName()) - .append(" controller") - .toString(); - } - - protected String makeSetControllerMethodContent() { - return new EzyFunction(getSetControllerMethod()) - .body() - .append(new EzyInstruction("\t", "\n") - .append("this.controller") - .equal() - .brackets(controller.getClazz().getClazz()) - .append("arg0")) - .function() - .toString(); - } - - protected String makeHandleRequestMethodContent() { - EzyMethod method = getHandleRequestMethod(); - EzyFunction function = new EzyFunction(method) - .throwsException(); - EzyBody body = function.body(); - int paramCount = prepareHandleMethodArguments(body); - EzyInstruction instruction = new EzyInstruction("\t", "\n"); - StringBuilder answerExpression = new StringBuilder(); - if (handlerMethod.getReturnType() != void.class) { - answerExpression.append(Object.class.getName()) - .append(" data = "); - } - answerExpression.append("this.controller.").append(handlerMethod.getName()) - .append("("); - for(int i = 0 ; i < paramCount ; ++i) { - answerExpression.append(PARAMETER_PREFIX).append(i); - if(i < paramCount - 1) - answerExpression.append(", "); - } - answerExpression.append(")"); - instruction.append(answerExpression); - body.append(instruction); - if (handlerMethod.getReturnType() != void.class) { - EzyInstruction responseInstruction = new EzyInstruction("\t", "\n") - .invoke("this", "responseToSession", "arg1", "data"); - body.append(responseInstruction); - } - return function.toString(); - } - - protected String makeHandleExceptionMethodContent() { - EzyMethod method = getHandleExceptionMethod(); - EzyFunction function = new EzyFunction(method) - .throwsException(); - EzyBody body = function.body(); - Map, EzyExceptionHandlerMethod> exceptionHandlerMethodMap - = controller.getExceptionHandlerMethodMap(); - Set> exceptionClasses = exceptionHandlerMethodMap.keySet(); - EzyClassTree exceptionTree = new EzyClassTree(exceptionClasses); - for(Class exceptionClass : exceptionTree.toList()) { - EzyExceptionHandlerMethod m = exceptionHandlerMethodMap.get(exceptionClass); - EzyInstruction instructionIf = new EzyInstruction("\t", "\n", false) - .append("if(arg3 instanceof ") - .append(exceptionClass.getName()) - .append(") {"); - body.append(instructionIf); - EzyInstruction instructionHandle = new EzyInstruction("\t\t", "\n"); - instructionHandle - .append("this.controller.").append(m.getName()) - .bracketopen(); - appendHandleExceptionMethodArguments(m, instructionHandle, exceptionClass); - instructionHandle - .bracketclose(); - body.append(instructionHandle); - body.append(new EzyInstruction("\t", "\n", false).append("}")); - } - if(exceptionClasses.size() > 0) { - body.append(new EzyInstruction("\t", "\n", false).append("else {")); - body.append(new EzyInstruction("\t\t", "\n").append("throw arg3")); - body.append(new EzyInstruction("\t", "\n", false).append("}")); - } - else { - body.append(new EzyInstruction("\t", "\n").append("throw arg3")); - } - return function.toString(); - } - - protected void appendHandleExceptionMethodArguments( - EzyExceptionHandlerMethod method, - EzyInstruction instruction, Class exceptionClass) { - super.appendHandleExceptionMethodArguments( - method, instruction, exceptionClass, "this.command", "arg2", "arg3"); - } - - protected String makeGetRequestDataTypeMethodContent() { - EzyInstruction answerInstruction = new EzyInstruction("\t", "\n") - .answer(); - if(handlerMethod.getRequestDataType() == null) - answerInstruction.append("null"); - else - answerInstruction.clazz(handlerMethod.getRequestDataType(), true); - return new EzyFunction(getGetResponseContentTypeMethod()) - .body() - .append(answerInstruction) - .function() - .toString(); - } - - protected EzyMethod getSetControllerMethod() { - Method method = EzyMethods.getMethod( - EzyAsmAbstractRequestHandler.class, "setController", Object.class); - return new EzyMethod(method); - } - - protected EzyMethod getHandleRequestMethod() { - Method method = EzyMethods.getMethod( - EzyAsmAbstractRequestHandler.class, - "handleRequest", - EzyContext.class, EzyUserSessionEvent.class, Object.class); - return new EzyMethod(method); - } - - protected EzyMethod getHandleExceptionMethod() { - Method method = EzyMethods.getMethod( - EzyAsmAbstractRequestHandler.class, - "handleException", - EzyContext.class, EzyUserSessionEvent.class, Object.class, Exception.class); - return new EzyMethod(method); - } - - protected EzyMethod getGetResponseContentTypeMethod() { - Method method = EzyMethods.getMethod( - EzyAsmAbstractRequestHandler.class, "getDataType"); - return new EzyMethod(method); - } - - protected Class getSuperClass() { - return EzyAsmAbstractRequestHandler.class; - } - - protected String getImplClassName() { - return controller.getControllerName() - + "$" + handlerMethod.getName() + "$Handler$AutoImpl$" + COUNT.incrementAndGet(); - } - - protected void printComponentContent(String componentContent) { - if(debug) - logger.debug("component content: \n{}", componentContent); - } - + + protected final EzyRequestControllerProxy controller; + + protected final static AtomicInteger COUNT = new AtomicInteger(0); + + public EzyRequestHandlerImplementer( + EzyRequestControllerProxy controller, EzyRequestHandlerMethod handlerMethod) { + super(handlerMethod); + this.controller = controller; + } + + public EzyAsmRequestHandler implement() { + try { + return doimplement(); + } + catch(Exception e) { + throw new IllegalStateException(e); + } + } + + @SuppressWarnings("rawtypes") + protected EzyAsmRequestHandler doimplement() throws Exception { + ClassPool pool = ClassPool.getDefault(); + String implClassName = getImplClassName(); + CtClass implClass = pool.makeClass(implClassName); + EzyClass superClass = new EzyClass(getSuperClass()); + String controllerFieldContent = makeControllerFieldContent(); + String setControllerMethodContent = makeSetControllerMethodContent(); + String handleRequestMethodContent = makeHandleRequestMethodContent(); + String handleExceptionMethodContent = makeHandleExceptionMethodContent(); + String getRequestDataTypeMethodContent = makeGetRequestDataTypeMethodContent(); + printComponentContent(controllerFieldContent); + printComponentContent(setControllerMethodContent); + printComponentContent(handleRequestMethodContent); + printComponentContent(handleExceptionMethodContent); + printComponentContent(getRequestDataTypeMethodContent); + implClass.setSuperclass(pool.get(superClass.getName())); + implClass.addField(CtField.make(controllerFieldContent, implClass)); + implClass.addMethod(CtNewMethod.make(setControllerMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(handleRequestMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(handleExceptionMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(getRequestDataTypeMethodContent, implClass)); + Class answerClass = implClass.toClass(); + implClass.detach(); + EzyAsmRequestHandler handler = (EzyAsmRequestHandler) answerClass.newInstance(); + handler.setCommand(handlerMethod.getCommand()); + handler.setResponseFactory(responseFactory); + setRepoComponent(handler); + return handler; + } + + protected void setRepoComponent(EzyAsmRequestHandler handler) { + handler.setController(controller.getInstance()); + } + + protected String makeControllerFieldContent() { + return new EzyInstruction() + .append("private ") + .append(controller.getClazz().getName()) + .append(" controller") + .toString(); + } + + protected String makeSetControllerMethodContent() { + return new EzyFunction(getSetControllerMethod()) + .body() + .append(new EzyInstruction("\t", "\n") + .append("this.controller") + .equal() + .brackets(controller.getClazz().getClazz()) + .append("arg0")) + .function() + .toString(); + } + + protected String makeHandleRequestMethodContent() { + EzyMethod method = getHandleRequestMethod(); + EzyFunction function = new EzyFunction(method) + .throwsException(); + EzyBody body = function.body(); + int paramCount = prepareHandleMethodArguments(body); + EzyInstruction instruction = new EzyInstruction("\t", "\n"); + StringBuilder answerExpression = new StringBuilder(); + if (handlerMethod.getReturnType() != void.class) { + answerExpression.append(Object.class.getName()) + .append(" data = "); + } + answerExpression.append("this.controller.").append(handlerMethod.getName()) + .append("("); + for(int i = 0 ; i < paramCount ; ++i) { + answerExpression.append(PARAMETER_PREFIX).append(i); + if(i < paramCount - 1) + answerExpression.append(", "); + } + answerExpression.append(")"); + instruction.append(answerExpression); + body.append(instruction); + if (handlerMethod.getReturnType() != void.class) { + EzyInstruction responseInstruction = new EzyInstruction("\t", "\n") + .invoke("this", "responseToSession", "arg1", "data"); + body.append(responseInstruction); + } + return function.toString(); + } + + protected String makeHandleExceptionMethodContent() { + EzyMethod method = getHandleExceptionMethod(); + EzyFunction function = new EzyFunction(method) + .throwsException(); + EzyBody body = function.body(); + Map, EzyExceptionHandlerMethod> exceptionHandlerMethodMap + = controller.getExceptionHandlerMethodMap(); + Set> exceptionClasses = exceptionHandlerMethodMap.keySet(); + EzyClassTree exceptionTree = new EzyClassTree(exceptionClasses); + for(Class exceptionClass : exceptionTree.toList()) { + EzyExceptionHandlerMethod m = exceptionHandlerMethodMap.get(exceptionClass); + EzyInstruction instructionIf = new EzyInstruction("\t", "\n", false) + .append("if(arg3 instanceof ") + .append(exceptionClass.getName()) + .append(") {"); + body.append(instructionIf); + EzyInstruction instructionHandle = new EzyInstruction("\t\t", "\n"); + instructionHandle + .append("this.controller.").append(m.getName()) + .bracketopen(); + appendHandleExceptionMethodArguments(m, instructionHandle, exceptionClass); + instructionHandle + .bracketclose(); + body.append(instructionHandle); + body.append(new EzyInstruction("\t", "\n", false).append("}")); + } + if(exceptionClasses.size() > 0) { + body.append(new EzyInstruction("\t", "\n", false).append("else {")); + body.append(new EzyInstruction("\t\t", "\n").append("throw arg3")); + body.append(new EzyInstruction("\t", "\n", false).append("}")); + } + else { + body.append(new EzyInstruction("\t", "\n").append("throw arg3")); + } + return function.toString(); + } + + protected void appendHandleExceptionMethodArguments( + EzyExceptionHandlerMethod method, + EzyInstruction instruction, Class exceptionClass) { + super.appendHandleExceptionMethodArguments( + method, instruction, exceptionClass, "this.command", "arg2", "arg3"); + } + + protected String makeGetRequestDataTypeMethodContent() { + EzyInstruction answerInstruction = new EzyInstruction("\t", "\n") + .answer(); + if(handlerMethod.getRequestDataType() == null) + answerInstruction.append("null"); + else + answerInstruction.clazz(handlerMethod.getRequestDataType(), true); + return new EzyFunction(getGetResponseContentTypeMethod()) + .body() + .append(answerInstruction) + .function() + .toString(); + } + + protected EzyMethod getSetControllerMethod() { + Method method = EzyMethods.getMethod( + EzyAsmAbstractRequestHandler.class, "setController", Object.class); + return new EzyMethod(method); + } + + protected EzyMethod getHandleRequestMethod() { + Method method = EzyMethods.getMethod( + EzyAsmAbstractRequestHandler.class, + "handleRequest", + EzyContext.class, EzyUserSessionEvent.class, Object.class); + return new EzyMethod(method); + } + + protected EzyMethod getHandleExceptionMethod() { + Method method = EzyMethods.getMethod( + EzyAsmAbstractRequestHandler.class, + "handleException", + EzyContext.class, EzyUserSessionEvent.class, Object.class, Exception.class); + return new EzyMethod(method); + } + + protected EzyMethod getGetResponseContentTypeMethod() { + Method method = EzyMethods.getMethod( + EzyAsmAbstractRequestHandler.class, "getDataType"); + return new EzyMethod(method); + } + + protected Class getSuperClass() { + return EzyAsmAbstractRequestHandler.class; + } + + protected String getImplClassName() { + return controller.getControllerName() + + "$" + handlerMethod.getName() + "$Handler$AutoImpl$" + COUNT.incrementAndGet(); + } + + protected void printComponentContent(String componentContent) { + if(debug) + logger.debug("component content: \n{}", componentContent); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlersImplementer.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlersImplementer.java index b8d1b9861..3f260aee1 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlersImplementer.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/asm/EzyRequestHandlersImplementer.java @@ -24,52 +24,52 @@ public class EzyRequestHandlersImplementer extends EzyLoggable { private EzyResponseFactory responseFactory; private EzyFeatureCommandManager featureCommandManager; private EzyRequestCommandManager requestCommandManager; - - public Map implement(Collection controllers) { - Map handlers = new HashMap<>(); - for(Object controller : controllers) { - Map map = implement(controller); - for(String command : map.keySet()) { - EzyUserRequestHandler handler = map.get(command); - EzyUserRequestHandler old = handlers.put(command, handler); - if(old != null && !allowOverrideCommand) { - throw new EzyDuplicateRequestHandlerException(command, old, handler); - } - } - } - return handlers; - } - - private Map implement(Object controller) { - Map handlers = new HashMap<>(); - EzyRequestControllerProxy proxy = new EzyRequestControllerProxy(controller); - String feature = proxy.getFeature(); - for(EzyRequestHandlerMethod method : proxy.getRequestHandlerMethods()) { - EzyRequestHandlerImplementer implementer = newImplementer(proxy, method); - EzyAsmRequestHandler handler = implementer.implement(); - String command = handler.getCommand(); - handlers.put(command, handler); - requestCommandManager.addCommand(command); - if (proxy.isManagement() || method.isManagement()) { - requestCommandManager.addManagementCommand(command); - } - if (proxy.isPayment() || method.isPayment()) { - requestCommandManager.addPaymentCommand(command); - } - String methodFeature = feature != null ? feature : method.getFeature(); - if (EzyStrings.isNotBlank(methodFeature)) { - featureCommandManager.addFeatureCommand(methodFeature, command); - } - } - return handlers; - } - - protected EzyRequestHandlerImplementer newImplementer( - EzyRequestControllerProxy controller, EzyRequestHandlerMethod method) { - EzyRequestHandlerImplementer implementer = - new EzyRequestHandlerImplementer(controller, method); - implementer.setResponseFactory(responseFactory); - return implementer; - } - + + public Map implement(Collection controllers) { + Map handlers = new HashMap<>(); + for(Object controller : controllers) { + Map map = implement(controller); + for(String command : map.keySet()) { + EzyUserRequestHandler handler = map.get(command); + EzyUserRequestHandler old = handlers.put(command, handler); + if(old != null && !allowOverrideCommand) { + throw new EzyDuplicateRequestHandlerException(command, old, handler); + } + } + } + return handlers; + } + + private Map implement(Object controller) { + Map handlers = new HashMap<>(); + EzyRequestControllerProxy proxy = new EzyRequestControllerProxy(controller); + String feature = proxy.getFeature(); + for(EzyRequestHandlerMethod method : proxy.getRequestHandlerMethods()) { + EzyRequestHandlerImplementer implementer = newImplementer(proxy, method); + EzyAsmRequestHandler handler = implementer.implement(); + String command = handler.getCommand(); + handlers.put(command, handler); + requestCommandManager.addCommand(command); + if (proxy.isManagement() || method.isManagement()) { + requestCommandManager.addManagementCommand(command); + } + if (proxy.isPayment() || method.isPayment()) { + requestCommandManager.addPaymentCommand(command); + } + String methodFeature = feature != null ? feature : method.getFeature(); + if (EzyStrings.isNotBlank(methodFeature)) { + featureCommandManager.addFeatureCommand(methodFeature, command); + } + } + return handlers; + } + + protected EzyRequestHandlerImplementer newImplementer( + EzyRequestControllerProxy controller, EzyRequestHandlerMethod method) { + EzyRequestHandlerImplementer implementer = + new EzyRequestHandlerImplementer(controller, method); + implementer.setResponseFactory(responseFactory); + return implementer; + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractArrayResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractArrayResponse.java index 6245755c1..f22c573a7 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractArrayResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractArrayResponse.java @@ -9,52 +9,52 @@ import com.tvd12.ezyfoxserver.context.EzyContext; public abstract class EzyAbstractArrayResponse - extends EzyAbstractResponse - implements EzyArrayResponse { - - protected List additionalParams = new ArrayList<>(); - - public EzyAbstractArrayResponse(EzyContext context, EzyMarshaller marshaller) { - super(context, marshaller); - } - - @Override - public EzyArrayResponse param(Object value) { - additionalParams.add(value); - return this; - } - - @Override - public EzyArrayResponse params(Object... values) { - for(Object value : values) - additionalParams.add(value); - return this; - } - - @Override - public EzyArrayResponse params(Iterable values) { - for(Object value : values) - additionalParams.add(value); - return this; - } - - @Override - protected EzyData getResponseData() { - EzyArray array = data != null - ? marshaller.marshal(data) - : newArrayBuilder().build(); - for(Object object : additionalParams) { - Object value = marshaller.marshal(object); - array.add(value); - } - return array; - } - - @Override - public void destroy() { - super.destroy(); - this.additionalParams.clear(); - this.additionalParams = null; - } - + extends EzyAbstractResponse + implements EzyArrayResponse { + + protected List additionalParams = new ArrayList<>(); + + public EzyAbstractArrayResponse(EzyContext context, EzyMarshaller marshaller) { + super(context, marshaller); + } + + @Override + public EzyArrayResponse param(Object value) { + additionalParams.add(value); + return this; + } + + @Override + public EzyArrayResponse params(Object... values) { + for(Object value : values) + additionalParams.add(value); + return this; + } + + @Override + public EzyArrayResponse params(Iterable values) { + for(Object value : values) + additionalParams.add(value); + return this; + } + + @Override + protected EzyData getResponseData() { + EzyArray array = data != null + ? marshaller.marshal(data) + : newArrayBuilder().build(); + for(Object object : additionalParams) { + Object value = marshaller.marshal(object); + array.add(value); + } + return array; + } + + @Override + public void destroy() { + super.destroy(); + this.additionalParams.clear(); + this.additionalParams = null; + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractObjectResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractObjectResponse.java index 657144191..a6f365184 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractObjectResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractObjectResponse.java @@ -11,41 +11,41 @@ import com.tvd12.ezyfoxserver.context.EzyContext; public abstract class EzyAbstractObjectResponse - extends EzyAbstractResponse - implements EzyObjectResponse { + extends EzyAbstractResponse + implements EzyObjectResponse { - protected final Set excludeParamKeys = new HashSet<>(); - protected final Map additionalParams = new HashMap<>(); - - public EzyAbstractObjectResponse(EzyContext context, EzyMarshaller marshaller) { - super(context, marshaller); - } - - @Override - public EzyObjectResponse param(Object key, Object value) { - additionalParams.put(key, value); - return this; - } - - @Override - public EzyObjectResponse exclude(Object key) { - excludeParamKeys.add(key); - return this; - } + protected final Set excludeParamKeys = new HashSet<>(); + protected final Map additionalParams = new HashMap<>(); + + public EzyAbstractObjectResponse(EzyContext context, EzyMarshaller marshaller) { + super(context, marshaller); + } + + @Override + public EzyObjectResponse param(Object key, Object value) { + additionalParams.put(key, value); + return this; + } + + @Override + public EzyObjectResponse exclude(Object key) { + excludeParamKeys.add(key); + return this; + } - @Override - protected EzyData getResponseData() { - EzyObject object = data != null - ? marshaller.marshal(data) - : newObjectBuilder().build(); - for(Object key : additionalParams.keySet()) { - Object value = additionalParams.get(key); - Object skey = marshaller.marshal(key); - Object svalue = marshaller.marshal(value); - object.put(skey, svalue); - } - object.removeAll(excludeParamKeys); - return object; - } - + @Override + protected EzyData getResponseData() { + EzyObject object = data != null + ? marshaller.marshal(data) + : newObjectBuilder().build(); + for(Object key : additionalParams.keySet()) { + Object value = additionalParams.get(key); + Object skey = marshaller.marshal(key); + Object svalue = marshaller.marshal(value); + object.put(skey, svalue); + } + object.removeAll(excludeParamKeys); + return object; + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractResponse.java index f202976e1..235430d73 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAbstractResponse.java @@ -11,12 +11,12 @@ @SuppressWarnings("unchecked") public abstract class EzyAbstractResponse> - extends EzyEntityBuilders - implements EzyResponse, EzyDestroyable { + extends EzyEntityBuilders + implements EzyResponse, EzyDestroyable { - protected Object data; + protected Object data; - protected com.tvd12.ezyfoxserver.command.EzyResponse response; + protected com.tvd12.ezyfoxserver.command.EzyResponse response; protected EzyContext context; protected EzyMarshaller marshaller; @@ -28,33 +28,33 @@ public EzyAbstractResponse(EzyContext context, EzyMarshaller marshaller) { } public T encrypted() { - this.response.encrypted(); - return (T)this; + this.response.encrypted(); + return (T)this; } public T encrypted(boolean value) { - this.response.encrypted(value); - return (T)this; + this.response.encrypted(value); + return (T)this; } - public T command(String command) { - this.response.command(command); + public T command(String command) { + this.response.command(command); return (T) this; } - @Override + @Override public T data(Object data) { this.data = data; return (T) this; } - + public T user(EzyUser user, boolean exclude) { this.response.user(user, exclude); return (T) this; } public T users(EzyUser[] users, boolean exclude) { - this.response.users(users, exclude); + this.response.users(users, exclude); return (T) this; } @@ -83,49 +83,49 @@ public T sessions(Iterable sessions, boolean exclude) { @Override public T username(String username, boolean exclude) { - this.response.username(username, exclude); - return (T)this; + this.response.username(username, exclude); + return (T)this; } @Override public T usernames(String[] usernames, boolean exclude) { - this.response.usernames(usernames, exclude); - return (T)this; + this.response.usernames(usernames, exclude); + return (T)this; } @Override public T usernames(Iterable usernames, boolean exclude) { - this.response.usernames(usernames, exclude); - return (T)this; + this.response.usernames(usernames, exclude); + return (T)this; } @Override public T transportType(EzyTransportType transportType) { - this.response.transportType(transportType); - return (T)this; + this.response.transportType(transportType); + return (T)this; } public void execute() { - response(getResponseData()); - destroy(); + response(getResponseData()); + destroy(); } protected abstract EzyData getResponseData(); protected void response(EzyData data) { - response - .params(data) - .execute(); + response + .params(data) + .execute(); } protected abstract com.tvd12.ezyfoxserver.command.EzyResponse newResponse(); @Override public void destroy() { - this.data = null; + this.data = null; this.response = null; this.context = null; this.marshaller = null; } - + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppArrayResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppArrayResponse.java index 512767ad1..0d1abe0aa 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppArrayResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppArrayResponse.java @@ -7,13 +7,13 @@ public class EzyAppArrayResponse extends EzyAbstractArrayResponse { - public EzyAppArrayResponse(EzyAppContext context, EzyMarshaller marshaller) { - super(context, marshaller); - } + public EzyAppArrayResponse(EzyAppContext context, EzyMarshaller marshaller) { + super(context, marshaller); + } + + @Override + protected EzyResponse newResponse() { + return context.cmd(EzyAppResponse.class); + } - @Override - protected EzyResponse newResponse() { - return context.cmd(EzyAppResponse.class); - } - } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppObjectResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppObjectResponse.java index cf16b24a2..139f555c1 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppObjectResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyAppObjectResponse.java @@ -10,15 +10,15 @@ public class EzyAppObjectResponse extends EzyAbstractObjectResponse { - protected final Map additionalParams = new HashMap<>(); - - public EzyAppObjectResponse(EzyAppContext context, EzyMarshaller marshaller) { - super(context, marshaller); - } - - @Override - protected EzyResponse newResponse() { - return context.cmd(EzyAppResponse.class); - } - + protected final Map additionalParams = new HashMap<>(); + + public EzyAppObjectResponse(EzyAppContext context, EzyMarshaller marshaller) { + super(context, marshaller); + } + + @Override + protected EzyResponse newResponse() { + return context.cmd(EzyAppResponse.class); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyArrayResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyArrayResponse.java index 69582ac1c..fa2bccfae 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyArrayResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyArrayResponse.java @@ -4,9 +4,9 @@ public interface EzyArrayResponse extends EzyResponse { - EzyArrayResponse param(Object value); - - EzyArrayResponse params(Object... values); - - EzyArrayResponse params(Iterable values); + EzyArrayResponse param(Object value); + + EzyArrayResponse params(Object... values); + + EzyArrayResponse params(Iterable values); } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyObjectResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyObjectResponse.java index 5d0518e36..45e1dae99 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyObjectResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyObjectResponse.java @@ -3,9 +3,9 @@ import com.tvd12.ezyfoxserver.support.command.EzyObjectResponse; public interface EzyObjectResponse extends EzyResponse { - - EzyObjectResponse param(Object key, Object value); - - EzyObjectResponse exclude(Object key); - + + EzyObjectResponse param(Object key, Object value); + + EzyObjectResponse exclude(Object key); + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginArrayResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginArrayResponse.java index 1d06e15a0..563368d8c 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginArrayResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginArrayResponse.java @@ -6,14 +6,14 @@ import com.tvd12.ezyfoxserver.context.EzyPluginContext; public class EzyPluginArrayResponse extends EzyAbstractArrayResponse { - - public EzyPluginArrayResponse(EzyPluginContext context, EzyMarshaller marshaller) { - super(context, marshaller); - } - - @Override - protected EzyResponse newResponse() { - return context.cmd(EzyPluginResponse.class); - } - + + public EzyPluginArrayResponse(EzyPluginContext context, EzyMarshaller marshaller) { + super(context, marshaller); + } + + @Override + protected EzyResponse newResponse() { + return context.cmd(EzyPluginResponse.class); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginObjectResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginObjectResponse.java index 1e450fa31..d2c02c2e3 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginObjectResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyPluginObjectResponse.java @@ -10,21 +10,21 @@ public class EzyPluginObjectResponse extends EzyAbstractObjectResponse { - protected Map additionalParams = new HashMap<>(); - - public EzyPluginObjectResponse(EzyPluginContext context, EzyMarshaller marshaller) { - super(context, marshaller); - } - - @Override - protected EzyResponse newResponse() { - return context.cmd(EzyPluginResponse.class); - } - - @Override - public void destroy() { - super.destroy(); - this.additionalParams.clear(); - this.additionalParams = null; - } + protected Map additionalParams = new HashMap<>(); + + public EzyPluginObjectResponse(EzyPluginContext context, EzyMarshaller marshaller) { + super(context, marshaller); + } + + @Override + protected EzyResponse newResponse() { + return context.cmd(EzyPluginResponse.class); + } + + @Override + public void destroy() { + super.destroy(); + this.additionalParams.clear(); + this.additionalParams = null; + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyResponse.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyResponse.java index 8bc8d22fe..fc9d63705 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyResponse.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/command/EzyResponse.java @@ -7,14 +7,14 @@ import com.tvd12.ezyfoxserver.entity.EzyUser; public interface EzyResponse> extends EzyVoidCommand { - - T encrypted(); - - T encrypted(boolean value); - T data(Object data); - - T command(String command); + T encrypted(); + + T encrypted(boolean value); + + T data(Object data); + + T command(String command); T user(EzyUser user, boolean exclude); @@ -41,43 +41,43 @@ default T data(EzyBuilder builder) { } default T user(EzyUser user) { - return user(user, false); + return user(user, false); } default T users(EzyUser... users) { - return users(users, false); + return users(users, false); } default T users(Iterable users) { - return users(users, false); + return users(users, false); } default T session(EzySession session) { - return session(session, false); + return session(session, false); } default T sessions(EzySession... sessions) { - return sessions(sessions, false); + return sessions(sessions, false); } default T sessions(Iterable sessions) { - return sessions(sessions, false); + return sessions(sessions, false); } default T username(String username) { - return username(username, false); + return username(username, false); } default T usernames(String... usernames) { - return usernames(usernames, false); + return usernames(usernames, false); } default T usernames(Iterable usernames) { - return usernames(usernames, false); + return usernames(usernames, false); } default T udpTransport() { - return transportType(EzyTransportType.UDP); + return transportType(EzyTransportType.UDP); } - + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyAbstractUserRequestController.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyAbstractUserRequestController.java index 3667c6e8b..37506715f 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyAbstractUserRequestController.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyAbstractUserRequestController.java @@ -10,11 +10,11 @@ public abstract class EzyAbstractUserRequestController extends EzyLoggable implements EzyCommandsAware { - - protected EzyData newErrorData(EzyBadRequestException e) { - EzyData errorData = newArray(e.getCode(), e.getReason()); - EzyData data = newArray(EzyResponseCommands.ERROR, errorData); - return data; - } - + + protected EzyData newErrorData(EzyBadRequestException e) { + EzyData errorData = newArray(e.getCode(), e.getReason()); + EzyData data = newArray(EzyResponseCommands.ERROR, errorData); + return data; + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppPrototypeController.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppPrototypeController.java index ac2620e6a..286610b0b 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppPrototypeController.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppPrototypeController.java @@ -8,37 +8,37 @@ import com.tvd12.ezyfoxserver.event.EzyUserRequestAppEvent; public class EzyUserRequestAppPrototypeController - extends EzyUserRequestPrototypeController - implements EzyAppRequestController { - - protected EzyUserRequestAppPrototypeController(Builder builder) { - super(builder); - } - - @Override - protected void preHandle( - EzyAppContext context, - EzyUserRequestAppEvent event, String cmd, EzyHandler handler) { - if(handler instanceof EzyAppContextAware) - ((EzyAppContextAware)handler).setAppContext(context); - } - - @Override - protected void responseError( - EzyAppContext context, - EzyUserRequestAppEvent event, EzyData errorData) { - context.send(errorData, event.getSession(), false); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyUserRequestPrototypeController.Builder { - - @Override - public EzyUserRequestAppPrototypeController build() { - return new EzyUserRequestAppPrototypeController(this); - } - } + extends EzyUserRequestPrototypeController + implements EzyAppRequestController { + + protected EzyUserRequestAppPrototypeController(Builder builder) { + super(builder); + } + + @Override + protected void preHandle( + EzyAppContext context, + EzyUserRequestAppEvent event, String cmd, EzyHandler handler) { + if(handler instanceof EzyAppContextAware) + ((EzyAppContextAware)handler).setAppContext(context); + } + + @Override + protected void responseError( + EzyAppContext context, + EzyUserRequestAppEvent event, EzyData errorData) { + context.send(errorData, event.getSession(), false); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyUserRequestPrototypeController.Builder { + + @Override + public EzyUserRequestAppPrototypeController build() { + return new EzyUserRequestAppPrototypeController(this); + } + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppSingletonController.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppSingletonController.java index 497683de3..2789c150c 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppSingletonController.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestAppSingletonController.java @@ -6,38 +6,38 @@ import com.tvd12.ezyfoxserver.event.EzyUserRequestAppEvent; public class EzyUserRequestAppSingletonController - extends EzyUserRequestSingletonController - implements EzyAppRequestController { - - protected EzyUserRequestAppSingletonController(Builder builder) { - super(builder); - } - - @Override - protected void responseError( - EzyAppContext context, - EzyUserRequestAppEvent event, EzyData errorData) { - context.send(errorData, event.getSession(), false); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyUserRequestSingletonController.Builder { - - @Override - public EzyUserRequestAppSingletonController build() { - return new EzyUserRequestAppSingletonController(this); - } - - @SuppressWarnings("rawtypes") - @Override - protected EzyUserRequestPrototypeController getPrototypeController() { - return EzyUserRequestAppPrototypeController.builder() - .beanContext(beanContext) - .build(); - } - - } + extends EzyUserRequestSingletonController + implements EzyAppRequestController { + + protected EzyUserRequestAppSingletonController(Builder builder) { + super(builder); + } + + @Override + protected void responseError( + EzyAppContext context, + EzyUserRequestAppEvent event, EzyData errorData) { + context.send(errorData, event.getSession(), false); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyUserRequestSingletonController.Builder { + + @Override + public EzyUserRequestAppSingletonController build() { + return new EzyUserRequestAppSingletonController(this); + } + + @SuppressWarnings("rawtypes") + @Override + protected EzyUserRequestPrototypeController getPrototypeController() { + return EzyUserRequestAppPrototypeController.builder() + .beanContext(beanContext) + .build(); + } + + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginPrototypeController.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginPrototypeController.java index ee448aca3..8bf74aa98 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginPrototypeController.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginPrototypeController.java @@ -8,36 +8,36 @@ import com.tvd12.ezyfoxserver.plugin.EzyPluginRequestController; public class EzyUserRequestPluginPrototypeController - extends EzyUserRequestPrototypeController - implements EzyPluginRequestController { + extends EzyUserRequestPrototypeController + implements EzyPluginRequestController { - protected EzyUserRequestPluginPrototypeController(Builder builder) { - super(builder); - } - - @Override - protected void preHandle( - EzyPluginContext context, - EzyUserRequestPluginEvent event, String cmd, EzyHandler handler) { - if(handler instanceof EzyPluginContextAware) - ((EzyPluginContextAware)handler).setPluginContext(context); - } - - @Override - protected void responseError( - EzyPluginContext context, - EzyUserRequestPluginEvent event, EzyData errorData) { - context.send(errorData, event.getSession(), false); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyUserRequestPrototypeController.Builder { - @Override - public EzyUserRequestPluginPrototypeController build() { - return new EzyUserRequestPluginPrototypeController(this); - } - } + protected EzyUserRequestPluginPrototypeController(Builder builder) { + super(builder); + } + + @Override + protected void preHandle( + EzyPluginContext context, + EzyUserRequestPluginEvent event, String cmd, EzyHandler handler) { + if(handler instanceof EzyPluginContextAware) + ((EzyPluginContextAware)handler).setPluginContext(context); + } + + @Override + protected void responseError( + EzyPluginContext context, + EzyUserRequestPluginEvent event, EzyData errorData) { + context.send(errorData, event.getSession(), false); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyUserRequestPrototypeController.Builder { + @Override + public EzyUserRequestPluginPrototypeController build() { + return new EzyUserRequestPluginPrototypeController(this); + } + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginSingletonController.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginSingletonController.java index 8bd283fd2..bfb082fbd 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginSingletonController.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPluginSingletonController.java @@ -6,38 +6,38 @@ import com.tvd12.ezyfoxserver.plugin.EzyPluginRequestController; public class EzyUserRequestPluginSingletonController - extends EzyUserRequestSingletonController - implements EzyPluginRequestController { - - protected EzyUserRequestPluginSingletonController(Builder builder) { - super(builder); - } - - @Override - protected void responseError( - EzyPluginContext context, - EzyUserRequestPluginEvent event, EzyData errorData) { - context.send(errorData, event.getSession(), false); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyUserRequestSingletonController.Builder { - - @Override - public EzyUserRequestPluginSingletonController build() { - return new EzyUserRequestPluginSingletonController(this); - } - - @SuppressWarnings("rawtypes") - @Override - protected EzyUserRequestPrototypeController getPrototypeController() { - return EzyUserRequestPluginPrototypeController.builder() - .beanContext(beanContext) - .build(); - } - - } + extends EzyUserRequestSingletonController + implements EzyPluginRequestController { + + protected EzyUserRequestPluginSingletonController(Builder builder) { + super(builder); + } + + @Override + protected void responseError( + EzyPluginContext context, + EzyUserRequestPluginEvent event, EzyData errorData) { + context.send(errorData, event.getSession(), false); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyUserRequestSingletonController.Builder { + + @Override + public EzyUserRequestPluginSingletonController build() { + return new EzyUserRequestPluginSingletonController(this); + } + + @SuppressWarnings("rawtypes") + @Override + protected EzyUserRequestPrototypeController getPrototypeController() { + return EzyUserRequestPluginPrototypeController.builder() + .beanContext(beanContext) + .build(); + } + + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPrototypeController.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPrototypeController.java index da60fa7ca..4e22b427a 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPrototypeController.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestPrototypeController.java @@ -32,92 +32,92 @@ import com.tvd12.ezyfoxserver.support.manager.EzyRequestCommandManager; public abstract class EzyUserRequestPrototypeController< - C extends EzyZoneChildContext, - E extends EzyUserRequestEvent> - extends EzyAbstractUserRequestController { - - protected final EzyBeanContext beanContext; - protected final EzyUnmarshaller unmarshaller; - protected final Map handlers; - - protected EzyUserRequestPrototypeController(Builder builder) { - this.beanContext = builder.beanContext; - this.unmarshaller = builder.unmarshaller; - this.handlers = new HashMap<>(builder.extractHandlers()); - } - - public void handle(C context, E event) { - EzyArray data = event.getData(); - String cmd = data.get(0, String.class); - EzyPrototypeSupplier supplier = handlers.get(cmd); - if(supplier == null) { - logger.warn("has no handler with command: {} from session: {}", cmd, event.getSession().getName()); - return; - } - EzyHandler handler = (EzyHandler)supplier.supply(beanContext); - if(handler instanceof EzyUserAware) - ((EzyUserAware)handler).setUser(event.getUser()); - if(handler instanceof EzySessionAware) - ((EzySessionAware)handler).setSession(event.getSession()); - if(handler instanceof EzyDataBinding) { - EzyData params = data.get(1, EzyData.class, null); - if(params != null) - unmarshaller.unwrap(params, handler); - } - try { - preHandle(context, event, cmd, handler); - handler.handle(); - postHandle(context, event, cmd, handler); - } - catch(EzyBadRequestException e) { - if(e.isSendToClient()) { - EzyData errorData = newErrorData(e); - responseError(context, event, errorData); - } - logger.debug("request cmd: {} by session: {} with data: {} error", cmd, event.getSession().getName(), data, e); - postHandle(context, event, cmd, handler, e); - } - catch(Exception e) { - postHandle(context, event, cmd, handler, e); - throw e; - } - } - - protected abstract void preHandle(C context, E event, String cmd, EzyHandler handler); - protected void postHandle(C context, E event, String cmd, EzyHandler handler) {} - protected void postHandle(C context, E event, String cmd, EzyHandler handler, Exception e) {} - - protected abstract void responseError(C context, E event, EzyData errorData); - - @Override + C extends EzyZoneChildContext, + E extends EzyUserRequestEvent> + extends EzyAbstractUserRequestController { + + protected final EzyBeanContext beanContext; + protected final EzyUnmarshaller unmarshaller; + protected final Map handlers; + + protected EzyUserRequestPrototypeController(Builder builder) { + this.beanContext = builder.beanContext; + this.unmarshaller = builder.unmarshaller; + this.handlers = new HashMap<>(builder.extractHandlers()); + } + + public void handle(C context, E event) { + EzyArray data = event.getData(); + String cmd = data.get(0, String.class); + EzyPrototypeSupplier supplier = handlers.get(cmd); + if(supplier == null) { + logger.warn("has no handler with command: {} from session: {}", cmd, event.getSession().getName()); + return; + } + EzyHandler handler = (EzyHandler)supplier.supply(beanContext); + if(handler instanceof EzyUserAware) + ((EzyUserAware)handler).setUser(event.getUser()); + if(handler instanceof EzySessionAware) + ((EzySessionAware)handler).setSession(event.getSession()); + if(handler instanceof EzyDataBinding) { + EzyData params = data.get(1, EzyData.class, null); + if(params != null) + unmarshaller.unwrap(params, handler); + } + try { + preHandle(context, event, cmd, handler); + handler.handle(); + postHandle(context, event, cmd, handler); + } + catch(EzyBadRequestException e) { + if(e.isSendToClient()) { + EzyData errorData = newErrorData(e); + responseError(context, event, errorData); + } + logger.debug("request cmd: {} by session: {} with data: {} error", cmd, event.getSession().getName(), data, e); + postHandle(context, event, cmd, handler, e); + } + catch(Exception e) { + postHandle(context, event, cmd, handler, e); + throw e; + } + } + + protected abstract void preHandle(C context, E event, String cmd, EzyHandler handler); + protected void postHandle(C context, E event, String cmd, EzyHandler handler) {} + protected void postHandle(C context, E event, String cmd, EzyHandler handler, Exception e) {} + + protected abstract void responseError(C context, E event, EzyData errorData); + + @Override public Set getCommands() { return new HashSet<>(handlers.keySet()); } - - @SuppressWarnings("rawtypes") - public abstract static class Builder - extends EzyLoggable - implements EzyBuilder { - - protected EzyBeanContext beanContext; - protected EzyPrototypeFactory prototypeFactory; - protected EzyUnmarshaller unmarshaller; - - @SuppressWarnings("unchecked") - public B beanContext(EzyBeanContext beanContext) { - this.beanContext = beanContext; - this.prototypeFactory = beanContext.getPrototypeFactory(); - this.unmarshaller = beanContext.getSingleton("unmarshaller", EzyUnmarshaller.class); - return (B)this; - } - - private Map extractHandlers() { - Map handlers = getHandlers(); - extractRequestCommands(handlers); - return handlers; - } - - private Map getHandlers() { + + @SuppressWarnings("rawtypes") + public abstract static class Builder + extends EzyLoggable + implements EzyBuilder { + + protected EzyBeanContext beanContext; + protected EzyPrototypeFactory prototypeFactory; + protected EzyUnmarshaller unmarshaller; + + @SuppressWarnings("unchecked") + public B beanContext(EzyBeanContext beanContext) { + this.beanContext = beanContext; + this.prototypeFactory = beanContext.getPrototypeFactory(); + this.unmarshaller = beanContext.getSingleton("unmarshaller", EzyUnmarshaller.class); + return (B)this; + } + + private Map extractHandlers() { + Map handlers = getHandlers(); + extractRequestCommands(handlers); + return handlers; + } + + private Map getHandlers() { List suppliers = prototypeFactory.getSuppliers(EzyRequestListener.class); Map handlers = new HashMap<>(); @@ -131,27 +131,27 @@ private Map getHandlers() { extractRequestCommands(handlers); return handlers; } - - private void extractRequestCommands(Map handlers) { - EzyFeatureCommandManager featureCommandManager = - beanContext.getSingleton(EzyFeatureCommandManager.class); - EzyRequestCommandManager requestCommandManager = - beanContext.getSingleton(EzyRequestCommandManager.class); - for(String command : handlers.keySet()) { - EzyPrototypeSupplier handler = handlers.get(command); - Class handleType = handler.getObjectType(); - requestCommandManager.addCommand(command); - if (handleType.isAnnotationPresent(EzyManagement.class)) { - requestCommandManager.addManagementCommand(command); - } - if (handleType.isAnnotationPresent(EzyPayment.class)) { - requestCommandManager.addPaymentCommand(command); - } - EzyFeature featureAnno = handleType.getAnnotation(EzyFeature.class); - if (featureAnno != null && isNotBlank(featureAnno.value())) { - featureCommandManager.addFeatureCommand(featureAnno.value(), command); - } - } - } - } + + private void extractRequestCommands(Map handlers) { + EzyFeatureCommandManager featureCommandManager = + beanContext.getSingleton(EzyFeatureCommandManager.class); + EzyRequestCommandManager requestCommandManager = + beanContext.getSingleton(EzyRequestCommandManager.class); + for(String command : handlers.keySet()) { + EzyPrototypeSupplier handler = handlers.get(command); + Class handleType = handler.getObjectType(); + requestCommandManager.addCommand(command); + if (handleType.isAnnotationPresent(EzyManagement.class)) { + requestCommandManager.addManagementCommand(command); + } + if (handleType.isAnnotationPresent(EzyPayment.class)) { + requestCommandManager.addPaymentCommand(command); + } + EzyFeature featureAnno = handleType.getAnnotation(EzyFeature.class); + if (featureAnno != null && isNotBlank(featureAnno.value())) { + featureCommandManager.addFeatureCommand(featureAnno.value(), command); + } + } + } + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestSingletonController.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestSingletonController.java index 47b49e2f9..9ff508019 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestSingletonController.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/controller/EzyUserRequestSingletonController.java @@ -43,137 +43,137 @@ @SuppressWarnings({ "unchecked", "rawtypes" }) public abstract class EzyUserRequestSingletonController< - C extends EzyZoneChildContext, - E extends EzyUserRequestEvent> - extends EzyAbstractUserRequestController{ + C extends EzyZoneChildContext, + E extends EzyUserRequestEvent> + extends EzyAbstractUserRequestController{ - protected final EzyUnmarshaller unmarshaller; - protected final EzyResponseFactory responseFactory; - protected final List> handledExceptionClasses; - protected final Map requestHandlers; - protected final List requestInterceptors; - protected final Map, EzyUncaughtExceptionHandler> exceptionHandlers; - protected final EzyUserRequestPrototypeController prototypeController; - - protected EzyUserRequestSingletonController(Builder builder) { - this.unmarshaller = builder.unmarshaller; - this.responseFactory = builder.responseFactory; - this.prototypeController = builder.getPrototypeController(); - this.requestHandlers = new HashMap<>(builder.extractRequestHandlers()); - this.exceptionHandlers = new HashMap<>(builder.getExceptionHandlers()); - this.requestInterceptors = new ArrayList<>(builder.getRequestInterceptors()); - this.handledExceptionClasses = new EzyClassTree(exceptionHandlers.keySet()).toList(); - } - - public void handle(C context, E event) { - EzyArray data = event.getData(); - String cmd = data.get(0, String.class); - EzyUserRequestHandler handler = requestHandlers.get(cmd); - if(handler == null) { - prototypeController.handle(context, event); - return; - } - Object handlerData = data.get(1, EzyData.class, null); - Class requestDataType = handler.getDataType(); - if(requestDataType != null) { - handlerData = unmarshaller.unmarshal(handlerData, requestDataType); - } - try { - preHandle(context, event, cmd, handlerData); - handler.handle(context, event, handlerData); - postHandle(context, event, cmd, handlerData); - } - catch (Exception e) { - postHandle(context, event, cmd, handlerData, e); - if(e instanceof EzyBadRequestException) { - EzyBadRequestException ex = (EzyBadRequestException)e; - if(ex.isSendToClient()) { - EzyData errorData = newErrorData(ex); - responseError(context, event, errorData); - } - logger.debug("request cmd: {} by session: {} with data: {} error", cmd, event.getSession().getName(), data, e); - } - else { - EzyUncaughtExceptionHandler exceptionHandler = getExceptionHandler(e.getClass()); - if(exceptionHandler == null) - throw new EzyUserRequestException(cmd, handlerData, e); - try { - exceptionHandler.handleException(context, event, cmd, handlerData, e); - } - catch (Exception ex) { - throw new EzyUserRequestException(cmd, handlerData, ex); - } - } - } - } - - protected void preHandle(C context, E event, String cmd, Object data) { - for(EzyUserRequestInterceptor interceptor : requestInterceptors) - interceptor.preHandle(context, event, cmd, data); - } - - protected void postHandle(C context, E event, String cmd, Object data) { - for(EzyUserRequestInterceptor interceptor : requestInterceptors) - interceptor.postHandle(context, event, cmd, data); - } - - protected void postHandle(C context, E event, String cmd, Object data, Exception e) { - for(EzyUserRequestInterceptor interceptor : requestInterceptors) - interceptor.postHandle(context, event, cmd, data, e); - } - - protected EzyUncaughtExceptionHandler getExceptionHandler(Class exceptionClass) { - for(Class exc : handledExceptionClasses) { - if(exc.isAssignableFrom(exceptionClass)) - return exceptionHandlers.get(exc); - } - return null; - } - - protected abstract void responseError(C context, E event, EzyData errorData); - - @Override - public Set getCommands() { - Set commands = new HashSet<>(); - commands.addAll(requestHandlers.keySet()); - commands.addAll(prototypeController.getCommands()); - return commands; - } - - public abstract static class Builder - extends EzyLoggable - implements EzyBuilder { + protected final EzyUnmarshaller unmarshaller; + protected final EzyResponseFactory responseFactory; + protected final List> handledExceptionClasses; + protected final Map requestHandlers; + protected final List requestInterceptors; + protected final Map, EzyUncaughtExceptionHandler> exceptionHandlers; + protected final EzyUserRequestPrototypeController prototypeController; - protected EzyBeanContext beanContext; - protected EzyUnmarshaller unmarshaller; - protected EzyResponseFactory responseFactory; - protected EzySingletonFactory singletonFactory; - protected EzyFeatureCommandManager featureCommandManager; - protected EzyRequestCommandManager requestCommandManager; - - public B beanContext(EzyBeanContext beanContext) { - this.beanContext = beanContext; - this.singletonFactory = beanContext.getSingletonFactory(); - this.responseFactory = beanContext.getSingleton(EzyResponseFactory.class); - this.unmarshaller = beanContext.getSingleton("unmarshaller", EzyUnmarshaller.class); - this.featureCommandManager = beanContext.getSingleton(EzyFeatureCommandManager.class); + protected EzyUserRequestSingletonController(Builder builder) { + this.unmarshaller = builder.unmarshaller; + this.responseFactory = builder.responseFactory; + this.prototypeController = builder.getPrototypeController(); + this.requestHandlers = new HashMap<>(builder.extractRequestHandlers()); + this.exceptionHandlers = new HashMap<>(builder.getExceptionHandlers()); + this.requestInterceptors = new ArrayList<>(builder.getRequestInterceptors()); + this.handledExceptionClasses = new EzyClassTree(exceptionHandlers.keySet()).toList(); + } + + public void handle(C context, E event) { + EzyArray data = event.getData(); + String cmd = data.get(0, String.class); + EzyUserRequestHandler handler = requestHandlers.get(cmd); + if(handler == null) { + prototypeController.handle(context, event); + return; + } + Object handlerData = data.get(1, EzyData.class, null); + Class requestDataType = handler.getDataType(); + if(requestDataType != null) { + handlerData = unmarshaller.unmarshal(handlerData, requestDataType); + } + try { + preHandle(context, event, cmd, handlerData); + handler.handle(context, event, handlerData); + postHandle(context, event, cmd, handlerData); + } + catch (Exception e) { + postHandle(context, event, cmd, handlerData, e); + if(e instanceof EzyBadRequestException) { + EzyBadRequestException ex = (EzyBadRequestException)e; + if(ex.isSendToClient()) { + EzyData errorData = newErrorData(ex); + responseError(context, event, errorData); + } + logger.debug("request cmd: {} by session: {} with data: {} error", cmd, event.getSession().getName(), data, e); + } + else { + EzyUncaughtExceptionHandler exceptionHandler = getExceptionHandler(e.getClass()); + if(exceptionHandler == null) + throw new EzyUserRequestException(cmd, handlerData, e); + try { + exceptionHandler.handleException(context, event, cmd, handlerData, e); + } + catch (Exception ex) { + throw new EzyUserRequestException(cmd, handlerData, ex); + } + } + } + } + + protected void preHandle(C context, E event, String cmd, Object data) { + for(EzyUserRequestInterceptor interceptor : requestInterceptors) + interceptor.preHandle(context, event, cmd, data); + } + + protected void postHandle(C context, E event, String cmd, Object data) { + for(EzyUserRequestInterceptor interceptor : requestInterceptors) + interceptor.postHandle(context, event, cmd, data); + } + + protected void postHandle(C context, E event, String cmd, Object data, Exception e) { + for(EzyUserRequestInterceptor interceptor : requestInterceptors) + interceptor.postHandle(context, event, cmd, data, e); + } + + protected EzyUncaughtExceptionHandler getExceptionHandler(Class exceptionClass) { + for(Class exc : handledExceptionClasses) { + if(exc.isAssignableFrom(exceptionClass)) + return exceptionHandlers.get(exc); + } + return null; + } + + protected abstract void responseError(C context, E event, EzyData errorData); + + @Override + public Set getCommands() { + Set commands = new HashSet<>(); + commands.addAll(requestHandlers.keySet()); + commands.addAll(prototypeController.getCommands()); + return commands; + } + + public abstract static class Builder + extends EzyLoggable + implements EzyBuilder { + + protected EzyBeanContext beanContext; + protected EzyUnmarshaller unmarshaller; + protected EzyResponseFactory responseFactory; + protected EzySingletonFactory singletonFactory; + protected EzyFeatureCommandManager featureCommandManager; + protected EzyRequestCommandManager requestCommandManager; + + public B beanContext(EzyBeanContext beanContext) { + this.beanContext = beanContext; + this.singletonFactory = beanContext.getSingletonFactory(); + this.responseFactory = beanContext.getSingleton(EzyResponseFactory.class); + this.unmarshaller = beanContext.getSingleton("unmarshaller", EzyUnmarshaller.class); + this.featureCommandManager = beanContext.getSingleton(EzyFeatureCommandManager.class); this.requestCommandManager = beanContext.getSingleton(EzyRequestCommandManager.class); - return (B)this; - } - - protected abstract EzyUserRequestPrototypeController getPrototypeController(); - - private Map extractRequestHandlers() { - Map fromListeners = - extractRequestHandlersFromListener(); - extractRequestCommands(fromListeners); - Map handlers = new HashMap<>(fromListeners); - handlers.putAll(implementClientRequestHandlers()); - return handlers; - } - - private Map extractRequestHandlersFromListener() { - List clientRequestHandlers = getClientRequestHandlers(); + return (B)this; + } + + protected abstract EzyUserRequestPrototypeController getPrototypeController(); + + private Map extractRequestHandlers() { + Map fromListeners = + extractRequestHandlersFromListener(); + extractRequestCommands(fromListeners); + Map handlers = new HashMap<>(fromListeners); + handlers.putAll(implementClientRequestHandlers()); + return handlers; + } + + private Map extractRequestHandlersFromListener() { + List clientRequestHandlers = getClientRequestHandlers(); Map handlers = new HashMap<>(); for(Object handler : clientRequestHandlers) { Class handleType = handler.getClass(); @@ -183,9 +183,9 @@ private Map extractRequestHandlersFromListen logger.debug("add command {} and request handler {}", command, handler); } return handlers; - } - - private void extractRequestCommands(Map handlers) { + } + + private void extractRequestCommands(Map handlers) { for(String command : handlers.keySet()) { EzyUserRequestHandlerProxy handler = handlers.get(command); Class handleType = handler.getHandler().getClass(); @@ -202,57 +202,57 @@ private void extractRequestCommands(Map hand } } } - - private List getRequestInterceptors() { - List interceptors = - singletonFactory.getSingletons(EzyRequestInterceptor.class); - List answer = new ArrayList<>(); - for(EzyUserRequestInterceptor interceptor : interceptors) { - logger.debug("add interceptor {}", interceptor); - answer.add(interceptor); - } - answer.sort((a, b) -> - EzyRequestInterceptorAnnotations.getPriority(a.getClass()) - - EzyRequestInterceptorAnnotations.getPriority(b.getClass()) - ); - return interceptors; - } - - private Map, EzyUncaughtExceptionHandler> getExceptionHandlers() { - Map, EzyUncaughtExceptionHandler> handlers = new HashMap<>(); - Map, EzyUncaughtExceptionHandler> implementedHandlers = implementExceptionHandlers(); - for(Class exceptionClass : implementedHandlers.keySet()) { - EzyUncaughtExceptionHandler handler = implementedHandlers.get(exceptionClass); - logger.debug("add exception {} and handler {}", exceptionClass.getName(), handler); - handlers.put(exceptionClass, handler); - } - return handlers; - } - - private List getClientRequestHandlers() { - return singletonFactory.getSingletons(EzyRequestListener.class); - } - - private Map implementClientRequestHandlers() { - EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); - implementer.setResponseFactory(responseFactory); - implementer.setFeatureCommandManager(featureCommandManager); - implementer.setRequestCommandManager(requestCommandManager); - implementer.setAllowOverrideCommand( - beanContext.getProperty(PROPERTY_NAME_MODULE_ALLOW_OVERRIDE_URI, boolean.class, false) - ); - Map implementedHandlers = - implementer.implement(singletonFactory.getSingletons(EzyRequestController.class)); - for(String command : implementedHandlers.keySet()) { + + private List getRequestInterceptors() { + List interceptors = + singletonFactory.getSingletons(EzyRequestInterceptor.class); + List answer = new ArrayList<>(); + for(EzyUserRequestInterceptor interceptor : interceptors) { + logger.debug("add interceptor {}", interceptor); + answer.add(interceptor); + } + answer.sort((a, b) -> + EzyRequestInterceptorAnnotations.getPriority(a.getClass()) + - EzyRequestInterceptorAnnotations.getPriority(b.getClass()) + ); + return interceptors; + } + + private Map, EzyUncaughtExceptionHandler> getExceptionHandlers() { + Map, EzyUncaughtExceptionHandler> handlers = new HashMap<>(); + Map, EzyUncaughtExceptionHandler> implementedHandlers = implementExceptionHandlers(); + for(Class exceptionClass : implementedHandlers.keySet()) { + EzyUncaughtExceptionHandler handler = implementedHandlers.get(exceptionClass); + logger.debug("add exception {} and handler {}", exceptionClass.getName(), handler); + handlers.put(exceptionClass, handler); + } + return handlers; + } + + private List getClientRequestHandlers() { + return singletonFactory.getSingletons(EzyRequestListener.class); + } + + private Map implementClientRequestHandlers() { + EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); + implementer.setResponseFactory(responseFactory); + implementer.setFeatureCommandManager(featureCommandManager); + implementer.setRequestCommandManager(requestCommandManager); + implementer.setAllowOverrideCommand( + beanContext.getProperty(PROPERTY_NAME_MODULE_ALLOW_OVERRIDE_URI, boolean.class, false) + ); + Map implementedHandlers = + implementer.implement(singletonFactory.getSingletons(EzyRequestController.class)); + for(String command : implementedHandlers.keySet()) { EzyUserRequestHandler handler = implementedHandlers.get(command); logger.debug("add command {} and request handler {}", command, handler); } - return implementedHandlers; - } - - private Map, EzyUncaughtExceptionHandler> implementExceptionHandlers() { - EzyExceptionHandlersImplementer implementer = new EzyExceptionHandlersImplementer(); - return implementer.implement(singletonFactory.getSingletons(EzyExceptionHandler.class)); - } - } + return implementedHandlers; + } + + private Map, EzyUncaughtExceptionHandler> implementExceptionHandlers() { + EzyExceptionHandlersImplementer implementer = new EzyExceptionHandlersImplementer(); + return implementer.implement(singletonFactory.getSingletons(EzyExceptionHandler.class)); + } + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimpleAppEntry.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimpleAppEntry.java index e3dc97376..6d30be935 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimpleAppEntry.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimpleAppEntry.java @@ -41,146 +41,146 @@ @SuppressWarnings({"unchecked", "rawtypes"}) public class EzySimpleAppEntry extends EzyAbstractAppEntry { - @Override - public final void config(EzyAppContext context) { - preConfig(context); - EzyBeanContext beanContext = createBeanContext(context); - context.setProperty(EzyBeanContext.class, beanContext); - addEventControllers(context, beanContext); - setAppRequestController(context, beanContext); - postConfig(context); - postConfig(context, beanContext); - } - - protected void preConfig(EzyAppContext context) {} - protected void postConfig(EzyAppContext context) {} - protected void postConfig(EzyAppContext context, EzyBeanContext beanContext) {} - - private void addEventControllers(EzyAppContext appContext, EzyBeanContext beanContext) { - EzySetup setup = appContext.get(EzySetup.class); - List eventControllers = beanContext.getSingletons(EzyEventHandler.class); - sortEventHandlersByPriority(eventControllers); - for (Object controller : eventControllers) { - Class controllerType = controller.getClass(); - EzyEventHandler annotation = controllerType.getAnnotation(EzyEventHandler.class); - String eventName = EzyEventHandlerAnnotations.getEvent(annotation); - setup.addEventController(EzyEventType.valueOf(eventName), (EzyEventController) controller); - logger.info("add event {} controller {}", eventName, controller); - } - } - - private void setAppRequestController(EzyAppContext appContext, EzyBeanContext beanContext) { - EzyAppSetup setup = appContext.get(EzyAppSetup.class); - EzyAppRequestController controller = newUserRequestController(beanContext); - setup.setRequestController(controller); - Set commands = ((EzyCommandsAware)controller).getCommands(); - appContext.setProperty(COMMANDS, commands); - } - - protected EzyAppRequestController newUserRequestController(EzyBeanContext beanContext) { - return EzyUserRequestAppSingletonController.builder() - .beanContext(beanContext) - .build(); - } - - protected EzyBeanContext createBeanContext(EzyAppContext context) { - EzyBindingContext bindingContext = createBindingContext(); - EzyMarshaller marshaller = bindingContext.newMarshaller(); - EzyUnmarshaller unmarshaller = bindingContext.newUnmarshaller(); - EzyResponseFactory appResponseFactory = createAppResponseFactory(context, marshaller); - ScheduledExecutorService executorService = context.get(ScheduledExecutorService.class); - EzyAppSetting appSetting = context.getApp().getSetting(); - EzyBeanContextBuilder beanContextBuilder = EzyBeanContext.builder() - .addSingleton("appContext", context) - .addSingleton("marshaller", marshaller) - .addSingleton("unmarshaller", unmarshaller) - .addSingleton("executorService", executorService) - .addSingleton("zoneContext", context.getParent()) - .addSingleton("serverContext", context.getParent().getParent()) - .addSingleton("userManager", context.getApp().getUserManager()) - .addSingleton("appResponseFactory", appResponseFactory) - .addSingleton("featureCommandManager", new EzyFeatureCommandManager()) - .addSingleton("requestCommandManager", new EzyRequestCommandManager()) - .activeProfiles(appSetting.getActiveProfiles()); - Class[] singletonClasses = getSingletonClasses(); - beanContextBuilder.addSingletonClasses(singletonClasses); - Class[] prototypeClasses = getPrototypeClasses(); - beanContextBuilder.addPrototypeClasses(prototypeClasses); - - Set scanablePackages = internalGetScanableBeanPackages(); - if(appSetting.getPackageName() != null) { - scanablePackages.add(appSetting.getPackageName()); - } - EzyReflection reflection = new EzyReflectionProxy(scanablePackages); - beanContextBuilder.addSingletonClasses( - (Set)reflection.getAnnotatedExtendsClasses( - EzyEventHandler.class, - EzyAppEventController.class)); - beanContextBuilder.addSingletonClasses( - (Set)reflection.getAnnotatedClasses(EzyRequestController.class)); - beanContextBuilder.addSingletonClasses( - (Set)reflection.getAnnotatedClasses(EzyExceptionHandler.class)); - beanContextBuilder.addSingletonClasses( - (Set)reflection.getAnnotatedClasses(EzyRequestInterceptor.class)); - beanContextBuilder.scan(scanablePackages); - setupBeanContext(context, beanContextBuilder); - return beanContextBuilder.build(); - } - - protected EzyBindingContext createBindingContext() { - return EzyBindingContext.builder() - .scan(internalGetScanableBindingPackages()) - .build(); - } - - private EzyResponseFactory createAppResponseFactory( - EzyAppContext appContext, EzyMarshaller marshaller) { - EzyAppResponseFactory factory = new EzyAppResponseFactory(); - factory.setAppContext(appContext); - factory.setMarshaller(marshaller); - return factory; - } - - protected Class[] getSingletonClasses() { - return new Class[0]; - } - - protected Class[] getPrototypeClasses() { - return new Class[0]; - } - - protected String[] getScanablePackages() { - return new String[0]; - } - - protected String[] getScanableBeanPackages() { - return new String[0]; - } - protected String[] getScanableBindingPackages() { - return new String[0]; - } - - private Set internalGetScanableBeanPackages() { - Set scanablePackages = new HashSet(); - scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); - scanablePackages.addAll(Arrays.asList(getScanablePackages())); - scanablePackages.addAll(Arrays.asList(getScanableBeanPackages())); - return scanablePackages; - } - - private Set internalGetScanableBindingPackages() { - Set scanablePackages = new HashSet(); - scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); - scanablePackages.addAll(Arrays.asList(getScanablePackages())); - scanablePackages.addAll(Arrays.asList(getScanableBindingPackages())); - return scanablePackages; - } - - protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) {} - - @Override - public void start() throws Exception {} - - @Override - public void destroy() {} + @Override + public final void config(EzyAppContext context) { + preConfig(context); + EzyBeanContext beanContext = createBeanContext(context); + context.setProperty(EzyBeanContext.class, beanContext); + addEventControllers(context, beanContext); + setAppRequestController(context, beanContext); + postConfig(context); + postConfig(context, beanContext); + } + + protected void preConfig(EzyAppContext context) {} + protected void postConfig(EzyAppContext context) {} + protected void postConfig(EzyAppContext context, EzyBeanContext beanContext) {} + + private void addEventControllers(EzyAppContext appContext, EzyBeanContext beanContext) { + EzySetup setup = appContext.get(EzySetup.class); + List eventControllers = beanContext.getSingletons(EzyEventHandler.class); + sortEventHandlersByPriority(eventControllers); + for (Object controller : eventControllers) { + Class controllerType = controller.getClass(); + EzyEventHandler annotation = controllerType.getAnnotation(EzyEventHandler.class); + String eventName = EzyEventHandlerAnnotations.getEvent(annotation); + setup.addEventController(EzyEventType.valueOf(eventName), (EzyEventController) controller); + logger.info("add event {} controller {}", eventName, controller); + } + } + + private void setAppRequestController(EzyAppContext appContext, EzyBeanContext beanContext) { + EzyAppSetup setup = appContext.get(EzyAppSetup.class); + EzyAppRequestController controller = newUserRequestController(beanContext); + setup.setRequestController(controller); + Set commands = ((EzyCommandsAware)controller).getCommands(); + appContext.setProperty(COMMANDS, commands); + } + + protected EzyAppRequestController newUserRequestController(EzyBeanContext beanContext) { + return EzyUserRequestAppSingletonController.builder() + .beanContext(beanContext) + .build(); + } + + protected EzyBeanContext createBeanContext(EzyAppContext context) { + EzyBindingContext bindingContext = createBindingContext(); + EzyMarshaller marshaller = bindingContext.newMarshaller(); + EzyUnmarshaller unmarshaller = bindingContext.newUnmarshaller(); + EzyResponseFactory appResponseFactory = createAppResponseFactory(context, marshaller); + ScheduledExecutorService executorService = context.get(ScheduledExecutorService.class); + EzyAppSetting appSetting = context.getApp().getSetting(); + EzyBeanContextBuilder beanContextBuilder = EzyBeanContext.builder() + .addSingleton("appContext", context) + .addSingleton("marshaller", marshaller) + .addSingleton("unmarshaller", unmarshaller) + .addSingleton("executorService", executorService) + .addSingleton("zoneContext", context.getParent()) + .addSingleton("serverContext", context.getParent().getParent()) + .addSingleton("userManager", context.getApp().getUserManager()) + .addSingleton("appResponseFactory", appResponseFactory) + .addSingleton("featureCommandManager", new EzyFeatureCommandManager()) + .addSingleton("requestCommandManager", new EzyRequestCommandManager()) + .activeProfiles(appSetting.getActiveProfiles()); + Class[] singletonClasses = getSingletonClasses(); + beanContextBuilder.addSingletonClasses(singletonClasses); + Class[] prototypeClasses = getPrototypeClasses(); + beanContextBuilder.addPrototypeClasses(prototypeClasses); + + Set scanablePackages = internalGetScanableBeanPackages(); + if(appSetting.getPackageName() != null) { + scanablePackages.add(appSetting.getPackageName()); + } + EzyReflection reflection = new EzyReflectionProxy(scanablePackages); + beanContextBuilder.addSingletonClasses( + (Set)reflection.getAnnotatedExtendsClasses( + EzyEventHandler.class, + EzyAppEventController.class)); + beanContextBuilder.addSingletonClasses( + (Set)reflection.getAnnotatedClasses(EzyRequestController.class)); + beanContextBuilder.addSingletonClasses( + (Set)reflection.getAnnotatedClasses(EzyExceptionHandler.class)); + beanContextBuilder.addSingletonClasses( + (Set)reflection.getAnnotatedClasses(EzyRequestInterceptor.class)); + beanContextBuilder.scan(scanablePackages); + setupBeanContext(context, beanContextBuilder); + return beanContextBuilder.build(); + } + + protected EzyBindingContext createBindingContext() { + return EzyBindingContext.builder() + .scan(internalGetScanableBindingPackages()) + .build(); + } + + private EzyResponseFactory createAppResponseFactory( + EzyAppContext appContext, EzyMarshaller marshaller) { + EzyAppResponseFactory factory = new EzyAppResponseFactory(); + factory.setAppContext(appContext); + factory.setMarshaller(marshaller); + return factory; + } + + protected Class[] getSingletonClasses() { + return new Class[0]; + } + + protected Class[] getPrototypeClasses() { + return new Class[0]; + } + + protected String[] getScanablePackages() { + return new String[0]; + } + + protected String[] getScanableBeanPackages() { + return new String[0]; + } + protected String[] getScanableBindingPackages() { + return new String[0]; + } + + private Set internalGetScanableBeanPackages() { + Set scanablePackages = new HashSet(); + scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); + scanablePackages.addAll(Arrays.asList(getScanablePackages())); + scanablePackages.addAll(Arrays.asList(getScanableBeanPackages())); + return scanablePackages; + } + + private Set internalGetScanableBindingPackages() { + Set scanablePackages = new HashSet(); + scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); + scanablePackages.addAll(Arrays.asList(getScanablePackages())); + scanablePackages.addAll(Arrays.asList(getScanableBindingPackages())); + return scanablePackages; + } + + protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) {} + + @Override + public void start() throws Exception {} + + @Override + public void destroy() {} } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimplePluginEntry.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimplePluginEntry.java index 5dc1543bf..d80eadd0f 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimplePluginEntry.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/entry/EzySimplePluginEntry.java @@ -41,160 +41,160 @@ @SuppressWarnings({"unchecked", "rawtypes"}) public class EzySimplePluginEntry extends EzyAbstractPluginEntry { - - @Override - public void config(EzyPluginContext context) { - preConfig(context); - EzyBeanContext beanContext = createBeanContext(context); - context.setProperty(EzyBeanContext.class, beanContext); - addEventControllers(context, beanContext); - setPluginRequestController(context, beanContext); - postConfig(context); - postConfig(context, beanContext); - } - - protected void preConfig(EzyPluginContext ctx) {} - - protected void postConfig(EzyPluginContext ctx) {} - - protected void postConfig(EzyPluginContext ctx, EzyBeanContext beanContext) {} - - private void addEventControllers(EzyPluginContext context, EzyBeanContext beanContext) { - EzySetup setup = context.get(EzySetup.class); - List eventControllers = beanContext.getSingletons(EzyEventHandler.class); - sortEventHandlersByPriority(eventControllers); - for (Object controller : eventControllers) { - Class handlerType = controller.getClass(); - EzyEventHandler annotation = handlerType.getAnnotation(EzyEventHandler.class); - String eventName = EzyEventHandlerAnnotations.getEvent(annotation); - setup.addEventController(EzyEventType.valueOf(eventName), (EzyEventController) controller); - logger.info("add event {} controller {}", eventName, controller); - } - } - - private void setPluginRequestController(EzyPluginContext pluginContext, EzyBeanContext beanContext) { - if(!allowRequest() || getClass().isAnnotationPresent(EzyDisallowRequest.class)) { - return; - } - EzyPluginSetup setup = pluginContext.get(EzyPluginSetup.class); - EzyPluginRequestController controller = newUserRequestController(beanContext); - setup.setRequestController(controller); - Set commands = ((EzyCommandsAware)controller).getCommands(); - pluginContext.setProperty(COMMANDS, commands); - } - - protected boolean allowRequest() { - return true; - } - - protected EzyPluginRequestController newUserRequestController(EzyBeanContext beanContext) { - return EzyUserRequestPluginSingletonController.builder() - .beanContext(beanContext) - .build(); - } - - private EzyBeanContext createBeanContext(EzyPluginContext context) { - EzyBindingContext bindingContext = createBindingContext(); - EzyMarshaller marshaller = bindingContext.newMarshaller(); - EzyUnmarshaller unmarshaller = bindingContext.newUnmarshaller(); - EzyResponseFactory pluginResponseFactory = createPluginResponseFactory(context, marshaller); - ScheduledExecutorService executorService = context.get(ScheduledExecutorService.class); - EzyPluginSetting pluginSetting = context.getPlugin().getSetting(); - EzyBeanContextBuilder beanContextBuilder = EzyBeanContext.builder() - .addSingleton("pluginContext", context) - .addSingleton("marshaller", marshaller) - .addSingleton("unmarshaller", unmarshaller) - .addSingleton("executorService", executorService) - .addSingleton("zoneContext", context.getParent()) - .addSingleton("serverContext", context.getParent().getParent()) - .addSingleton("pluginResponseFactory", pluginResponseFactory) - .addSingleton("featureCommandManager", new EzyFeatureCommandManager()) + + @Override + public void config(EzyPluginContext context) { + preConfig(context); + EzyBeanContext beanContext = createBeanContext(context); + context.setProperty(EzyBeanContext.class, beanContext); + addEventControllers(context, beanContext); + setPluginRequestController(context, beanContext); + postConfig(context); + postConfig(context, beanContext); + } + + protected void preConfig(EzyPluginContext ctx) {} + + protected void postConfig(EzyPluginContext ctx) {} + + protected void postConfig(EzyPluginContext ctx, EzyBeanContext beanContext) {} + + private void addEventControllers(EzyPluginContext context, EzyBeanContext beanContext) { + EzySetup setup = context.get(EzySetup.class); + List eventControllers = beanContext.getSingletons(EzyEventHandler.class); + sortEventHandlersByPriority(eventControllers); + for (Object controller : eventControllers) { + Class handlerType = controller.getClass(); + EzyEventHandler annotation = handlerType.getAnnotation(EzyEventHandler.class); + String eventName = EzyEventHandlerAnnotations.getEvent(annotation); + setup.addEventController(EzyEventType.valueOf(eventName), (EzyEventController) controller); + logger.info("add event {} controller {}", eventName, controller); + } + } + + private void setPluginRequestController(EzyPluginContext pluginContext, EzyBeanContext beanContext) { + if(!allowRequest() || getClass().isAnnotationPresent(EzyDisallowRequest.class)) { + return; + } + EzyPluginSetup setup = pluginContext.get(EzyPluginSetup.class); + EzyPluginRequestController controller = newUserRequestController(beanContext); + setup.setRequestController(controller); + Set commands = ((EzyCommandsAware)controller).getCommands(); + pluginContext.setProperty(COMMANDS, commands); + } + + protected boolean allowRequest() { + return true; + } + + protected EzyPluginRequestController newUserRequestController(EzyBeanContext beanContext) { + return EzyUserRequestPluginSingletonController.builder() + .beanContext(beanContext) + .build(); + } + + private EzyBeanContext createBeanContext(EzyPluginContext context) { + EzyBindingContext bindingContext = createBindingContext(); + EzyMarshaller marshaller = bindingContext.newMarshaller(); + EzyUnmarshaller unmarshaller = bindingContext.newUnmarshaller(); + EzyResponseFactory pluginResponseFactory = createPluginResponseFactory(context, marshaller); + ScheduledExecutorService executorService = context.get(ScheduledExecutorService.class); + EzyPluginSetting pluginSetting = context.getPlugin().getSetting(); + EzyBeanContextBuilder beanContextBuilder = EzyBeanContext.builder() + .addSingleton("pluginContext", context) + .addSingleton("marshaller", marshaller) + .addSingleton("unmarshaller", unmarshaller) + .addSingleton("executorService", executorService) + .addSingleton("zoneContext", context.getParent()) + .addSingleton("serverContext", context.getParent().getParent()) + .addSingleton("pluginResponseFactory", pluginResponseFactory) + .addSingleton("featureCommandManager", new EzyFeatureCommandManager()) .addSingleton("requestCommandManager", new EzyRequestCommandManager()) - .activeProfiles(pluginSetting.getActiveProfiles()); - Class[] singletonClasses = getSingletonClasses(); - beanContextBuilder.addSingletonClasses(singletonClasses); - Class[] prototypeClasses = getPrototypeClasses(); - beanContextBuilder.addPrototypeClasses(prototypeClasses); - - Set scanablePackages = internalGetScanableBeanPackages(); - if(pluginSetting.getPackageName() != null) { - scanablePackages.add(pluginSetting.getPackageName()); - } - EzyReflection reflection = new EzyReflectionProxy(scanablePackages); - beanContextBuilder.addSingletonClasses( - (Set) reflection.getAnnotatedExtendsClasses( - EzyEventHandler.class, - EzyPluginEventController.class)); - beanContextBuilder.addSingletonClasses( - (Set) reflection.getAnnotatedClasses(EzyRequestController.class)); - beanContextBuilder.addSingletonClasses( - (Set) reflection.getAnnotatedClasses(EzyExceptionHandler.class)); - beanContextBuilder.addSingletonClasses( - (Set) reflection.getAnnotatedClasses(EzyRequestInterceptor.class)); - beanContextBuilder.scan(scanablePackages); - setupBeanContext(context, beanContextBuilder); - return beanContextBuilder.build(); - } - - protected EzyBindingContext createBindingContext() { - return EzyBindingContext.builder() - .scan(internalGetScanableBindingPackages()) - .build(); - } - - private EzyResponseFactory createPluginResponseFactory( - EzyPluginContext pluginContext, EzyMarshaller marshaller) { - EzyPluginResponseFactory factory = new EzyPluginResponseFactory(); - factory.setPluginContext(pluginContext); - factory.setMarshaller(marshaller); - return factory; - } - - protected Class[] getSingletonClasses() { - return new Class[0]; - } - - protected Class[] getPrototypeClasses() { - return new Class[0]; - } - - protected String[] getScanablePackages() { - return new String[0]; - } - - protected String[] getScanableBeanPackages() { - return new String[0]; - } - - protected String[] getScanableBindingPackages() { - return new String[0]; - } - - private Set internalGetScanableBeanPackages() { - Set scanablePackages = new HashSet(); - scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); - scanablePackages.addAll(Arrays.asList(getScanablePackages())); - scanablePackages.addAll(Arrays.asList(getScanableBeanPackages())); - return scanablePackages; - } - - private Set internalGetScanableBindingPackages() { - Set scanablePackages = new HashSet(); - scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); - scanablePackages.addAll(Arrays.asList(getScanablePackages())); - scanablePackages.addAll(Arrays.asList(getScanableBindingPackages())); - return scanablePackages; - } - - protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { - } - - @Override - public void start() throws Exception { - } - - @Override - public void destroy() { - } - + .activeProfiles(pluginSetting.getActiveProfiles()); + Class[] singletonClasses = getSingletonClasses(); + beanContextBuilder.addSingletonClasses(singletonClasses); + Class[] prototypeClasses = getPrototypeClasses(); + beanContextBuilder.addPrototypeClasses(prototypeClasses); + + Set scanablePackages = internalGetScanableBeanPackages(); + if(pluginSetting.getPackageName() != null) { + scanablePackages.add(pluginSetting.getPackageName()); + } + EzyReflection reflection = new EzyReflectionProxy(scanablePackages); + beanContextBuilder.addSingletonClasses( + (Set) reflection.getAnnotatedExtendsClasses( + EzyEventHandler.class, + EzyPluginEventController.class)); + beanContextBuilder.addSingletonClasses( + (Set) reflection.getAnnotatedClasses(EzyRequestController.class)); + beanContextBuilder.addSingletonClasses( + (Set) reflection.getAnnotatedClasses(EzyExceptionHandler.class)); + beanContextBuilder.addSingletonClasses( + (Set) reflection.getAnnotatedClasses(EzyRequestInterceptor.class)); + beanContextBuilder.scan(scanablePackages); + setupBeanContext(context, beanContextBuilder); + return beanContextBuilder.build(); + } + + protected EzyBindingContext createBindingContext() { + return EzyBindingContext.builder() + .scan(internalGetScanableBindingPackages()) + .build(); + } + + private EzyResponseFactory createPluginResponseFactory( + EzyPluginContext pluginContext, EzyMarshaller marshaller) { + EzyPluginResponseFactory factory = new EzyPluginResponseFactory(); + factory.setPluginContext(pluginContext); + factory.setMarshaller(marshaller); + return factory; + } + + protected Class[] getSingletonClasses() { + return new Class[0]; + } + + protected Class[] getPrototypeClasses() { + return new Class[0]; + } + + protected String[] getScanablePackages() { + return new String[0]; + } + + protected String[] getScanableBeanPackages() { + return new String[0]; + } + + protected String[] getScanableBindingPackages() { + return new String[0]; + } + + private Set internalGetScanableBeanPackages() { + Set scanablePackages = new HashSet(); + scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); + scanablePackages.addAll(Arrays.asList(getScanablePackages())); + scanablePackages.addAll(Arrays.asList(getScanableBeanPackages())); + return scanablePackages; + } + + private Set internalGetScanableBindingPackages() { + Set scanablePackages = new HashSet(); + scanablePackages.add(DEFAULT_PACKAGE_TO_SCAN); + scanablePackages.addAll(Arrays.asList(getScanablePackages())); + scanablePackages.addAll(Arrays.asList(getScanableBindingPackages())); + return scanablePackages; + } + + protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { + } + + @Override + public void start() throws Exception { + } + + @Override + public void destroy() { + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyDuplicateRequestHandlerException.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyDuplicateRequestHandlerException.java index c9ff994f0..2824e353e 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyDuplicateRequestHandlerException.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyDuplicateRequestHandlerException.java @@ -3,13 +3,13 @@ import com.tvd12.ezyfoxserver.support.handler.EzyUserRequestHandler; public class EzyDuplicateRequestHandlerException extends IllegalStateException { - private static final long serialVersionUID = 2586181034307827101L; - - @SuppressWarnings("rawtypes") - public EzyDuplicateRequestHandlerException( - String command, - EzyUserRequestHandler old, EzyUserRequestHandler now) { - super("duplicate handler for: " + command + " <> " + old + " => " + now); - } - + private static final long serialVersionUID = 2586181034307827101L; + + @SuppressWarnings("rawtypes") + public EzyDuplicateRequestHandlerException( + String command, + EzyUserRequestHandler old, EzyUserRequestHandler now) { + super("duplicate handler for: " + command + " <> " + old + " => " + now); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyUserRequestException.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyUserRequestException.java index 0575fa870..03f080b78 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyUserRequestException.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/exception/EzyUserRequestException.java @@ -4,18 +4,18 @@ @Getter public class EzyUserRequestException extends IllegalStateException { - private static final long serialVersionUID = 2586181034307827101L; + private static final long serialVersionUID = 2586181034307827101L; + + protected final String command; + protected final Object data; + + public EzyUserRequestException( + String command, + Object data, + Exception e) { + super("handle request: " + command + " with data: " + data + " error", e); + this.command = command; + this.data = data; + } - protected final String command; - protected final Object data; - - public EzyUserRequestException( - String command, - Object data, - Exception e) { - super("handle request: " + command + " with data: " + data + " error", e); - this.command = command; - this.data = data; - } - } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAbstractResponseFactory.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAbstractResponseFactory.java index abd84665f..0936a4b8d 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAbstractResponseFactory.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAbstractResponseFactory.java @@ -7,6 +7,6 @@ @Setter public abstract class EzyAbstractResponseFactory implements EzyResponseFactory { - protected EzyMarshaller marshaller; - + protected EzyMarshaller marshaller; + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAppResponseFactory.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAppResponseFactory.java index 2a64881f7..78881223c 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAppResponseFactory.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyAppResponseFactory.java @@ -11,16 +11,16 @@ @Setter public class EzyAppResponseFactory extends EzyAbstractResponseFactory { - protected EzyAppContext appContext; - - @Override - public EzyArrayResponse newArrayResponse() { - return new EzyAppArrayResponse(appContext, marshaller); - } - - @Override - public EzyObjectResponse newObjectResponse() { - return new EzyAppObjectResponse(appContext, marshaller); - } - + protected EzyAppContext appContext; + + @Override + public EzyArrayResponse newArrayResponse() { + return new EzyAppArrayResponse(appContext, marshaller); + } + + @Override + public EzyObjectResponse newObjectResponse() { + return new EzyAppObjectResponse(appContext, marshaller); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyPluginResponseFactory.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyPluginResponseFactory.java index eb32ffc2e..3a299f527 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyPluginResponseFactory.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyPluginResponseFactory.java @@ -11,16 +11,16 @@ @Setter public class EzyPluginResponseFactory extends EzyAbstractResponseFactory { - protected EzyPluginContext pluginContext; - - @Override - public EzyArrayResponse newArrayResponse() { - return new EzyPluginArrayResponse(pluginContext, marshaller); - } - - @Override - public EzyObjectResponse newObjectResponse() { - return new EzyPluginObjectResponse(pluginContext, marshaller); - } - + protected EzyPluginContext pluginContext; + + @Override + public EzyArrayResponse newArrayResponse() { + return new EzyPluginArrayResponse(pluginContext, marshaller); + } + + @Override + public EzyObjectResponse newObjectResponse() { + return new EzyPluginObjectResponse(pluginContext, marshaller); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyResponseFactory.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyResponseFactory.java index 2a10136f0..55268efad 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyResponseFactory.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/factory/EzyResponseFactory.java @@ -5,8 +5,8 @@ public interface EzyResponseFactory { - EzyArrayResponse newArrayResponse(); - - EzyObjectResponse newObjectResponse(); - + EzyArrayResponse newArrayResponse(); + + EzyObjectResponse newObjectResponse(); + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyAbstractUserRequestHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyAbstractUserRequestHandler.java index 4dfe415ad..fa50a3e2a 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyAbstractUserRequestHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyAbstractUserRequestHandler.java @@ -5,18 +5,18 @@ import com.tvd12.ezyfoxserver.context.EzyContext; public abstract class EzyAbstractUserRequestHandler - extends EzyLoggable - implements EzyUserRequestHandler { - - @SuppressWarnings("unchecked") - @Override - public Class getDataType() { - try { - return EzyGenerics.getTwoGenericClassArguments(getClass().getGenericSuperclass())[1]; - } - catch (Exception e) { - return null; - } - } - + extends EzyLoggable + implements EzyUserRequestHandler { + + @SuppressWarnings("unchecked") + @Override + public Class getDataType() { + try { + return EzyGenerics.getTwoGenericClassArguments(getClass().getGenericSuperclass())[1]; + } + catch (Exception e) { + return null; + } + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUncaughtExceptionHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUncaughtExceptionHandler.java index 1b3069a56..835807225 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUncaughtExceptionHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUncaughtExceptionHandler.java @@ -5,11 +5,11 @@ public interface EzyUncaughtExceptionHandler { - void handleException( - C context, - EzyUserSessionEvent event, - String command, - D data, - Exception exception) throws Exception; + void handleException( + C context, + EzyUserSessionEvent event, + String command, + D data, + Exception exception) throws Exception; } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestAppHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestAppHandler.java index 3be4c118a..30e37844a 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestAppHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestAppHandler.java @@ -4,19 +4,19 @@ import com.tvd12.ezyfoxserver.context.EzyAppContext; public interface EzyUserRequestAppHandler - extends EzyUserRequestHandler { - - @SuppressWarnings("unchecked") - @Override - default Class getDataType() { - try { - return EzyGenerics.getGenericInterfacesArguments( - getClass(), - EzyUserRequestAppHandler.class, 1)[0]; - } - catch (Exception e) { - return null; - } - } - + extends EzyUserRequestHandler { + + @SuppressWarnings("unchecked") + @Override + default Class getDataType() { + try { + return EzyGenerics.getGenericInterfacesArguments( + getClass(), + EzyUserRequestAppHandler.class, 1)[0]; + } + catch (Exception e) { + return null; + } + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandler.java index 9a572b81b..c58366230 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandler.java @@ -5,19 +5,19 @@ import com.tvd12.ezyfoxserver.event.EzyUserSessionEvent; public interface EzyUserRequestHandler { - - void handle(C context, EzyUserSessionEvent event, D data); - - @SuppressWarnings("unchecked") - default Class getDataType() { - try { - return EzyGenerics.getGenericInterfacesArguments( - getClass(), - EzyUserRequestHandler.class, 2)[1]; - } - catch (Exception e) { - return null; - } - } - + + void handle(C context, EzyUserSessionEvent event, D data); + + @SuppressWarnings("unchecked") + default Class getDataType() { + try { + return EzyGenerics.getGenericInterfacesArguments( + getClass(), + EzyUserRequestHandler.class, 2)[1]; + } + catch (Exception e) { + return null; + } + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandlerProxy.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandlerProxy.java index e09d917f9..b50ddb0ee 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandlerProxy.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestHandlerProxy.java @@ -9,17 +9,17 @@ @SuppressWarnings({"rawtypes", "unchecked"}) public class EzyUserRequestHandlerProxy implements EzyUserRequestHandler { - protected final Class dataType; - protected final EzyUserRequestHandler handler; - - public EzyUserRequestHandlerProxy(EzyUserRequestHandler handler) { - this.handler = handler; - this.dataType = handler.getDataType(); - } - - @Override - public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { - handler.handle(context, event, data); - } + protected final Class dataType; + protected final EzyUserRequestHandler handler; + + public EzyUserRequestHandlerProxy(EzyUserRequestHandler handler) { + this.handler = handler; + this.dataType = handler.getDataType(); + } + + @Override + public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { + handler.handle(context, event, data); + } } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestInterceptor.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestInterceptor.java index 017974002..f3ccf8df1 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestInterceptor.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestInterceptor.java @@ -4,20 +4,20 @@ import com.tvd12.ezyfoxserver.event.EzyUserSessionEvent; public interface EzyUserRequestInterceptor { - - default void preHandle( - C context, - EzyUserSessionEvent event, - String command, Object data) {} - - default void postHandle( - C context, - EzyUserSessionEvent event, - String command, Object data) {} - - default void postHandle( - C context, - EzyUserSessionEvent event, - String command, Object data, Exception e) {} - + + default void preHandle( + C context, + EzyUserSessionEvent event, + String command, Object data) {} + + default void postHandle( + C context, + EzyUserSessionEvent event, + String command, Object data) {} + + default void postHandle( + C context, + EzyUserSessionEvent event, + String command, Object data, Exception e) {} + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestPluginHandler.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestPluginHandler.java index a32379655..b28e2402a 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestPluginHandler.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/handler/EzyUserRequestPluginHandler.java @@ -4,19 +4,19 @@ import com.tvd12.ezyfoxserver.context.EzyPluginContext; public interface EzyUserRequestPluginHandler - extends EzyUserRequestHandler { - - @SuppressWarnings("unchecked") - @Override - default Class getDataType() { - try { - return EzyGenerics.getGenericInterfacesArguments( - getClass(), - EzyUserRequestPluginHandler.class, 1)[0]; - } - catch (Exception e) { - return null; - } - } - + extends EzyUserRequestHandler { + + @SuppressWarnings("unchecked") + @Override + default Class getDataType() { + try { + return EzyGenerics.getGenericInterfacesArguments( + getClass(), + EzyUserRequestPluginHandler.class, 1)[0]; + } + catch (Exception e) { + return null; + } + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerMethod.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerMethod.java index 6c0ad9f29..2475a0d48 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerMethod.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerMethod.java @@ -9,18 +9,18 @@ @Getter public class EzyExceptionHandlerMethod extends EzyHandlerMethod { - protected final Class[] exceptionClasses; - - public EzyExceptionHandlerMethod(EzyMethod method) { - super(method); - this.exceptionClasses = fetchExceptionClasses(); - - } - - protected Class[] fetchExceptionClasses() { - EzyTryCatch annotation = method.getAnnotation(EzyTryCatch.class); - Class[] classes = EzyTryCatchAnnotations.getExceptionClasses(annotation); - return classes; - } - + protected final Class[] exceptionClasses; + + public EzyExceptionHandlerMethod(EzyMethod method) { + super(method); + this.exceptionClasses = fetchExceptionClasses(); + + } + + protected Class[] fetchExceptionClasses() { + EzyTryCatch annotation = method.getAnnotation(EzyTryCatch.class); + Class[] classes = EzyTryCatchAnnotations.getExceptionClasses(annotation); + return classes; + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerProxy.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerProxy.java index edbb70890..a70539c7c 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerProxy.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyExceptionHandlerProxy.java @@ -12,39 +12,39 @@ @Getter public class EzyExceptionHandlerProxy { - protected final EzyClass clazz; - protected final Object instance; - protected final List exceptionHandlerMethods; - - public EzyExceptionHandlerProxy(Object instance) { - this.instance = instance; - this.clazz = new EzyClass(instance.getClass()); - this.exceptionHandlerMethods = fetchExceptionHandlerMethods(); - } - - public List fetchExceptionHandlerMethods() { - List list = new ArrayList<>(); - List methods = clazz.getPublicMethods(m -> m.isAnnotated(EzyTryCatch.class)); - for(EzyMethod method : methods) { - EzyExceptionHandlerMethod m = new EzyExceptionHandlerMethod(method); - list.add(m); - } - return list; - } - - public String getClassSimpleName() { - return clazz.getClazz().getSimpleName(); - } - - @Override - public String toString() { - return new StringBuilder() - .append(clazz.getName()) - .append("(\n") - .append("\tinstance: ").append(instance).append(",\n") - .append("\texceptionHandlerMethods: ").append(exceptionHandlerMethods).append("\n") - .append(")") - .toString(); - } - + protected final EzyClass clazz; + protected final Object instance; + protected final List exceptionHandlerMethods; + + public EzyExceptionHandlerProxy(Object instance) { + this.instance = instance; + this.clazz = new EzyClass(instance.getClass()); + this.exceptionHandlerMethods = fetchExceptionHandlerMethods(); + } + + public List fetchExceptionHandlerMethods() { + List list = new ArrayList<>(); + List methods = clazz.getPublicMethods(m -> m.isAnnotated(EzyTryCatch.class)); + for(EzyMethod method : methods) { + EzyExceptionHandlerMethod m = new EzyExceptionHandlerMethod(method); + list.add(m); + } + return list; + } + + public String getClassSimpleName() { + return clazz.getClazz().getSimpleName(); + } + + @Override + public String toString() { + return new StringBuilder() + .append(clazz.getName()) + .append("(\n") + .append("\tinstance: ").append(instance).append(",\n") + .append("\texceptionHandlerMethods: ").append(exceptionHandlerMethods).append("\n") + .append(")") + .toString(); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyHandlerMethod.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyHandlerMethod.java index 8d65392f4..851eed2f8 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyHandlerMethod.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyHandlerMethod.java @@ -14,44 +14,44 @@ import lombok.Getter; public abstract class EzyHandlerMethod { - - @Getter - protected final EzyMethod method; - - public EzyHandlerMethod(EzyMethod method) { - this.method = method; - } - - public String getName() { - return method.getName(); - } - - public Parameter[] getParameters() { - return method.getMethod().getParameters(); - } - - public Class[] getParameterTypes() { - return method.getParameterTypes(); - } - - public Class getRequestDataType() { - Class dataType = null; - for(Parameter parameter : getParameters()) { - Class type = parameter.getType(); - if(type != EzyContext.class && - type != EzyAppContext.class && - type != EzyPluginContext.class && - type != EzyUserSessionEvent.class && - type != EzyUser.class && - type != EzySession.class && - !Throwable.class.isAssignableFrom(type)) { - if(dataType == null || type != String.class) - dataType = type; - if(parameter.isAnnotationPresent(EzyRequestData.class)) - break; - } - } - return dataType; - } - + + @Getter + protected final EzyMethod method; + + public EzyHandlerMethod(EzyMethod method) { + this.method = method; + } + + public String getName() { + return method.getName(); + } + + public Parameter[] getParameters() { + return method.getMethod().getParameters(); + } + + public Class[] getParameterTypes() { + return method.getParameterTypes(); + } + + public Class getRequestDataType() { + Class dataType = null; + for(Parameter parameter : getParameters()) { + Class type = parameter.getType(); + if(type != EzyContext.class && + type != EzyAppContext.class && + type != EzyPluginContext.class && + type != EzyUserSessionEvent.class && + type != EzyUser.class && + type != EzySession.class && + !Throwable.class.isAssignableFrom(type)) { + if(dataType == null || type != String.class) + dataType = type; + if(parameter.isAnnotationPresent(EzyRequestData.class)) + break; + } + } + return dataType; + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestControllerProxy.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestControllerProxy.java index d982c858a..165ead53d 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestControllerProxy.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestControllerProxy.java @@ -19,66 +19,66 @@ @Getter public class EzyRequestControllerProxy { - protected final EzyClass clazz; - protected final Object instance; - protected final String commandGroup; - protected final List requestHandlerMethods; - protected final List exceptionHandlerMethods; - protected final Map, EzyExceptionHandlerMethod> exceptionHandlerMethodMap; - - public EzyRequestControllerProxy(Object instance) { - this.instance = instance; - this.clazz = new EzyClass(instance.getClass()); - this.commandGroup = getCommandGroup(); - this.requestHandlerMethods = fetchRequestHandlerMethods(); - this.exceptionHandlerMethods = fetchExceptionHandlerMethods(); - this.exceptionHandlerMethodMap = fetchExceptionHandlerMethodMap(); - } - - protected String getCommandGroup() { - String uri = EzyRequestControllerAnnotations.getGroup(clazz.getClazz()); - return uri; - } - - protected List fetchRequestHandlerMethods() { - List list = new ArrayList<>(); - List methods = clazz.getPublicMethods(m -> isRequestHandlerMethod(m)); - for(EzyMethod method : methods) { - EzyRequestHandlerMethod m = new EzyRequestHandlerMethod(commandGroup, method); - list.add(m); - } - return list; - } - - public List fetchExceptionHandlerMethods() { - List list = new ArrayList<>(); - List methods = clazz.getMethods(m -> m.isAnnotated(EzyTryCatch.class)); - for(EzyMethod method : methods) { - EzyExceptionHandlerMethod m = new EzyExceptionHandlerMethod(method); - list.add(m); - } - return list; - } - - protected final Map, EzyExceptionHandlerMethod> fetchExceptionHandlerMethodMap() { - Map, EzyExceptionHandlerMethod> answer = new HashMap<>(); - for(EzyExceptionHandlerMethod m : exceptionHandlerMethods) { - for(Class exceptionClass : m.getExceptionClasses()) - answer.put(exceptionClass, m); - } - return answer; - } - - protected boolean isRequestHandlerMethod(EzyMethod method) { - return method.isAnnotated(EzyDoHandle.class); - } - - public String getControllerName() { - return clazz.getClazz().getSimpleName(); - } - - public boolean isManagement() { - return clazz.isAnnotated(EzyManagement.class); + protected final EzyClass clazz; + protected final Object instance; + protected final String commandGroup; + protected final List requestHandlerMethods; + protected final List exceptionHandlerMethods; + protected final Map, EzyExceptionHandlerMethod> exceptionHandlerMethodMap; + + public EzyRequestControllerProxy(Object instance) { + this.instance = instance; + this.clazz = new EzyClass(instance.getClass()); + this.commandGroup = getCommandGroup(); + this.requestHandlerMethods = fetchRequestHandlerMethods(); + this.exceptionHandlerMethods = fetchExceptionHandlerMethods(); + this.exceptionHandlerMethodMap = fetchExceptionHandlerMethodMap(); + } + + protected String getCommandGroup() { + String uri = EzyRequestControllerAnnotations.getGroup(clazz.getClazz()); + return uri; + } + + protected List fetchRequestHandlerMethods() { + List list = new ArrayList<>(); + List methods = clazz.getPublicMethods(m -> isRequestHandlerMethod(m)); + for(EzyMethod method : methods) { + EzyRequestHandlerMethod m = new EzyRequestHandlerMethod(commandGroup, method); + list.add(m); + } + return list; + } + + public List fetchExceptionHandlerMethods() { + List list = new ArrayList<>(); + List methods = clazz.getMethods(m -> m.isAnnotated(EzyTryCatch.class)); + for(EzyMethod method : methods) { + EzyExceptionHandlerMethod m = new EzyExceptionHandlerMethod(method); + list.add(m); + } + return list; + } + + protected final Map, EzyExceptionHandlerMethod> fetchExceptionHandlerMethodMap() { + Map, EzyExceptionHandlerMethod> answer = new HashMap<>(); + for(EzyExceptionHandlerMethod m : exceptionHandlerMethods) { + for(Class exceptionClass : m.getExceptionClasses()) + answer.put(exceptionClass, m); + } + return answer; + } + + protected boolean isRequestHandlerMethod(EzyMethod method) { + return method.isAnnotated(EzyDoHandle.class); + } + + public String getControllerName() { + return clazz.getClazz().getSimpleName(); + } + + public boolean isManagement() { + return clazz.isAnnotated(EzyManagement.class); } public boolean isPayment() { @@ -89,16 +89,16 @@ public String getFeature() { EzyFeature annotation = clazz.getAnnotation(EzyFeature.class); return annotation != null ? annotation.value() : null; } - - @Override - public String toString() { - return new StringBuilder() - .append(clazz.getName()) - .append("(\n") - .append("\tinstance: ").append(instance).append(",\n") - .append("\trequestHandlerMethods: ").append(requestHandlerMethods).append(",\n") - .append(")") - .toString(); - } - + + @Override + public String toString() { + return new StringBuilder() + .append(clazz.getName()) + .append("(\n") + .append("\tinstance: ").append(instance).append(",\n") + .append("\trequestHandlerMethods: ").append(requestHandlerMethods).append(",\n") + .append(")") + .toString(); + } + } diff --git a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestHandlerMethod.java b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestHandlerMethod.java index 47d8921f2..3d81548e3 100644 --- a/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestHandlerMethod.java +++ b/ezyfox-server-support/src/main/java/com/tvd12/ezyfoxserver/support/reflect/EzyRequestHandlerMethod.java @@ -13,21 +13,21 @@ @Getter public class EzyRequestHandlerMethod extends EzyHandlerMethod { - protected final String command; - - public EzyRequestHandlerMethod(String group, EzyMethod method) { - super(method); - this.command = fetchCommand(group); - } - - protected String fetchCommand(String group) { - String methodCommand = EzyDoHandleAnnotations - .getCommand(method.getAnnotation(EzyDoHandle.class)); - if(EzyStrings.isNoContent(group)) - return methodCommand; - return group + "/" + methodCommand; - } - + protected final String command; + + public EzyRequestHandlerMethod(String group, EzyMethod method) { + super(method); + this.command = fetchCommand(group); + } + + protected String fetchCommand(String group) { + String methodCommand = EzyDoHandleAnnotations + .getCommand(method.getAnnotation(EzyDoHandle.class)); + if(EzyStrings.isNoContent(group)) + return methodCommand; + return group + "/" + methodCommand; + } + public Class getReturnType() { return method.getReturnType(); } @@ -39,20 +39,20 @@ public boolean isManagement() { public boolean isPayment() { return method.isAnnotated(EzyPayment.class); } - + public String getFeature() { EzyFeature annotation = method.getAnnotation(EzyFeature.class); return annotation != null ? annotation.value() : null; } - @Override - public String toString() { - return new StringBuilder() - .append(method.getName()) - .append("(") - .append("command: ").append(command) - .append(")") - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append(method.getName()) + .append("(") + .append("command: ").append(command) + .append(")") + .toString(); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlerImplementerTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlerImplementerTest.java index c178af20c..028b63101 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlerImplementerTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlerImplementerTest.java @@ -12,33 +12,33 @@ public class EzyExceptionHandlerImplementerTest { - @Test(expectedExceptions = IllegalStateException.class) - public void testFailedCase() throws Exception { - EzyExceptionHandlerProxy handlerProxy = - new EzyExceptionHandlerProxy(new ExceptionHandlerFail()); - EzyExceptionHandlerMethod method = - new EzyExceptionHandlerMethod(new EzyMethod( - ExceptionHandlerFail.class - .getDeclaredMethod("handle", Exception.class, int.class))); - new EzyExceptionHandlerImplementer(handlerProxy, method) { - @SuppressWarnings("rawtypes") - @Override - protected EzyUncaughtExceptionHandler doimplement() throws Exception { - throw new IllegalStateException("test"); - } - } - .implement(); - - } - - public static class ExceptionHandlerFail { - - @EzyTryCatch(Exception.class) - public void handle(Exception e, - @EzyRequestData int value) { - e.printStackTrace(); - } - - } - + @Test(expectedExceptions = IllegalStateException.class) + public void testFailedCase() throws Exception { + EzyExceptionHandlerProxy handlerProxy = + new EzyExceptionHandlerProxy(new ExceptionHandlerFail()); + EzyExceptionHandlerMethod method = + new EzyExceptionHandlerMethod(new EzyMethod( + ExceptionHandlerFail.class + .getDeclaredMethod("handle", Exception.class, int.class))); + new EzyExceptionHandlerImplementer(handlerProxy, method) { + @SuppressWarnings("rawtypes") + @Override + protected EzyUncaughtExceptionHandler doimplement() throws Exception { + throw new IllegalStateException("test"); + } + } + .implement(); + + } + + public static class ExceptionHandlerFail { + + @EzyTryCatch(Exception.class) + public void handle(Exception e, + @EzyRequestData int value) { + e.printStackTrace(); + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlersImplementerTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlersImplementerTest.java index ea3a1de3b..e9ba2b557 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlersImplementerTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyExceptionHandlersImplementerTest.java @@ -12,23 +12,23 @@ public class EzyExceptionHandlersImplementerTest { - @Test - public void test() { - EzyExceptionHandlerImplementer.setDebug(true); - EzyExceptionHandlersImplementer implementer = new EzyExceptionHandlersImplementer(); - implementer.implement(Arrays.asList(new ExExceptionHandler())); - EzyExceptionHandlerImplementer.setDebug(false); - implementer.implement(Arrays.asList(new ExExceptionHandler())); - } - - @EzyExceptionHandler - public static class ExExceptionHandler { - - @EzyTryCatch(IllegalArgumentException.class) - public void handle(EzySession session, IllegalArgumentException ex) { - ex.printStackTrace(); - } - - } - + @Test + public void test() { + EzyExceptionHandlerImplementer.setDebug(true); + EzyExceptionHandlersImplementer implementer = new EzyExceptionHandlersImplementer(); + implementer.implement(Arrays.asList(new ExExceptionHandler())); + EzyExceptionHandlerImplementer.setDebug(false); + implementer.implement(Arrays.asList(new ExExceptionHandler())); + } + + @EzyExceptionHandler + public static class ExExceptionHandler { + + @EzyTryCatch(IllegalArgumentException.class) + public void handle(EzySession session, IllegalArgumentException ex) { + ex.printStackTrace(); + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyRequestHandlersImplementerTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyRequestHandlersImplementerTest.java index b7e887cf6..b42f51c38 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyRequestHandlersImplementerTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/asm/EzyRequestHandlersImplementerTest.java @@ -38,93 +38,93 @@ public class EzyRequestHandlersImplementerTest { - @Test - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void test() { - // given - EzyAppContext context = mock(EzyAppContext.class); - EzySession session = mock(EzyAbstractSession.class); - EzyUser user = new EzySimpleUser(); - EzyUserSessionEvent event = new EzySimpleUserSessionEvent(user, session); - EzyRequestHandlerImplementer.setDebug(true); - EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); - - EzyResponseFactory responseFactory = mock(EzyResponseFactory.class); - EzyObjectResponse objectResponse = mock(EzyObjectResponse.class); - when(responseFactory.newObjectResponse()).thenReturn(objectResponse); - when(objectResponse.command("Big/Hello6")).thenReturn(objectResponse); - when(objectResponse.data(new GreetResponse("Hello Dzung!"))).thenReturn(objectResponse); - when(objectResponse.session(any())).thenReturn(objectResponse); - doNothing().when(objectResponse).execute(); - - implementer.setResponseFactory(responseFactory); - - EzyFeatureCommandManager featureCommandManager = new EzyFeatureCommandManager(); + @Test + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void test() { + // given + EzyAppContext context = mock(EzyAppContext.class); + EzySession session = mock(EzyAbstractSession.class); + EzyUser user = new EzySimpleUser(); + EzyUserSessionEvent event = new EzySimpleUserSessionEvent(user, session); + EzyRequestHandlerImplementer.setDebug(true); + EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); + + EzyResponseFactory responseFactory = mock(EzyResponseFactory.class); + EzyObjectResponse objectResponse = mock(EzyObjectResponse.class); + when(responseFactory.newObjectResponse()).thenReturn(objectResponse); + when(objectResponse.command("Big/Hello6")).thenReturn(objectResponse); + when(objectResponse.data(new GreetResponse("Hello Dzung!"))).thenReturn(objectResponse); + when(objectResponse.session(any())).thenReturn(objectResponse); + doNothing().when(objectResponse).execute(); + + implementer.setResponseFactory(responseFactory); + + EzyFeatureCommandManager featureCommandManager = new EzyFeatureCommandManager(); EzyRequestCommandManager requestCommandManager = new EzyRequestCommandManager(); implementer.setFeatureCommandManager(featureCommandManager); implementer.setRequestCommandManager(requestCommandManager); - - Map handlers = implementer.implement( - Collections.singletonList(new HelloController()) - ); - for(EzyUserRequestHandler handler : handlers.values()) { - handler.handle(context, event, new GreetRequest("Dzung")); - } - EzyRequestHandlerImplementer.setDebug(false); - implementer = new EzyRequestHandlersImplementer(); - implementer.setFeatureCommandManager(featureCommandManager); + + Map handlers = implementer.implement( + Collections.singletonList(new HelloController()) + ); + for(EzyUserRequestHandler handler : handlers.values()) { + handler.handle(context, event, new GreetRequest("Dzung")); + } + EzyRequestHandlerImplementer.setDebug(false); + implementer = new EzyRequestHandlersImplementer(); + implementer.setFeatureCommandManager(featureCommandManager); implementer.setRequestCommandManager(requestCommandManager); - - // when - handlers = implementer.implement(Collections.singletonList(new HelloController())); - - // then - Asserts.assertTrue(handlers.containsKey("Big/Hello")); - verify(responseFactory, times(1)).newObjectResponse(); - verify(objectResponse, times(1)).command("Big/Hello6"); - verify(objectResponse, times(1)).data(new GreetResponse("Hello Dzung!")); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testImplementFailedCase() { - EzyRequestControllerProxy proxy - = new EzyRequestControllerProxy(new HelloController()); - EzyRequestHandlerImplementer implementer = - new EzyRequestHandlerImplementer( - proxy, - proxy.getRequestHandlerMethods().get(0)) { - @Override - protected EzyAsmRequestHandler doimplement() throws Exception { - throw new RuntimeException("test"); - } - }; - implementer.implement(); - } - - @Test - public void testImplementFailedCase2() { - EzyRequestHandlerImplementer.setDebug(true); - EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); - EzyFeatureCommandManager featureCommandManager = new EzyFeatureCommandManager(); + + // when + handlers = implementer.implement(Collections.singletonList(new HelloController())); + + // then + Asserts.assertTrue(handlers.containsKey("Big/Hello")); + verify(responseFactory, times(1)).newObjectResponse(); + verify(objectResponse, times(1)).command("Big/Hello6"); + verify(objectResponse, times(1)).data(new GreetResponse("Hello Dzung!")); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testImplementFailedCase() { + EzyRequestControllerProxy proxy + = new EzyRequestControllerProxy(new HelloController()); + EzyRequestHandlerImplementer implementer = + new EzyRequestHandlerImplementer( + proxy, + proxy.getRequestHandlerMethods().get(0)) { + @Override + protected EzyAsmRequestHandler doimplement() throws Exception { + throw new RuntimeException("test"); + } + }; + implementer.implement(); + } + + @Test + public void testImplementFailedCase2() { + EzyRequestHandlerImplementer.setDebug(true); + EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); + EzyFeatureCommandManager featureCommandManager = new EzyFeatureCommandManager(); EzyRequestCommandManager requestCommandManager = new EzyRequestCommandManager(); implementer.setFeatureCommandManager(featureCommandManager); implementer.setRequestCommandManager(requestCommandManager); - implementer.implement(Collections.singletonList(new HelloController2())); - } - - @Test(expectedExceptions = EzyDuplicateRequestHandlerException.class) - public void testImplementFailedCase3() { - EzyRequestHandlerImplementer.setDebug(true); - EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); - EzyFeatureCommandManager featureCommandManager = new EzyFeatureCommandManager(); + implementer.implement(Collections.singletonList(new HelloController2())); + } + + @Test(expectedExceptions = EzyDuplicateRequestHandlerException.class) + public void testImplementFailedCase3() { + EzyRequestHandlerImplementer.setDebug(true); + EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); + EzyFeatureCommandManager featureCommandManager = new EzyFeatureCommandManager(); EzyRequestCommandManager requestCommandManager = new EzyRequestCommandManager(); implementer.setFeatureCommandManager(featureCommandManager); implementer.setRequestCommandManager(requestCommandManager); - implementer.implement(Arrays.asList(new HelloController(), new HelloController())); - } + implementer.implement(Arrays.asList(new HelloController(), new HelloController())); + } - @Test + @Test public void testImplementDuplicateCommandButAllowOverride() { EzyRequestHandlerImplementer.setDebug(true); EzyRequestHandlersImplementer implementer = new EzyRequestHandlersImplementer(); diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/command/EzyAbstractResponseTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/command/EzyAbstractResponseTest.java index 73ac7289f..c1aa02de2 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/command/EzyAbstractResponseTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/command/EzyAbstractResponseTest.java @@ -12,40 +12,40 @@ public class EzyAbstractResponseTest { - private EzyResponse response; - - @Test - public void test() { - // given - response = mock(EzyResponse.class); - Sut sut = new Sut(); - - // when - sut.encrypted(); - sut.encrypted(true); - - // then - verify(response, times(1)).encrypted(); - verify(response, times(1)).encrypted(true); - } - - @SuppressWarnings("rawtypes") - public class Sut extends EzyAbstractResponse { - - public Sut() { - super(null, null); - } - - @Override - protected EzyData getResponseData() { - return null; - } - - @Override - protected EzyResponse newResponse() { - return EzyAbstractResponseTest.this.response; - } - - } - + private EzyResponse response; + + @Test + public void test() { + // given + response = mock(EzyResponse.class); + Sut sut = new Sut(); + + // when + sut.encrypted(); + sut.encrypted(true); + + // then + verify(response, times(1)).encrypted(); + verify(response, times(1)).encrypted(true); + } + + @SuppressWarnings("rawtypes") + public class Sut extends EzyAbstractResponse { + + public Sut() { + super(null, null); + } + + @Override + protected EzyData getResponseData() { + return null; + } + + @Override + protected EzyResponse newResponse() { + return EzyAbstractResponseTest.this.response; + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestAppSingletonControllerTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestAppSingletonControllerTest.java index 9443c6621..331420c5d 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestAppSingletonControllerTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestAppSingletonControllerTest.java @@ -42,197 +42,197 @@ public class EzyUserRequestAppSingletonControllerTest extends BaseTest { - @Test - public void test() throws Exception { - EzyRequestHandlerImplementer.setDebug(true); - EzyExceptionHandlerImplementer.setDebug(true); - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); - appSetting.setName("test"); - - EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() - .build(); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimpleApplication application = new EzySimpleApplication(); - application.setSetting(appSetting); - application.setUserManager(appUserManager); - application.setEventControllers(eventControllers); - - ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimpleAppContext appContext = new EzySimpleAppContext(); - appContext.setApp(application); - appContext.setParent(zoneContext); - appContext.setExecutorService(appScheduledExecutorService); - appContext.init(); - - EzySimpleAppEntry entry = new EzyAppEntryEx(); - entry.config(appContext); - entry.start(); - handleClientRequest(appContext); - EzyBeanContext beanContext = appContext.get(EzyBeanContext.class); - EzyRequestCommandManager requestCommandManager = - beanContext.getSingleton(EzyRequestCommandManager.class); - EzyFeatureCommandManager featureCommandManager = - beanContext.getSingleton(EzyFeatureCommandManager.class); - Asserts.assertTrue(requestCommandManager.containsCommand("v1.2.2/hello")); - Asserts.assertTrue(requestCommandManager.containsCommand("v122/listener/hello")); - Asserts.assertTrue(requestCommandManager.isManagementCommand("v1.2.2/hello")); - Asserts.assertTrue(requestCommandManager.isPaymentCommand("v1.2.2/hello")); - Asserts.assertEquals(featureCommandManager.getFeatureByCommand("v1.2.2/hello"), "hello.world"); - entry.destroy(); - } - - private void handleClientRequest(EzyAppContext context) { - EzySimpleApplication app = (EzySimpleApplication) context.getApp(); - EzyAppRequestController requestController = app.getRequestController(); - - EzyAbstractSession session = spy(EzyAbstractSession.class); - EzySimpleUser user = new EzySimpleUser(); - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append("hello") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - EzyUserRequestAppEvent event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("responseFactoryTest") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("no command") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("hello2") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("hello6") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("c_hello") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestSend") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestNotSend") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("requestException") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - try { - data = EzyEntityFactory.newArrayBuilder() - .append("requestException2") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - } - catch (Exception e) { - assert e.getCause().getClass() == Exception.class; - } - - data = EzyEntityFactory.newArrayBuilder() - .append("requestException3") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - try { - data = EzyEntityFactory.newArrayBuilder() - .append("exception") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - } - catch (Exception e) { - assert e instanceof IllegalStateException; - } - } - - public static class EzyAppEntryEx extends EzySimpleAppEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.controller.app" - }; - } - - @SuppressWarnings("rawtypes") - @Override - protected Class[] getPrototypeClasses() { - return new Class[] { - }; - } - - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.controller" - }; - } - - @Override - protected EzyAppRequestController newUserRequestController(EzyBeanContext beanContext) { - return EzyUserRequestAppSingletonController.builder() - .beanContext(beanContext) - .build(); - } - - } - + @Test + public void test() throws Exception { + EzyRequestHandlerImplementer.setDebug(true); + EzyExceptionHandlerImplementer.setDebug(true); + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); + appSetting.setName("test"); + + EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() + .build(); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimpleApplication application = new EzySimpleApplication(); + application.setSetting(appSetting); + application.setUserManager(appUserManager); + application.setEventControllers(eventControllers); + + ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimpleAppContext appContext = new EzySimpleAppContext(); + appContext.setApp(application); + appContext.setParent(zoneContext); + appContext.setExecutorService(appScheduledExecutorService); + appContext.init(); + + EzySimpleAppEntry entry = new EzyAppEntryEx(); + entry.config(appContext); + entry.start(); + handleClientRequest(appContext); + EzyBeanContext beanContext = appContext.get(EzyBeanContext.class); + EzyRequestCommandManager requestCommandManager = + beanContext.getSingleton(EzyRequestCommandManager.class); + EzyFeatureCommandManager featureCommandManager = + beanContext.getSingleton(EzyFeatureCommandManager.class); + Asserts.assertTrue(requestCommandManager.containsCommand("v1.2.2/hello")); + Asserts.assertTrue(requestCommandManager.containsCommand("v122/listener/hello")); + Asserts.assertTrue(requestCommandManager.isManagementCommand("v1.2.2/hello")); + Asserts.assertTrue(requestCommandManager.isPaymentCommand("v1.2.2/hello")); + Asserts.assertEquals(featureCommandManager.getFeatureByCommand("v1.2.2/hello"), "hello.world"); + entry.destroy(); + } + + private void handleClientRequest(EzyAppContext context) { + EzySimpleApplication app = (EzySimpleApplication) context.getApp(); + EzyAppRequestController requestController = app.getRequestController(); + + EzyAbstractSession session = spy(EzyAbstractSession.class); + EzySimpleUser user = new EzySimpleUser(); + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append("hello") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + EzyUserRequestAppEvent event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("responseFactoryTest") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("no command") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("hello2") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("hello6") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("c_hello") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestSend") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestNotSend") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("requestException") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + try { + data = EzyEntityFactory.newArrayBuilder() + .append("requestException2") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + } + catch (Exception e) { + assert e.getCause().getClass() == Exception.class; + } + + data = EzyEntityFactory.newArrayBuilder() + .append("requestException3") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + try { + data = EzyEntityFactory.newArrayBuilder() + .append("exception") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + } + catch (Exception e) { + assert e instanceof IllegalStateException; + } + } + + public static class EzyAppEntryEx extends EzySimpleAppEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.controller.app" + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected Class[] getPrototypeClasses() { + return new Class[] { + }; + } + + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.controller" + }; + } + + @Override + protected EzyAppRequestController newUserRequestController(EzyBeanContext beanContext) { + return EzyUserRequestAppSingletonController.builder() + .beanContext(beanContext) + .build(); + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestPluginSingletonControllerTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestPluginSingletonControllerTest.java index f4b83a003..93c274137 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestPluginSingletonControllerTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/EzyUserRequestPluginSingletonControllerTest.java @@ -40,48 +40,48 @@ public class EzyUserRequestPluginSingletonControllerTest extends BaseTest { - @Test - public void test() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzyZoneUserManager zoneUserManager = EzyZoneUserManagerImpl.builder() - .zoneName("test") - .build(); - zone.setUserManager(zoneUserManager); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); - pluginSetting.setName("test"); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimplePlugin plugin = new EzySimplePlugin(); - plugin.setSetting(pluginSetting); - plugin.setEventControllers(eventControllers); - - ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimplePluginContext pluginContext = new EzySimplePluginContext(); - pluginContext.setPlugin(plugin); - pluginContext.setParent(zoneContext); - pluginContext.setExecutorService(pluginScheduledExecutorService); - pluginContext.init(); - - EzySimplePluginEntry entry = new EzyPluginEntryEx(); - entry.config(pluginContext); - entry.start(); - handleClientRequest(pluginContext); - EzyBeanContext beanContext = pluginContext.get(EzyBeanContext.class); + @Test + public void test() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzyZoneUserManager zoneUserManager = EzyZoneUserManagerImpl.builder() + .zoneName("test") + .build(); + zone.setUserManager(zoneUserManager); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); + pluginSetting.setName("test"); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimplePlugin plugin = new EzySimplePlugin(); + plugin.setSetting(pluginSetting); + plugin.setEventControllers(eventControllers); + + ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimplePluginContext pluginContext = new EzySimplePluginContext(); + pluginContext.setPlugin(plugin); + pluginContext.setParent(zoneContext); + pluginContext.setExecutorService(pluginScheduledExecutorService); + pluginContext.init(); + + EzySimplePluginEntry entry = new EzyPluginEntryEx(); + entry.config(pluginContext); + entry.start(); + handleClientRequest(pluginContext); + EzyBeanContext beanContext = pluginContext.get(EzyBeanContext.class); EzyRequestCommandManager requestCommandManager = beanContext.getSingleton(EzyRequestCommandManager.class); EzyFeatureCommandManager featureCommandManager = @@ -90,115 +90,115 @@ public void test() throws Exception { Asserts.assertTrue(requestCommandManager.isManagementCommand("v1.2.2/hello")); Asserts.assertTrue(requestCommandManager.isPaymentCommand("v1.2.2/hello")); Asserts.assertEquals(featureCommandManager.getFeatureByCommand("v1.2.2/hello"), "hello.world"); - entry.destroy(); - } - - private void handleClientRequest(EzyPluginContext context) { - EzySimplePlugin plugin = (EzySimplePlugin) context.getPlugin(); - EzyPluginRequestController requestController = plugin.getRequestController(); - - EzyAbstractSession session = spy(EzyAbstractSession.class); - EzySimpleUser user = new EzySimpleUser(); - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append("hello") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - EzyUserRequestPluginEvent event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("responseFactoryTest") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("no command") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("hello2") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("plugin/c_hello") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestSend") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestNotSend") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("plugin/requestException4") - .append(EzyEntityFactory.newObjectBuilder() - .append("who", "Mr.Young Monkey!")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - try { - data = EzyEntityFactory.newArrayBuilder() - .append("exception") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - } - catch (Exception e) { - assert e instanceof IllegalStateException; - } - } - - public static class EzyPluginEntryEx extends EzySimplePluginEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.controller.plugin" - }; - } - - @SuppressWarnings("rawtypes") - @Override - protected Class[] getPrototypeClasses() { - return new Class[] { - }; - } - - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.controller" - }; - } - - @Override - protected EzyPluginRequestController newUserRequestController(EzyBeanContext beanContext) { - return EzyUserRequestPluginSingletonController.builder() - .beanContext(beanContext) - .build(); - } - - } - + entry.destroy(); + } + + private void handleClientRequest(EzyPluginContext context) { + EzySimplePlugin plugin = (EzySimplePlugin) context.getPlugin(); + EzyPluginRequestController requestController = plugin.getRequestController(); + + EzyAbstractSession session = spy(EzyAbstractSession.class); + EzySimpleUser user = new EzySimpleUser(); + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append("hello") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + EzyUserRequestPluginEvent event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("responseFactoryTest") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("no command") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("hello2") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("plugin/c_hello") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestSend") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestNotSend") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("plugin/requestException4") + .append(EzyEntityFactory.newObjectBuilder() + .append("who", "Mr.Young Monkey!")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + try { + data = EzyEntityFactory.newArrayBuilder() + .append("exception") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + } + catch (Exception e) { + assert e instanceof IllegalStateException; + } + } + + public static class EzyPluginEntryEx extends EzySimplePluginEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.controller.plugin" + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected Class[] getPrototypeClasses() { + return new Class[] { + }; + } + + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.controller" + }; + } + + @Override + protected EzyPluginRequestController newUserRequestController(EzyBeanContext beanContext) { + return EzyUserRequestPluginSingletonController.builder() + .beanContext(beanContext) + .build(); + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/Hello.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/Hello.java index e3f486bea..9f10cf074 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/Hello.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/Hello.java @@ -10,6 +10,6 @@ @EzyObjectBinding public class Hello { - protected String who; - + protected String who; + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController.java index 1cb2b7fe3..f43c9cd59 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController.java @@ -15,72 +15,72 @@ @EzyRequestController("Big") public class HelloController { - @EzyAutoBind - protected EzyResponseFactory appResponseFactory; - - @EzyDoHandle("Hello") - public void greet(GreetRequest request, EzyUser user, EzySession session) { - GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); - System.out.println("HelloController::Big/Hello response: " + response); - } - - @EzyDoHandle("Hello2") - public void greet( - @EzyRequestData GreetRequest request, - EzyUser user, EzySession session, Integer nothing) { - GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); - System.out.println("HelloController::Big/Hello response: " + response); - } - - @EzyDoHandle("Hello3") - public void greet( - @EzyRequestData GreetRequest request, - EzyUser user, EzySession session, int nothing) { - GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); - System.out.println("HelloController::Big/Hello response: " + response); - } - - @EzyDoHandle("Hello4") - public void greet( - @EzyRequestData GreetRequest request, - EzyUser user, EzySession session, boolean nothing) { - GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); - System.out.println("HelloController::Big/Hello response: " + response); - } - - @EzyDoHandle("Hello5") - public void greet( - @EzyRequestData GreetRequest request, - EzyUser user, EzySession session, char nothing) { - GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); - System.out.println("HelloController::Big/Hello response: " + response); - } - - @EzyDoHandle("Hello6") + @EzyAutoBind + protected EzyResponseFactory appResponseFactory; + + @EzyDoHandle("Hello") + public void greet(GreetRequest request, EzyUser user, EzySession session) { + GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); + System.out.println("HelloController::Big/Hello response: " + response); + } + + @EzyDoHandle("Hello2") + public void greet( + @EzyRequestData GreetRequest request, + EzyUser user, EzySession session, Integer nothing) { + GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); + System.out.println("HelloController::Big/Hello response: " + response); + } + + @EzyDoHandle("Hello3") + public void greet( + @EzyRequestData GreetRequest request, + EzyUser user, EzySession session, int nothing) { + GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); + System.out.println("HelloController::Big/Hello response: " + response); + } + + @EzyDoHandle("Hello4") + public void greet( + @EzyRequestData GreetRequest request, + EzyUser user, EzySession session, boolean nothing) { + GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); + System.out.println("HelloController::Big/Hello response: " + response); + } + + @EzyDoHandle("Hello5") + public void greet( + @EzyRequestData GreetRequest request, + EzyUser user, EzySession session, char nothing) { + GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); + System.out.println("HelloController::Big/Hello response: " + response); + } + + @EzyDoHandle("Hello6") public Object greetAndReturn(GreetRequest request) { return new GreetResponse("Hello " + request.getWho() + "!"); } - - @EzyTryCatch({IllegalStateException.class, IllegalArgumentException.class}) - public void handleException1(Exception e) { - e.printStackTrace(); - } - - @EzyTryCatch({RuntimeException.class}) - public void handleException2( - RuntimeException e, - GreetRequest request, - EzyUser user, EzySession session, EzyContext context) { - e.printStackTrace(); - } - - @EzyTryCatch({IllegalArgumentException.class}) - public void handleException3( - IllegalArgumentException e, - String cmd, - GreetRequest request, - EzyUser user, EzySession session, EzyContext context) { - System.out.println("HelloController:handleException:IllegalArgumentException, cmd = " + cmd); - } - + + @EzyTryCatch({IllegalStateException.class, IllegalArgumentException.class}) + public void handleException1(Exception e) { + e.printStackTrace(); + } + + @EzyTryCatch({RuntimeException.class}) + public void handleException2( + RuntimeException e, + GreetRequest request, + EzyUser user, EzySession session, EzyContext context) { + e.printStackTrace(); + } + + @EzyTryCatch({IllegalArgumentException.class}) + public void handleException3( + IllegalArgumentException e, + String cmd, + GreetRequest request, + EzyUser user, EzySession session, EzyContext context) { + System.out.println("HelloController:handleException:IllegalArgumentException, cmd = " + cmd); + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController2.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController2.java index ee9931f1f..b241a8057 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController2.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/HelloController2.java @@ -13,21 +13,21 @@ @EzyRequestController("Big") public class HelloController2 { - @EzyAutoBind - protected EzyResponseFactory appResponseFactory; - - @EzyDoHandle("Hello") - public void greet(GreetRequest request, EzyUser user, EzySession session) { - GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); - System.out.println("HelloController::Big/Hello response: " + response); - } - - @EzyDoHandle("Hello") - public void greet( - @EzyRequestData GreetRequest request, - EzyUser user, EzySession session, Integer nothing) { - GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); - System.out.println("HelloController::Big/Hello response: " + response); - } - + @EzyAutoBind + protected EzyResponseFactory appResponseFactory; + + @EzyDoHandle("Hello") + public void greet(GreetRequest request, EzyUser user, EzySession session) { + GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); + System.out.println("HelloController::Big/Hello response: " + response); + } + + @EzyDoHandle("Hello") + public void greet( + @EzyRequestData GreetRequest request, + EzyUser user, EzySession session, Integer nothing) { + GreetResponse response = new GreetResponse("Hello " + request.getWho() + "!"); + System.out.println("HelloController::Big/Hello response: " + response); + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestNotSendRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestNotSendRequestHandler.java index 69f6e36d2..871f1b372 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestNotSendRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestNotSendRequestHandler.java @@ -11,12 +11,12 @@ @EzySingleton @EzyRequestListener("badRequestNotSend") public class AppBadRequestNotSendRequestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { + + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + throw new EzyBadRequestException(1, "server maintain", false); + } - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - throw new EzyBadRequestException(1, "server maintain", false); - } - } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestSendRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestSendRequestHandler.java index ebc08daa3..f1ca5cb38 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestSendRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppBadRequestSendRequestHandler.java @@ -11,11 +11,11 @@ @EzySingleton @EzyRequestListener("badRequestSend") public class AppBadRequestSendRequestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - throw new EzyBadRequestException(1, "server maintain", true); - } + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + throw new EzyBadRequestException(1, "server maintain", true); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientExceptionRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientExceptionRequestHandler.java index 8f7e88b0b..5a4407794 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientExceptionRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientExceptionRequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("exception") public class AppClientExceptionRequestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - throw new IllegalStateException("server maintain"); - } + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + throw new IllegalStateException("server maintain"); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello2RequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello2RequestHandler.java index 490ab4bb3..392984d67 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello2RequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello2RequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello2") public class AppClientHello2RequestHandler - extends EzyAbstractUserRequestHandler { - - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("hello: " + data.getWho()); - } + extends EzyAbstractUserRequestHandler { + + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("hello: " + data.getWho()); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello3RequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello3RequestHandler.java index a05dc9ce9..9906299cd 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello3RequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello3RequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello") public class AppClientHello3RequestHandler - implements EzyUserRequestAppHandler { - - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("hello: " + data.getWho()); - } + implements EzyUserRequestAppHandler { + + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("hello: " + data.getWho()); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello4RequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello4RequestHandler.java index a8b390123..12ecbf98b 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello4RequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello4RequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello4") public class AppClientHello4RequestHandler - implements EzyUserRequestAppHandler { - - @Override - public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { - System.out.println("hello with: " + data); - } + implements EzyUserRequestAppHandler { + + @Override + public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { + System.out.println("hello with: " + data); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello5RequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello5RequestHandler.java index 56b1b5143..49846044f 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello5RequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello5RequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello5") public class AppClientHello5RequestHandler - extends EzyAbstractUserRequestHandler { - - @Override - public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { - System.out.println("hello with: " + data); - } + extends EzyAbstractUserRequestHandler { + + @Override + public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { + System.out.println("hello with: " + data); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello6RequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello6RequestHandler.java index eda64bfc0..78aa9e496 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello6RequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHello6RequestHandler.java @@ -10,10 +10,10 @@ @EzySingleton @EzyRequestListener("hello6") public class AppClientHello6RequestHandler implements EzyUserRequestHandler { - - @Override - public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { - System.out.println("hello with: " + data); - } + + @Override + public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { + System.out.println("hello with: " + data); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestController.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestController.java index 2ea19c938..2d032824a 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestController.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestController.java @@ -14,57 +14,57 @@ @EzyRequestController public class AppClientHelloRequestController { - @EzyDoHandle("c_hello") - public void handleHello(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("app: c_hello: " + data.getWho()); - } - - @EzyDoHandle("c_hello1") - public void handleHello1(EzyAppContext context, EzyUserSessionEvent event) { - System.out.println("app: c_hello1"); - } - - @EzyDoHandle("c_hello2") - public void handleHello2() { - System.out.println("app: c_hello2"); - } - - @EzyDoHandle("c_hello3") - public void handleHello3(EzyUser user) { - System.out.println("app: c_hello3"); - } - - @EzyDoHandle("c_hello4") - public void handleHello4(EzySession session) { - System.out.println("app: c_hello4"); - } - - @EzyDoHandle("c_hello5") - public void handleHello5(EzyContext context) { - System.out.println("app: c_hello5"); - } - - @EzyDoHandle("c_hello6") - public void handleHello6(EzyContext context, String value, Exception e) { - System.out.println("app: c_hello6"); - } - - @EzyDoHandle("requestException") - public void handleRequestException(EzyContext context, Hello data) { - throw new RequestException(getClass().getSimpleName() + ":handlerequestException"); - } - - @EzyDoHandle("requestException2") - public void handleRequestException2( - EzyContext context, - String cmd, - @EzyRequestData Hello data) throws Exception { - throw new Exception(getClass().getSimpleName() + ":handleRequestException2, cmd = " + cmd); - } - - @EzyDoHandle("requestException3") - public void handleRequestException3(EzyContext context) throws Exception { - throw new IllegalArgumentException(getClass().getSimpleName() + ":handleRequestException3"); - } - + @EzyDoHandle("c_hello") + public void handleHello(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("app: c_hello: " + data.getWho()); + } + + @EzyDoHandle("c_hello1") + public void handleHello1(EzyAppContext context, EzyUserSessionEvent event) { + System.out.println("app: c_hello1"); + } + + @EzyDoHandle("c_hello2") + public void handleHello2() { + System.out.println("app: c_hello2"); + } + + @EzyDoHandle("c_hello3") + public void handleHello3(EzyUser user) { + System.out.println("app: c_hello3"); + } + + @EzyDoHandle("c_hello4") + public void handleHello4(EzySession session) { + System.out.println("app: c_hello4"); + } + + @EzyDoHandle("c_hello5") + public void handleHello5(EzyContext context) { + System.out.println("app: c_hello5"); + } + + @EzyDoHandle("c_hello6") + public void handleHello6(EzyContext context, String value, Exception e) { + System.out.println("app: c_hello6"); + } + + @EzyDoHandle("requestException") + public void handleRequestException(EzyContext context, Hello data) { + throw new RequestException(getClass().getSimpleName() + ":handlerequestException"); + } + + @EzyDoHandle("requestException2") + public void handleRequestException2( + EzyContext context, + String cmd, + @EzyRequestData Hello data) throws Exception { + throw new Exception(getClass().getSimpleName() + ":handleRequestException2, cmd = " + cmd); + } + + @EzyDoHandle("requestException3") + public void handleRequestException3(EzyContext context) throws Exception { + throw new IllegalArgumentException(getClass().getSimpleName() + ":handleRequestException3"); + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestHandler.java index 366377752..b4bdaa2aa 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppClientHelloRequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello") public class AppClientHelloRequestHandler - implements EzyUserRequestHandler { - - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("hello: " + data.getWho()); - } + implements EzyUserRequestHandler { + + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("hello: " + data.getWho()); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppGlobalExceptionHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppGlobalExceptionHandler.java index 14e4d6a2d..d0b9a603a 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppGlobalExceptionHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppGlobalExceptionHandler.java @@ -11,32 +11,32 @@ @EzyExceptionHandler public class AppGlobalExceptionHandler extends EzyLoggable { - @EzyTryCatch(RequestException.class) - public void handleRequestException(RequestException e, - EzyUserSessionEvent event, - boolean boolValue, - int intValue, - Void voidData, - String cmd, - Hello data, - String stringValue) { - logger.error("try cath RequestException, data: {}", data, e); - } - - @EzyTryCatch(IllegalArgumentException.class) - public void handleIllegalArgumentException( - IllegalArgumentException e, - String cmd, - @EzyRequestData Object data) { - logger.error("try cath IllegalArgumentException, cmd = {}, data = {}", cmd, data, e); - } - - @EzyTryCatch(Exception.class) - public void handleException( - Exception e, - String cmd, - @EzyRequestData Object data) throws Exception { - throw e; - } - + @EzyTryCatch(RequestException.class) + public void handleRequestException(RequestException e, + EzyUserSessionEvent event, + boolean boolValue, + int intValue, + Void voidData, + String cmd, + Hello data, + String stringValue) { + logger.error("try cath RequestException, data: {}", data, e); + } + + @EzyTryCatch(IllegalArgumentException.class) + public void handleIllegalArgumentException( + IllegalArgumentException e, + String cmd, + @EzyRequestData Object data) { + logger.error("try cath IllegalArgumentException, cmd = {}, data = {}", cmd, data, e); + } + + @EzyTryCatch(Exception.class) + public void handleException( + Exception e, + String cmd, + @EzyRequestData Object data) throws Exception { + throw e; + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor.java index 1f692abbf..e1245dd11 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor.java @@ -6,6 +6,6 @@ @EzyRequestInterceptor public class AppRequestInteceptor - implements EzyUserRequestInterceptor { + implements EzyUserRequestInterceptor { } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor2.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor2.java index 6c360e52c..8dc68e6b1 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor2.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppRequestInteceptor2.java @@ -6,6 +6,6 @@ @EzyRequestInterceptor(priority = 1) public class AppRequestInteceptor2 - implements EzyUserRequestInterceptor { + implements EzyUserRequestInterceptor { } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppResponseFactoryTestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppResponseFactoryTestHandler.java index 0f643d0ee..a2f75caa2 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppResponseFactoryTestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/AppResponseFactoryTestHandler.java @@ -17,56 +17,56 @@ @EzySingleton @EzyRequestListener("responseFactoryTest") public class AppResponseFactoryTestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { + + @EzyAutoBind("appResponseFactory") + protected EzyResponseFactory responseFactory; + + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + responseFactory.newArrayResponse() + .command("hello") + .data(EzyEntityFactory.newArrayBuilder()) + .param(1) + .params(2, 3) + .params(Lists.newArrayList(4, 5)) + .user(event.getUser()) + .users(event.getUser()) + .users(Lists.newArrayList(event.getUser())) + .session(event.getSession()) + .sessions(event.getSession()) + .sessions(Lists.newArrayList(event.getSession())) + .username(event.getUser().getName()) + .usernames(event.getUser().getName()) + .usernames(Lists.newArrayList(event.getUser().getName())) + .execute(); + + responseFactory.newArrayResponse() + .command("hello") + .usernames(Lists.newArrayList(event.getUser().getName())) + .execute(); + + responseFactory.newObjectResponse() + .command("hello") + .data(EzyEntityFactory.newObjectBuilder()) + .param("1", 1) + .param("2", 2) + .exclude("2") + .user(event.getUser()) + .users(event.getUser()) + .users(Lists.newArrayList(event.getUser())) + .session(event.getSession()) + .sessions(event.getSession()) + .sessions(Lists.newArrayList(event.getSession())) + .username(event.getUser().getName()) + .usernames(event.getUser().getName()) + .usernames(Lists.newArrayList(event.getUser().getName())) + .execute(); + + responseFactory.newObjectResponse() + .command("hello") + .usernames(Lists.newArrayList(event.getUser().getName())) + .execute(); + } - @EzyAutoBind("appResponseFactory") - protected EzyResponseFactory responseFactory; - - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - responseFactory.newArrayResponse() - .command("hello") - .data(EzyEntityFactory.newArrayBuilder()) - .param(1) - .params(2, 3) - .params(Lists.newArrayList(4, 5)) - .user(event.getUser()) - .users(event.getUser()) - .users(Lists.newArrayList(event.getUser())) - .session(event.getSession()) - .sessions(event.getSession()) - .sessions(Lists.newArrayList(event.getSession())) - .username(event.getUser().getName()) - .usernames(event.getUser().getName()) - .usernames(Lists.newArrayList(event.getUser().getName())) - .execute(); - - responseFactory.newArrayResponse() - .command("hello") - .usernames(Lists.newArrayList(event.getUser().getName())) - .execute(); - - responseFactory.newObjectResponse() - .command("hello") - .data(EzyEntityFactory.newObjectBuilder()) - .param("1", 1) - .param("2", 2) - .exclude("2") - .user(event.getUser()) - .users(event.getUser()) - .users(Lists.newArrayList(event.getUser())) - .session(event.getSession()) - .sessions(event.getSession()) - .sessions(Lists.newArrayList(event.getSession())) - .username(event.getUser().getName()) - .usernames(event.getUser().getName()) - .usernames(Lists.newArrayList(event.getUser().getName())) - .execute(); - - responseFactory.newObjectResponse() - .command("hello") - .usernames(Lists.newArrayList(event.getUser().getName())) - .execute(); - } - } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestFeatureEmptyHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestFeatureEmptyHandler.java index 7e1a2fe90..56cb67ea6 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestFeatureEmptyHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestFeatureEmptyHandler.java @@ -16,11 +16,11 @@ @EzyFeature("") @EzyRequestListener("v122/listener/hello_feature_empty") public class V122AppClientHelloRequestFeatureEmptyHandler - implements EzyUserRequestHandler { - - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("hello: " + data.getWho()); - } + implements EzyUserRequestHandler { + + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("hello: " + data.getWho()); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestHandler.java index 96967bc1d..13e48ddf5 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/app/V122AppClientHelloRequestHandler.java @@ -16,11 +16,11 @@ @EzyFeature("hello.world") @EzyRequestListener("v122/listener/hello") public class V122AppClientHelloRequestHandler - implements EzyUserRequestHandler { - - @Override - public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("hello: " + data.getWho()); - } + implements EzyUserRequestHandler { + + @Override + public void handle(EzyAppContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("hello: " + data.getWho()); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestNotSendRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestNotSendRequestHandler.java index 8a64c58da..9bf2ac215 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestNotSendRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestNotSendRequestHandler.java @@ -11,11 +11,11 @@ @EzySingleton @EzyRequestListener("badRequestNotSend") public class PluginBadRequestNotSendRequestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { - @Override - public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { - throw new EzyBadRequestException(1, "server maintain", false); - } + @Override + public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { + throw new EzyBadRequestException(1, "server maintain", false); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestSendRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestSendRequestHandler.java index 9a452b6a4..99d01b5f3 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestSendRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginBadRequestSendRequestHandler.java @@ -11,11 +11,11 @@ @EzySingleton @EzyRequestListener("badRequestSend") public class PluginBadRequestSendRequestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { - @Override - public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { - throw new EzyBadRequestException(1, "server maintain", true); - } + @Override + public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { + throw new EzyBadRequestException(1, "server maintain", true); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientExceptionRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientExceptionRequestHandler.java index 6a0b1e334..13a441661 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientExceptionRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientExceptionRequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("exception") public class PluginClientExceptionRequestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { - @Override - public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { - throw new IllegalStateException("server maintain"); - } + @Override + public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { + throw new IllegalStateException("server maintain"); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello2RequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello2RequestHandler.java index 5c50091fd..c7f2b47d6 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello2RequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello2RequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello2") public class PluginClientHello2RequestHandler - implements EzyUserRequestPluginHandler { + implements EzyUserRequestPluginHandler { - @Override - public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("hello: " + data.getWho()); - } + @Override + public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("hello: " + data.getWho()); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello3RequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello3RequestHandler.java index 3f37ad85b..a08cd9079 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello3RequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHello3RequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello3") public class PluginClientHello3RequestHandler - implements EzyUserRequestPluginHandler { + implements EzyUserRequestPluginHandler { - @Override - public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { - System.out.println("hello: " + data); - } + @Override + public void handle(EzyContext context, EzyUserSessionEvent event, Object data) { + System.out.println("hello: " + data); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestController.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestController.java index 7edf2bd71..0220c6ed8 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestController.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestController.java @@ -14,29 +14,29 @@ @EzyRequestController("plugin") public class PluginClientHelloRequestController { - @EzyDoHandle("c_hello") - public void handleHello( - EzyPluginContext context, - @EzyRequestData Hello data, - EzyUser user) { - System.out.println("plugin: c_hello: " + data.getWho()); - } - - @EzyDoHandle("requestException4") - public void handleRequestException4( - EzyContext context, - String cmd, - @EzyRequestData Hello data) throws Exception { - throw new RequestException4(getClass().getSimpleName() + ":handleRequestException4, cmd = " + cmd); - } - - @EzyTryCatch({RequestException4.class}) - public void handleRequestException2( - RequestException4 e, - String cmd, - Hello request, - EzyUser user, EzySession session, EzyContext context) { - System.out.println("PluginClientHelloRequestController::handleRequestException2, cmd = " + cmd + ", data = " + request + ", e = " + e); - } - + @EzyDoHandle("c_hello") + public void handleHello( + EzyPluginContext context, + @EzyRequestData Hello data, + EzyUser user) { + System.out.println("plugin: c_hello: " + data.getWho()); + } + + @EzyDoHandle("requestException4") + public void handleRequestException4( + EzyContext context, + String cmd, + @EzyRequestData Hello data) throws Exception { + throw new RequestException4(getClass().getSimpleName() + ":handleRequestException4, cmd = " + cmd); + } + + @EzyTryCatch({RequestException4.class}) + public void handleRequestException2( + RequestException4 e, + String cmd, + Hello request, + EzyUser user, EzySession session, EzyContext context) { + System.out.println("PluginClientHelloRequestController::handleRequestException2, cmd = " + cmd + ", data = " + request + ", e = " + e); + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestHandler.java index 5614bb785..b81cf68d4 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginClientHelloRequestHandler.java @@ -10,11 +10,11 @@ @EzySingleton @EzyRequestListener("hello") public class PluginClientHelloRequestHandler - implements EzyUserRequestPluginHandler { + implements EzyUserRequestPluginHandler { - @Override - public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { - System.out.println("hello: " + data.getWho()); - } + @Override + public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { + System.out.println("hello: " + data.getWho()); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginResponseFactoryTestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginResponseFactoryTestHandler.java index 98a02e576..d84dceea6 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginResponseFactoryTestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/PluginResponseFactoryTestHandler.java @@ -18,58 +18,58 @@ @EzySingleton @EzyRequestListener("responseFactoryTest") public class PluginResponseFactoryTestHandler - implements EzyUserRequestHandler { + implements EzyUserRequestHandler { - @EzyAutoBind("pluginResponseFactory") - protected EzyResponseFactory responseFactory; - - @Override - public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { - responseFactory.newArrayResponse() - .command("hello") - .data(EzyEntityFactory.newArrayBuilder()) - .param(1) - .params(2, 3) - .params(Lists.newArrayList(4, 5)) - .user(event.getUser()) - .users(event.getUser()) - .users(Lists.newArrayList(event.getUser())) - .session(event.getSession()) - .sessions(event.getSession()) - .sessions(Lists.newArrayList(event.getSession())) - .username(event.getUser().getName()) - .usernames(event.getUser().getName()) - .usernames(Lists.newArrayList(event.getUser().getName())) - .execute(); - - responseFactory.newArrayResponse() - .command("hello") - .usernames(Lists.newArrayList(event.getUser().getName())) - .execute(); - - responseFactory.newObjectResponse() - .command("hello") - .data(EzyEntityFactory.newObjectBuilder()) - .param("1", 1) - .param("2", 2) - .exclude("2") - .user(event.getUser()) - .users(event.getUser()) - .users(Lists.newArrayList(event.getUser())) - .session(event.getSession()) - .sessions(event.getSession()) - .sessions(Lists.newArrayList(event.getSession())) - .username(event.getUser().getName()) - .usernames(event.getUser().getName()) - .usernames(Lists.newArrayList(event.getUser().getName())) - .transportType(EzyTransportType.TCP) - .udpTransport() - .execute(); - - responseFactory.newObjectResponse() - .command("hello") - .usernames(Lists.newArrayList(event.getUser().getName())) - .execute(); - } - + @EzyAutoBind("pluginResponseFactory") + protected EzyResponseFactory responseFactory; + + @Override + public void handle(EzyPluginContext context, EzyUserSessionEvent event, Hello data) { + responseFactory.newArrayResponse() + .command("hello") + .data(EzyEntityFactory.newArrayBuilder()) + .param(1) + .params(2, 3) + .params(Lists.newArrayList(4, 5)) + .user(event.getUser()) + .users(event.getUser()) + .users(Lists.newArrayList(event.getUser())) + .session(event.getSession()) + .sessions(event.getSession()) + .sessions(Lists.newArrayList(event.getSession())) + .username(event.getUser().getName()) + .usernames(event.getUser().getName()) + .usernames(Lists.newArrayList(event.getUser().getName())) + .execute(); + + responseFactory.newArrayResponse() + .command("hello") + .usernames(Lists.newArrayList(event.getUser().getName())) + .execute(); + + responseFactory.newObjectResponse() + .command("hello") + .data(EzyEntityFactory.newObjectBuilder()) + .param("1", 1) + .param("2", 2) + .exclude("2") + .user(event.getUser()) + .users(event.getUser()) + .users(Lists.newArrayList(event.getUser())) + .session(event.getSession()) + .sessions(event.getSession()) + .sessions(Lists.newArrayList(event.getSession())) + .username(event.getUser().getName()) + .usernames(event.getUser().getName()) + .usernames(Lists.newArrayList(event.getUser().getName())) + .transportType(EzyTransportType.TCP) + .udpTransport() + .execute(); + + responseFactory.newObjectResponse() + .command("hello") + .usernames(Lists.newArrayList(event.getUser().getName())) + .execute(); + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestHandler.java index b096a3c5b..f6785b36a 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestHandler.java @@ -18,5 +18,5 @@ public class V122HelloRequestHandler implements EzyHandler, EzyDataBinding { @Override public void handle() {} - + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestWithFeatureEmptyHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestWithFeatureEmptyHandler.java index 4755b9448..8a038457f 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestWithFeatureEmptyHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/controller/plugin/V122HelloRequestWithFeatureEmptyHandler.java @@ -18,5 +18,5 @@ public class V122HelloRequestWithFeatureEmptyHandler implements EzyHandler, EzyD @Override public void handle() {} - + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetRequest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetRequest.java index 1b02f030a..37e322e49 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetRequest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetRequest.java @@ -12,6 +12,6 @@ @AllArgsConstructor public class GreetRequest { - protected String who; - + protected String who; + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetResponse.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetResponse.java index 68eaa96be..3a808c5ff 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetResponse.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/data/GreetResponse.java @@ -10,6 +10,6 @@ @EzyObjectBinding(read = false) public class GreetResponse { - protected String message; - + protected String message; + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientAppRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientAppRequestHandler.java index 2a47ed436..67143336b 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientAppRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientAppRequestHandler.java @@ -11,15 +11,15 @@ @Setter @EzyRequestListener("app") public class ClientAppRequestHandler - extends EzyLoggable - implements - EzyAppContextAware, - EzyHandler { + extends EzyLoggable + implements + EzyAppContextAware, + EzyHandler { - protected EzyAppContext appContext; - - @Override - public void handle() { - } + protected EzyAppContext appContext; + + @Override + public void handle() { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestNoSendRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestNoSendRequestHandler.java index 5cad5481c..51fc65d5d 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestNoSendRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestNoSendRequestHandler.java @@ -12,13 +12,13 @@ @EzyPrototype @EzyRequestListener("badRequestNoSend") public class ClientBadRequestNoSendRequestHandler - extends EzyLoggable - implements - EzyHandler { + extends EzyLoggable + implements + EzyHandler { - @Override - public void handle() { - throw new EzyBadRequestException(1, "test", false); - } + @Override + public void handle() { + throw new EzyBadRequestException(1, "test", false); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestSendRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestSendRequestHandler.java index e9b93a4a9..713d6828f 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestSendRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientBadRequestSendRequestHandler.java @@ -12,13 +12,13 @@ @EzyPrototype @EzyRequestListener("badRequestSend") public class ClientBadRequestSendRequestHandler - extends EzyLoggable - implements - EzyHandler { + extends EzyLoggable + implements + EzyHandler { - @Override - public void handle() { - throw new EzyBadRequestException(1, "test", true); - } + @Override + public void handle() { + throw new EzyBadRequestException(1, "test", true); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientChatRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientChatRequestHandler.java index a2dfc9ce6..289bbc500 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientChatRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientChatRequestHandler.java @@ -18,18 +18,18 @@ @EzyRequestListener("chat") @EzyObjectBinding(read = false) public class ClientChatRequestHandler - extends EzyLoggable - implements - EzyHandler, - EzyUserAware, - EzySessionAware, - EzyDataBinding { + extends EzyLoggable + implements + EzyHandler, + EzyUserAware, + EzySessionAware, + EzyDataBinding { - protected EzyUser user; - protected EzySession session; - - @Override - public void handle() { - } + protected EzyUser user; + protected EzySession session; + + @Override + public void handle() { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientExceptionRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientExceptionRequestHandler.java index c28e71805..e10ef4fa6 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientExceptionRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientExceptionRequestHandler.java @@ -11,13 +11,13 @@ @EzyPrototype @EzyRequestListener("exception") public class ClientExceptionRequestHandler - extends EzyLoggable - implements - EzyHandler { + extends EzyLoggable + implements + EzyHandler { - @Override - public void handle() { - throw new IllegalStateException("server maintain"); - } + @Override + public void handle() { + throw new IllegalStateException("server maintain"); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoDataBindingRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoDataBindingRequestHandler.java index df2362ddd..c4fbfd217 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoDataBindingRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoDataBindingRequestHandler.java @@ -11,12 +11,12 @@ @EzyPrototype @EzyRequestListener("noDataBinding") public class ClientNoDataBindingRequestHandler - extends EzyLoggable - implements - EzyHandler { + extends EzyLoggable + implements + EzyHandler { - @Override - public void handle() { - } + @Override + public void handle() { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoSessionRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoSessionRequestHandler.java index 830c0a77e..f18d421b8 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoSessionRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoSessionRequestHandler.java @@ -14,13 +14,13 @@ @EzyRequestListener("noSession") @EzyObjectBinding(read = false) public class ClientNoSessionRequestHandler - extends EzyLoggable - implements - EzyHandler, - EzyDataBinding { + extends EzyLoggable + implements + EzyHandler, + EzyDataBinding { - @Override - public void handle() { - } + @Override + public void handle() { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoUserRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoUserRequestHandler.java index 8dcba02f7..df83446a9 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoUserRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientNoUserRequestHandler.java @@ -16,16 +16,16 @@ @EzyRequestListener("noUser") @EzyObjectBinding(read = false) public class ClientNoUserRequestHandler - extends EzyLoggable - implements - EzyHandler, - EzySessionAware, - EzyDataBinding { + extends EzyLoggable + implements + EzyHandler, + EzySessionAware, + EzyDataBinding { - protected EzySession session; - - @Override - public void handle() { - } + protected EzySession session; + + @Override + public void handle() { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientPluginRequestHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientPluginRequestHandler.java index 25b7886a3..52c9b28dd 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientPluginRequestHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ClientPluginRequestHandler.java @@ -11,15 +11,15 @@ @Setter @EzyRequestListener("plugin") public class ClientPluginRequestHandler - extends EzyLoggable - implements - EzyPluginContextAware, - EzyHandler { + extends EzyLoggable + implements + EzyPluginContextAware, + EzyHandler { - protected EzyPluginContext pluginContext; - - @Override - public void handle() { - } + protected EzyPluginContext pluginContext; + + @Override + public void handle() { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultAppEntryTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultAppEntryTest.java index 8ed4d5011..20ac551be 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultAppEntryTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultAppEntryTest.java @@ -36,221 +36,221 @@ public class EzyDefaultAppEntryTest { - @Test - public void test() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); - appSetting.setName("test"); - appSetting.setActiveProfiles("hello,world"); - appSetting.setPackageName("x.z.y"); - - EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() - .build(); + @Test + public void test() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); + appSetting.setName("test"); + appSetting.setActiveProfiles("hello,world"); + appSetting.setPackageName("x.z.y"); + + EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() + .build(); - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimpleApplication application = new EzySimpleApplication(); - application.setSetting(appSetting); - application.setUserManager(appUserManager); - application.setEventControllers(eventControllers); - - ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimpleAppContext appContext = new EzySimpleAppContext(); - appContext.setApp(application); - appContext.setParent(zoneContext); - appContext.setExecutorService(appScheduledExecutorService); - appContext.init(); - - EzySimpleAppEntry entry = new EzyAppEntryEx(); - entry.config(appContext); - entry.start(); - handleClientRequest(appContext); - entry.destroy(); - } - - private void handleClientRequest(EzyAppContext context) { - EzySimpleApplication app = (EzySimpleApplication) context.getApp(); - EzyAppRequestController requestController = app.getRequestController(); - - EzyAbstractSession session = spy(EzyAbstractSession.class); - EzySimpleUser user = new EzySimpleUser(); - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - EzyUserRequestAppEvent event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("no command") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noUser") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noSession") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noDataBinding") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestSend") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestNoSend") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("exception") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - try { - requestController.handle(context, event); - } - catch (Exception e) { - assert e instanceof IllegalStateException; - } - - data = EzyEntityFactory.newArrayBuilder() - .append("app") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - } - - @Test - public void test2() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); - appSetting.setName("test"); - - EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() - .build(); + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimpleApplication application = new EzySimpleApplication(); + application.setSetting(appSetting); + application.setUserManager(appUserManager); + application.setEventControllers(eventControllers); + + ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimpleAppContext appContext = new EzySimpleAppContext(); + appContext.setApp(application); + appContext.setParent(zoneContext); + appContext.setExecutorService(appScheduledExecutorService); + appContext.init(); + + EzySimpleAppEntry entry = new EzyAppEntryEx(); + entry.config(appContext); + entry.start(); + handleClientRequest(appContext); + entry.destroy(); + } + + private void handleClientRequest(EzyAppContext context) { + EzySimpleApplication app = (EzySimpleApplication) context.getApp(); + EzyAppRequestController requestController = app.getRequestController(); + + EzyAbstractSession session = spy(EzyAbstractSession.class); + EzySimpleUser user = new EzySimpleUser(); + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + EzyUserRequestAppEvent event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("no command") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noUser") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noSession") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noDataBinding") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestSend") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestNoSend") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("exception") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + try { + requestController.handle(context, event); + } + catch (Exception e) { + assert e instanceof IllegalStateException; + } + + data = EzyEntityFactory.newArrayBuilder() + .append("app") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + } + + @Test + public void test2() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); + appSetting.setName("test"); + + EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() + .build(); - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimpleApplication application = new EzySimpleApplication(); - application.setSetting(appSetting); - application.setUserManager(appUserManager); - application.setEventControllers(eventControllers); - - ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimpleAppContext appContext = new EzySimpleAppContext(); - appContext.setApp(application); - appContext.setParent(zoneContext); - appContext.setExecutorService(appScheduledExecutorService); - appContext.init(); - - EzySimpleAppEntry entry = new EzyAppEntryEx2(); - entry.config(appContext); - entry.start(); - entry.destroy(); - } - - public static class EzyAppEntryEx extends EzyDefaultAppEntry { + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimpleApplication application = new EzySimpleApplication(); + application.setSetting(appSetting); + application.setUserManager(appUserManager); + application.setEventControllers(eventControllers); + + ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimpleAppContext appContext = new EzySimpleAppContext(); + appContext.setApp(application); + appContext.setParent(zoneContext); + appContext.setExecutorService(appScheduledExecutorService); + appContext.init(); + + EzySimpleAppEntry entry = new EzyAppEntryEx2(); + entry.config(appContext); + entry.start(); + entry.destroy(); + } + + public static class EzyAppEntryEx extends EzyDefaultAppEntry { - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } - - @SuppressWarnings("rawtypes") - @Override - protected Class[] getPrototypeClasses() { - return new Class[] { - ClientAppRequestHandler.class - }; - } + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected Class[] getPrototypeClasses() { + return new Class[] { + ClientAppRequestHandler.class + }; + } - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } - @Override - protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { - } - - } - - public static class EzyAppEntryEx2 extends EzyDefaultAppEntry { + @Override + protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { + } + + } + + public static class EzyAppEntryEx2 extends EzyDefaultAppEntry { - @Override - protected String[] getScanableBeanPackages() { - return new String[0]; - } + @Override + protected String[] getScanableBeanPackages() { + return new String[0]; + } - @Override - protected String[] getScanableBindingPackages() { - return new String[0]; - } + @Override + protected String[] getScanableBindingPackages() { + return new String[0]; + } - @Override - protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { - } - - } - + @Override + protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultPluginEntryTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultPluginEntryTest.java index e62059535..fd9e46ddc 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultPluginEntryTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzyDefaultPluginEntryTest.java @@ -34,208 +34,208 @@ public class EzyDefaultPluginEntryTest { - @Test - public void test() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); - pluginSetting.setName("test"); - pluginSetting.setActiveProfiles("hello,world"); - pluginSetting.setPackageName("x.z.y"); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimplePlugin plugin = new EzySimplePlugin(); - plugin.setSetting(pluginSetting); - plugin.setEventControllers(eventControllers); - - ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimplePluginContext pluginContext = new EzySimplePluginContext(); - pluginContext.setPlugin(plugin); - pluginContext.setParent(zoneContext); - pluginContext.setExecutorService(pluginScheduledExecutorService); - pluginContext.init(); - - EzySimplePluginEntry entry = new EzyPluginEntryEx(); - entry.config(pluginContext); - entry.start(); - handleClientRequest(pluginContext); - entry.destroy(); - } - - private void handleClientRequest(EzyPluginContext context) { - EzySimplePlugin plugin = (EzySimplePlugin) context.getPlugin(); - EzyPluginRequestController requestController = plugin.getRequestController(); - - EzyAbstractSession session = spy(EzyAbstractSession.class); - EzySimpleUser user = new EzySimpleUser(); - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - EzyUserRequestPluginEvent event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("no command") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noUser") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noSession") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noDataBinding") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestSend") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestNoSend") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("exception") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - try { - requestController.handle(context, event); - } - catch (Exception e) { - assert e instanceof IllegalStateException; - } - - data = EzyEntityFactory.newArrayBuilder() - .append("plugin") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - } - - @Test - public void test2() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); - pluginSetting.setName("test"); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimplePlugin plugin = new EzySimplePlugin(); - plugin.setSetting(pluginSetting); - plugin.setEventControllers(eventControllers); - - ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimplePluginContext pluginContext = new EzySimplePluginContext(); - pluginContext.setPlugin(plugin); - pluginContext.setParent(zoneContext); - pluginContext.setExecutorService(pluginScheduledExecutorService); - pluginContext.init(); - - EzySimplePluginEntry entry = new EzyPluginEntryEx2(); - entry.config(pluginContext); - entry.start(); - entry.destroy(); - } - - public static class EzyPluginEntryEx extends EzyDefaultPluginEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } - - @SuppressWarnings("rawtypes") - @Override - protected Class[] getPrototypeClasses() { - return new Class[] { - ClientPluginRequestHandler.class - }; - } - - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } - - @Override - protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { - } - - } - - public static class EzyPluginEntryEx2 extends EzyDefaultPluginEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[0]; - } - - @Override - protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { - } - - } - + @Test + public void test() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); + pluginSetting.setName("test"); + pluginSetting.setActiveProfiles("hello,world"); + pluginSetting.setPackageName("x.z.y"); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimplePlugin plugin = new EzySimplePlugin(); + plugin.setSetting(pluginSetting); + plugin.setEventControllers(eventControllers); + + ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimplePluginContext pluginContext = new EzySimplePluginContext(); + pluginContext.setPlugin(plugin); + pluginContext.setParent(zoneContext); + pluginContext.setExecutorService(pluginScheduledExecutorService); + pluginContext.init(); + + EzySimplePluginEntry entry = new EzyPluginEntryEx(); + entry.config(pluginContext); + entry.start(); + handleClientRequest(pluginContext); + entry.destroy(); + } + + private void handleClientRequest(EzyPluginContext context) { + EzySimplePlugin plugin = (EzySimplePlugin) context.getPlugin(); + EzyPluginRequestController requestController = plugin.getRequestController(); + + EzyAbstractSession session = spy(EzyAbstractSession.class); + EzySimpleUser user = new EzySimpleUser(); + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + EzyUserRequestPluginEvent event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("no command") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noUser") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noSession") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noDataBinding") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestSend") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestNoSend") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("exception") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + try { + requestController.handle(context, event); + } + catch (Exception e) { + assert e instanceof IllegalStateException; + } + + data = EzyEntityFactory.newArrayBuilder() + .append("plugin") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + } + + @Test + public void test2() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); + pluginSetting.setName("test"); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimplePlugin plugin = new EzySimplePlugin(); + plugin.setSetting(pluginSetting); + plugin.setEventControllers(eventControllers); + + ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimplePluginContext pluginContext = new EzySimplePluginContext(); + pluginContext.setPlugin(plugin); + pluginContext.setParent(zoneContext); + pluginContext.setExecutorService(pluginScheduledExecutorService); + pluginContext.init(); + + EzySimplePluginEntry entry = new EzyPluginEntryEx2(); + entry.config(pluginContext); + entry.start(); + entry.destroy(); + } + + public static class EzyPluginEntryEx extends EzyDefaultPluginEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected Class[] getPrototypeClasses() { + return new Class[] { + ClientPluginRequestHandler.class + }; + } + + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } + + @Override + protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { + } + + } + + public static class EzyPluginEntryEx2 extends EzyDefaultPluginEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[0]; + } + + @Override + protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimpleAppEntryTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimpleAppEntryTest.java index c10e64b0c..73d730cdc 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimpleAppEntryTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimpleAppEntryTest.java @@ -40,48 +40,48 @@ public class EzySimpleAppEntryTest { @SuppressWarnings({ "rawtypes" }) - @Test - public void test() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); - appSetting.setName("test"); - - EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() - .build(); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimpleApplication application = new EzySimpleApplication(); - application.setSetting(appSetting); - application.setUserManager(appUserManager); - application.setEventControllers(eventControllers); - - ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimpleAppContext appContext = new EzySimpleAppContext(); - appContext.setApp(application); - appContext.setParent(zoneContext); - appContext.setExecutorService(appScheduledExecutorService); - appContext.init(); - - EzySimpleAppEntry entry = new EzyAppEntryEx(); - entry.config(appContext); - entry.start(); - handleClientRequest(appContext); - + @Test + public void test() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); + appSetting.setName("test"); + + EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() + .build(); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimpleApplication application = new EzySimpleApplication(); + application.setSetting(appSetting); + application.setUserManager(appUserManager); + application.setEventControllers(eventControllers); + + ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimpleAppContext appContext = new EzySimpleAppContext(); + appContext.setApp(application); + appContext.setParent(zoneContext); + appContext.setExecutorService(appScheduledExecutorService); + appContext.init(); + + EzySimpleAppEntry entry = new EzyAppEntryEx(); + entry.config(appContext); + entry.start(); + handleClientRequest(appContext); + List serverReadyHandlers = appContext .getApp() .getEventControllers() @@ -96,169 +96,169 @@ public void test() throws Exception { .getControllers(EzyEventType.USER_LOGIN); Assert.assertEquals(loginEventHandlers.size(), 1); Assert.assertEquals(loginEventHandlers.get(0).getClass(), AppUserLoginRequestController.class); - - entry.destroy(); - } - - private void handleClientRequest(EzyAppContext context) { - EzySimpleApplication app = (EzySimpleApplication) context.getApp(); - EzyAppRequestController requestController = app.getRequestController(); - - EzyAbstractSession session = spy(EzyAbstractSession.class); - EzySimpleUser user = new EzySimpleUser(); - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - EzyUserRequestAppEvent event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("no command") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noUser") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noSession") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noDataBinding") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestSend") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestNoSend") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("exception") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - try { - requestController.handle(context, event); - } - catch (Exception e) { - assert e instanceof IllegalStateException; - } - - data = EzyEntityFactory.newArrayBuilder() - .append("app") - .build(); - event = new EzySimpleUserRequestAppEvent(user, session, data); - requestController.handle(context, event); - } - + + entry.destroy(); + } + + private void handleClientRequest(EzyAppContext context) { + EzySimpleApplication app = (EzySimpleApplication) context.getApp(); + EzyAppRequestController requestController = app.getRequestController(); + + EzyAbstractSession session = spy(EzyAbstractSession.class); + EzySimpleUser user = new EzySimpleUser(); + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + EzyUserRequestAppEvent event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("no command") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noUser") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noSession") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noDataBinding") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestSend") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestNoSend") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("exception") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + try { + requestController.handle(context, event); + } + catch (Exception e) { + assert e instanceof IllegalStateException; + } + + data = EzyEntityFactory.newArrayBuilder() + .append("app") + .build(); + event = new EzySimpleUserRequestAppEvent(user, session, data); + requestController.handle(context, event); + } + @Test - public void test2() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); - appSetting.setName("test"); - - EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() - .build(); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimpleApplication application = new EzySimpleApplication(); - application.setSetting(appSetting); - application.setUserManager(appUserManager); - application.setEventControllers(eventControllers); - - ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimpleAppContext appContext = new EzySimpleAppContext(); - appContext.setApp(application); - appContext.setParent(zoneContext); - appContext.setExecutorService(appScheduledExecutorService); - appContext.init(); - - EzySimpleAppEntry entry = new EzyAppEntryEx2(); - entry.config(appContext); - entry.start(); - entry.destroy(); - } - - public static class EzyAppEntryEx extends EzySimpleAppEntry { - - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } - - @SuppressWarnings("rawtypes") - @Override - protected Class[] getPrototypeClasses() { - return new Class[] { - ClientAppRequestHandler.class - }; - } - - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } - - @Override - protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { - } - - } - - public static class EzyAppEntryEx2 extends EzySimpleAppEntry { - - @Override - protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { - } - - } - + public void test2() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); + appSetting.setName("test"); + + EzyAppUserManager appUserManager = EzyAppUserManagerImpl.builder() + .build(); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimpleApplication application = new EzySimpleApplication(); + application.setSetting(appSetting); + application.setUserManager(appUserManager); + application.setEventControllers(eventControllers); + + ScheduledExecutorService appScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimpleAppContext appContext = new EzySimpleAppContext(); + appContext.setApp(application); + appContext.setParent(zoneContext); + appContext.setExecutorService(appScheduledExecutorService); + appContext.init(); + + EzySimpleAppEntry entry = new EzyAppEntryEx2(); + entry.config(appContext); + entry.start(); + entry.destroy(); + } + + public static class EzyAppEntryEx extends EzySimpleAppEntry { + + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected Class[] getPrototypeClasses() { + return new Class[] { + ClientAppRequestHandler.class + }; + } + + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } + + @Override + protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { + } + + } + + public static class EzyAppEntryEx2 extends EzySimpleAppEntry { + + @Override + protected void setupBeanContext(EzyAppContext context, EzyBeanContextBuilder builder) { + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimplePluginEntryTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimplePluginEntryTest.java index bafe235be..5ad50b336 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimplePluginEntryTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/EzySimplePluginEntryTest.java @@ -37,209 +37,209 @@ public class EzySimplePluginEntryTest { - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes") @Test - public void test() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); - pluginSetting.setName("test"); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimplePlugin plugin = new EzySimplePlugin(); - plugin.setSetting(pluginSetting); - plugin.setEventControllers(eventControllers); - - ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimplePluginContext pluginContext = new EzySimplePluginContext(); - pluginContext.setPlugin(plugin); - pluginContext.setParent(zoneContext); - pluginContext.setExecutorService(pluginScheduledExecutorService); - pluginContext.init(); - - EzySimplePluginEntry entry = new EzyPluginEntryEx(); - entry.config(pluginContext); - entry.start(); - handleClientRequest(pluginContext); - - List loginEventHandlers = pluginContext + public void test() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); + pluginSetting.setName("test"); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimplePlugin plugin = new EzySimplePlugin(); + plugin.setSetting(pluginSetting); + plugin.setEventControllers(eventControllers); + + ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimplePluginContext pluginContext = new EzySimplePluginContext(); + pluginContext.setPlugin(plugin); + pluginContext.setParent(zoneContext); + pluginContext.setExecutorService(pluginScheduledExecutorService); + pluginContext.init(); + + EzySimplePluginEntry entry = new EzyPluginEntryEx(); + entry.config(pluginContext); + entry.start(); + handleClientRequest(pluginContext); + + List loginEventHandlers = pluginContext .getPlugin() .getEventControllers() .getControllers(EzyEventType.USER_LOGIN); Assert.assertEquals(loginEventHandlers.size(), 1); Assert.assertEquals(loginEventHandlers.get(0).getClass(), PluginUserLoginRequestController.class); - entry.destroy(); - } - - private void handleClientRequest(EzyPluginContext context) { - EzySimplePlugin plugin = (EzySimplePlugin) context.getPlugin(); - EzyPluginRequestController requestController = plugin.getRequestController(); - - EzyAbstractSession session = spy(EzyAbstractSession.class); - EzySimpleUser user = new EzySimpleUser(); - EzyArray data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - EzyUserRequestPluginEvent event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("chat") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("no command") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noUser") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noSession") - .append(EzyEntityFactory.newObjectBuilder() - .append("message", "greet")) - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("noDataBinding") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestSend") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("badRequestNoSend") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - - data = EzyEntityFactory.newArrayBuilder() - .append("exception") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - try { - requestController.handle(context, event); - } - catch (Exception e) { - assert e instanceof IllegalStateException; - } - - data = EzyEntityFactory.newArrayBuilder() - .append("plugin") - .build(); - event = new EzySimpleUserRequestPluginEvent(user, session, data); - requestController.handle(context, event); - } - - @Test - public void test2() throws Exception { - EzySimpleSettings settings = new EzySimpleSettings(); - EzySimpleServer server = new EzySimpleServer(); - server.setSettings(settings); - EzySimpleServerContext serverContext = new EzySimpleServerContext(); - serverContext.setServer(server); - serverContext.init(); - - EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); - EzySimpleZone zone = new EzySimpleZone(); - zone.setSetting(zoneSetting); - EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); - zoneContext.setZone(zone); - zoneContext.init(); - zoneContext.setParent(serverContext); - - EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); - pluginSetting.setName("test"); - - EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); - EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); - EzySimplePlugin plugin = new EzySimplePlugin(); - plugin.setSetting(pluginSetting); - plugin.setEventControllers(eventControllers); - - ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); - EzySimplePluginContext pluginContext = new EzySimplePluginContext(); - pluginContext.setPlugin(plugin); - pluginContext.setParent(zoneContext); - pluginContext.setExecutorService(pluginScheduledExecutorService); - pluginContext.init(); - - EzySimplePluginEntry entry = new EzyPluginEntryEx2(); - entry.config(pluginContext); - entry.start(); - entry.destroy(); - } - - public static class EzyPluginEntryEx extends EzySimplePluginEntry { + entry.destroy(); + } + + private void handleClientRequest(EzyPluginContext context) { + EzySimplePlugin plugin = (EzySimplePlugin) context.getPlugin(); + EzyPluginRequestController requestController = plugin.getRequestController(); + + EzyAbstractSession session = spy(EzyAbstractSession.class); + EzySimpleUser user = new EzySimpleUser(); + EzyArray data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + EzyUserRequestPluginEvent event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("chat") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("no command") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noUser") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noSession") + .append(EzyEntityFactory.newObjectBuilder() + .append("message", "greet")) + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("noDataBinding") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestSend") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("badRequestNoSend") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + + data = EzyEntityFactory.newArrayBuilder() + .append("exception") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + try { + requestController.handle(context, event); + } + catch (Exception e) { + assert e instanceof IllegalStateException; + } + + data = EzyEntityFactory.newArrayBuilder() + .append("plugin") + .build(); + event = new EzySimpleUserRequestPluginEvent(user, session, data); + requestController.handle(context, event); + } + + @Test + public void test2() throws Exception { + EzySimpleSettings settings = new EzySimpleSettings(); + EzySimpleServer server = new EzySimpleServer(); + server.setSettings(settings); + EzySimpleServerContext serverContext = new EzySimpleServerContext(); + serverContext.setServer(server); + serverContext.init(); + + EzySimpleZoneSetting zoneSetting = new EzySimpleZoneSetting(); + EzySimpleZone zone = new EzySimpleZone(); + zone.setSetting(zoneSetting); + EzySimpleZoneContext zoneContext = new EzySimpleZoneContext(); + zoneContext.setZone(zone); + zoneContext.init(); + zoneContext.setParent(serverContext); + + EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); + pluginSetting.setName("test"); + + EzyEventControllersSetting eventControllersSetting = new EzySimpleEventControllersSetting(); + EzyEventControllers eventControllers = EzyEventControllersImpl.create(eventControllersSetting); + EzySimplePlugin plugin = new EzySimplePlugin(); + plugin.setSetting(pluginSetting); + plugin.setEventControllers(eventControllers); + + ScheduledExecutorService pluginScheduledExecutorService = new EzyErrorScheduledExecutorService("not implement"); + EzySimplePluginContext pluginContext = new EzySimplePluginContext(); + pluginContext.setPlugin(plugin); + pluginContext.setParent(zoneContext); + pluginContext.setExecutorService(pluginScheduledExecutorService); + pluginContext.init(); + + EzySimplePluginEntry entry = new EzyPluginEntryEx2(); + entry.config(pluginContext); + entry.start(); + entry.destroy(); + } + + public static class EzyPluginEntryEx extends EzySimplePluginEntry { - @Override - protected String[] getScanableBeanPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } - - @SuppressWarnings("rawtypes") - @Override - protected Class[] getPrototypeClasses() { - return new Class[] { - ClientPluginRequestHandler.class - }; - } + @Override + protected String[] getScanableBeanPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected Class[] getPrototypeClasses() { + return new Class[] { + ClientPluginRequestHandler.class + }; + } - @Override - protected String[] getScanableBindingPackages() { - return new String[] { - "com.tvd12.ezyfoxserver.support.test.entry" - }; - } + @Override + protected String[] getScanableBindingPackages() { + return new String[] { + "com.tvd12.ezyfoxserver.support.test.entry" + }; + } - @Override - protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { - } - - } - - public static class EzyPluginEntryEx2 extends EzySimplePluginEntry { + @Override + protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { + } + + } + + public static class EzyPluginEntryEx2 extends EzySimplePluginEntry { - @Override - protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { - } - - } - + @Override + protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) { + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler.java index 71d820575..9287676cb 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler.java @@ -11,8 +11,8 @@ @EzyEventHandler(value = EzyEventNames.SERVER_READY, priority = Integer.MAX_VALUE) public class ServerReadyEventHandler implements EzyServerReadyController { - @Override - public void handle(EzyServerContext ctx, EzyServerReadyEvent event) { - } + @Override + public void handle(EzyServerContext ctx, EzyServerReadyEvent event) { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler2.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler2.java index b044da1b7..ec75615f2 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler2.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/entry/ServerReadyEventHandler2.java @@ -11,8 +11,8 @@ @EzyEventHandler(EzyEventNames.SERVER_READY) public class ServerReadyEventHandler2 implements EzyServerReadyController { - @Override - public void handle(EzyServerContext ctx, EzyServerReadyEvent event) { - } + @Override + public void handle(EzyServerContext ctx, EzyServerReadyEvent event) { + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/EzyUserRequestExceptionTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/EzyUserRequestExceptionTest.java index a4eba7b30..4ead7b660 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/EzyUserRequestExceptionTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/EzyUserRequestExceptionTest.java @@ -6,11 +6,11 @@ public class EzyUserRequestExceptionTest { - @Test - public void test() { - EzyUserRequestException ex = new EzyUserRequestException("cmd", "data", new Exception()); - assert ex.getCommand().equals("cmd"); - assert ex.getData().equals("data"); - } - + @Test + public void test() { + EzyUserRequestException ex = new EzyUserRequestException("cmd", "data", new Exception()); + assert ex.getCommand().equals("cmd"); + assert ex.getData().equals("data"); + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException.java index 08b20df88..8a4373d94 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException.java @@ -1,10 +1,10 @@ package com.tvd12.ezyfoxserver.support.test.exception; public class RequestException extends RuntimeException { - private static final long serialVersionUID = 6040054244978864625L; - - public RequestException(String msg) { - super(msg); - } + private static final long serialVersionUID = 6040054244978864625L; + + public RequestException(String msg) { + super(msg); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException4.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException4.java index e10d4d419..3493149cb 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException4.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/exception/RequestException4.java @@ -1,10 +1,10 @@ package com.tvd12.ezyfoxserver.support.test.exception; public class RequestException4 extends RuntimeException { - private static final long serialVersionUID = 6040054244978864625L; - - public RequestException4(String msg) { - super(msg); - } + private static final long serialVersionUID = 6040054244978864625L; + + public RequestException4(String msg) { + super(msg); + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyExceptionHandlerProxyTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyExceptionHandlerProxyTest.java index ac9b65293..18f85202d 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyExceptionHandlerProxyTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyExceptionHandlerProxyTest.java @@ -7,20 +7,20 @@ public class EzyExceptionHandlerProxyTest { - @Test - public void test() { - EzyExceptionHandlerProxy proxy = new EzyExceptionHandlerProxy( - new ExceptionHandlerEx()); - System.out.println(proxy.toString()); - } - - public static class ExceptionHandlerEx { - - @EzyTryCatch(Exception.class) - public void handle(Exception e) { - e.printStackTrace(); - } - - } - + @Test + public void test() { + EzyExceptionHandlerProxy proxy = new EzyExceptionHandlerProxy( + new ExceptionHandlerEx()); + System.out.println(proxy.toString()); + } + + public static class ExceptionHandlerEx { + + @EzyTryCatch(Exception.class) + public void handle(Exception e) { + e.printStackTrace(); + } + + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestControllerTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestControllerTest.java index b2cc09847..d781608cb 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestControllerTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestControllerTest.java @@ -7,14 +7,14 @@ public class EzyRequestControllerTest { - @Test - public void test() { - Object instance = new HelloController(); - EzyRequestControllerProxy controllerProxy = - new EzyRequestControllerProxy(instance); - assert controllerProxy.getInstance() == instance; - assert controllerProxy.getExceptionHandlerMethods().size() >= 0; - System.out.println(controllerProxy); - } - + @Test + public void test() { + Object instance = new HelloController(); + EzyRequestControllerProxy controllerProxy = + new EzyRequestControllerProxy(instance); + assert controllerProxy.getInstance() == instance; + assert controllerProxy.getExceptionHandlerMethods().size() >= 0; + System.out.println(controllerProxy); + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestHandlerMethodTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestHandlerMethodTest.java index 9ca47b00c..0d010cd3b 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestHandlerMethodTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/test/reflect/EzyRequestHandlerMethodTest.java @@ -9,14 +9,14 @@ public class EzyRequestHandlerMethodTest { - @Test - public void test() throws Exception { - EzyMethod method = new EzyMethod(AppClientHelloRequestController.class - .getDeclaredMethod("handleHello5", EzyContext.class)); - EzyRequestHandlerMethod handlerMethod = new EzyRequestHandlerMethod("c_hello5", method); - assert handlerMethod.getMethod() == method; - System.out.println(handlerMethod); - assert handlerMethod.getParameterTypes().length >= 0; - } - + @Test + public void test() throws Exception { + EzyMethod method = new EzyMethod(AppClientHelloRequestController.class + .getDeclaredMethod("handleHello5", EzyContext.class)); + EzyRequestHandlerMethod handlerMethod = new EzyRequestHandlerMethod("c_hello5", method); + assert handlerMethod.getMethod() == method; + System.out.println(handlerMethod); + assert handlerMethod.getParameterTypes().length >= 0; + } + } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimpleAppEntryTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimpleAppEntryTest.java index 44bcadb59..1bfe2e0d4 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimpleAppEntryTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimpleAppEntryTest.java @@ -27,68 +27,68 @@ import lombok.Setter; public class EzySimpleAppEntryTest { - - @Test - public void scanPackages() { - // given - EzyAppContext appContext = mock(EzyAppContext.class); - ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyApplication application = mock(EzyApplication.class); - EzyAppUserManager appUserManager = mock(EzyAppUserManager.class); - EzyAppSetup appSetup = mock(EzyAppSetup.class); - + + @Test + public void scanPackages() { + // given + EzyAppContext appContext = mock(EzyAppContext.class); + ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyApplication application = mock(EzyApplication.class); + EzyAppUserManager appUserManager = mock(EzyAppUserManager.class); + EzyAppSetup appSetup = mock(EzyAppSetup.class); + EzyAppSetting appSetting = mock(EzyAppSetting.class); when(application.getSetting()).thenReturn(appSetting); - - InternalAppEntry sut = new InternalAppEntry(); - - // when - when(appContext.get(ScheduledExecutorService.class)).thenReturn(executorService); - when(appContext.getParent()).thenReturn(zoneContext); - when(zoneContext.getParent()).thenReturn(serverContext); - when(appContext.getApp()).thenReturn(application); - when(application.getUserManager()).thenReturn(appUserManager); - when(appContext.get(EzyAppSetup.class)).thenReturn(appSetup); - - sut.config(appContext); - - // then - EzyBeanContext beanContext = sut.beanContext; - MongoConfig mongoConfig = (MongoConfig) beanContext.getBean(MongoConfig.class); - - Set expectedPackages = Sets.newHashSet( - EzySupportConstants.DEFAULT_PACKAGE_TO_SCAN, - "com.tvd12.ezyfoxserver.support.v120.test.entry" - ); - - Asserts.assertEquals(expectedPackages, mongoConfig.packagesToScan); - - Singleton singleton = (Singleton) beanContext.getBean(Singleton.class); - Asserts.assertNotNull(singleton); - } - - @EzySingleton - public static class Singleton {} - - @Setter - @EzyConfigurationBefore - public static class MongoConfig implements EzyPackagesToScanAware { - public Set packagesToScan; - } - - private static class InternalAppEntry extends EzySimpleAppEntry { - public EzyBeanContext beanContext; - - @Override - protected String[] getScanablePackages() { - return new String[]{"com.tvd12.ezyfoxserver.support.v120.test.entry"}; - } - - @Override - protected void postConfig(EzyAppContext context, EzyBeanContext beanContext) { - this.beanContext = beanContext; - } - } + + InternalAppEntry sut = new InternalAppEntry(); + + // when + when(appContext.get(ScheduledExecutorService.class)).thenReturn(executorService); + when(appContext.getParent()).thenReturn(zoneContext); + when(zoneContext.getParent()).thenReturn(serverContext); + when(appContext.getApp()).thenReturn(application); + when(application.getUserManager()).thenReturn(appUserManager); + when(appContext.get(EzyAppSetup.class)).thenReturn(appSetup); + + sut.config(appContext); + + // then + EzyBeanContext beanContext = sut.beanContext; + MongoConfig mongoConfig = (MongoConfig) beanContext.getBean(MongoConfig.class); + + Set expectedPackages = Sets.newHashSet( + EzySupportConstants.DEFAULT_PACKAGE_TO_SCAN, + "com.tvd12.ezyfoxserver.support.v120.test.entry" + ); + + Asserts.assertEquals(expectedPackages, mongoConfig.packagesToScan); + + Singleton singleton = (Singleton) beanContext.getBean(Singleton.class); + Asserts.assertNotNull(singleton); + } + + @EzySingleton + public static class Singleton {} + + @Setter + @EzyConfigurationBefore + public static class MongoConfig implements EzyPackagesToScanAware { + public Set packagesToScan; + } + + private static class InternalAppEntry extends EzySimpleAppEntry { + public EzyBeanContext beanContext; + + @Override + protected String[] getScanablePackages() { + return new String[]{"com.tvd12.ezyfoxserver.support.v120.test.entry"}; + } + + @Override + protected void postConfig(EzyAppContext context, EzyBeanContext beanContext) { + this.beanContext = beanContext; + } + } } diff --git a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimplePluginEntryTest.java b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimplePluginEntryTest.java index 239d088a5..4ddcb8368 100644 --- a/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimplePluginEntryTest.java +++ b/ezyfox-server-support/src/test/java/com/tvd12/ezyfoxserver/support/v120/test/entry/EzySimplePluginEntryTest.java @@ -29,137 +29,137 @@ import lombok.Setter; public class EzySimplePluginEntryTest { - - @Test - public void scanPackages() { - // given - EzyPluginContext pluginContext = mock(EzyPluginContext.class); - ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyPluginSetup pluginSetup = mock(EzyPluginSetup.class); - - EzyPlugin plugin = mock(EzyPlugin.class); - when(pluginContext.getPlugin()).thenReturn(plugin); - - EzyPluginSetting pluginSetting = mock(EzyPluginSetting.class); - when(plugin.getSetting()).thenReturn(pluginSetting); - - InteralPluginEngtry sut = new InteralPluginEngtry(); - - // when - when(pluginContext.get(ScheduledExecutorService.class)).thenReturn(executorService); - when(pluginContext.getParent()).thenReturn(zoneContext); - when(zoneContext.getParent()).thenReturn(serverContext); - when(pluginContext.get(EzyPluginSetup.class)).thenReturn(pluginSetup); - - sut.config(pluginContext); - - // then - EzyBeanContext beanContext = sut.beanContext; - MongoConfig mongoConfig = (MongoConfig) beanContext.getBean(MongoConfig.class); - - Set expectedPackages = Sets.newHashSet( - EzySupportConstants.DEFAULT_PACKAGE_TO_SCAN, - "com.tvd12.ezyfoxserver.support.v120.test.entry" - ); - - Asserts.assertEquals(expectedPackages, mongoConfig.packagesToScan); - - Singleton singleton = (Singleton) beanContext.getBean(Singleton.class); - Asserts.assertNotNull(singleton); - } - - @Test - public void notAllowRequestTest() { - // given - EzyPluginContext pluginContext = mock(EzyPluginContext.class); - ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyPluginSetup pluginSetup = mock(EzyPluginSetup.class); - - EzyPlugin plugin = mock(EzyPlugin.class); + + @Test + public void scanPackages() { + // given + EzyPluginContext pluginContext = mock(EzyPluginContext.class); + ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyPluginSetup pluginSetup = mock(EzyPluginSetup.class); + + EzyPlugin plugin = mock(EzyPlugin.class); + when(pluginContext.getPlugin()).thenReturn(plugin); + + EzyPluginSetting pluginSetting = mock(EzyPluginSetting.class); + when(plugin.getSetting()).thenReturn(pluginSetting); + + InteralPluginEngtry sut = new InteralPluginEngtry(); + + // when + when(pluginContext.get(ScheduledExecutorService.class)).thenReturn(executorService); + when(pluginContext.getParent()).thenReturn(zoneContext); + when(zoneContext.getParent()).thenReturn(serverContext); + when(pluginContext.get(EzyPluginSetup.class)).thenReturn(pluginSetup); + + sut.config(pluginContext); + + // then + EzyBeanContext beanContext = sut.beanContext; + MongoConfig mongoConfig = (MongoConfig) beanContext.getBean(MongoConfig.class); + + Set expectedPackages = Sets.newHashSet( + EzySupportConstants.DEFAULT_PACKAGE_TO_SCAN, + "com.tvd12.ezyfoxserver.support.v120.test.entry" + ); + + Asserts.assertEquals(expectedPackages, mongoConfig.packagesToScan); + + Singleton singleton = (Singleton) beanContext.getBean(Singleton.class); + Asserts.assertNotNull(singleton); + } + + @Test + public void notAllowRequestTest() { + // given + EzyPluginContext pluginContext = mock(EzyPluginContext.class); + ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyPluginSetup pluginSetup = mock(EzyPluginSetup.class); + + EzyPlugin plugin = mock(EzyPlugin.class); when(pluginContext.getPlugin()).thenReturn(plugin); EzyPluginSetting pluginSetting = mock(EzyPluginSetting.class); when(plugin.getSetting()).thenReturn(pluginSetting); - - NotAllowRequestEngtry sut = new NotAllowRequestEngtry(); - - // when - when(pluginContext.get(ScheduledExecutorService.class)).thenReturn(executorService); - when(pluginContext.getParent()).thenReturn(zoneContext); - when(zoneContext.getParent()).thenReturn(serverContext); - when(pluginContext.get(EzyPluginSetup.class)).thenReturn(pluginSetup); - - sut.config(pluginContext); - - // then - verify(pluginContext, times(0)).get(EzyPluginSetup.class); - } - - @Test - public void disallowRequestTest() { - // given - EzyPluginContext pluginContext = mock(EzyPluginContext.class); - ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); - EzyZoneContext zoneContext = mock(EzyZoneContext.class); - EzyServerContext serverContext = mock(EzyServerContext.class); - EzyPluginSetup pluginSetup = mock(EzyPluginSetup.class); - - EzyPlugin plugin = mock(EzyPlugin.class); + + NotAllowRequestEngtry sut = new NotAllowRequestEngtry(); + + // when + when(pluginContext.get(ScheduledExecutorService.class)).thenReturn(executorService); + when(pluginContext.getParent()).thenReturn(zoneContext); + when(zoneContext.getParent()).thenReturn(serverContext); + when(pluginContext.get(EzyPluginSetup.class)).thenReturn(pluginSetup); + + sut.config(pluginContext); + + // then + verify(pluginContext, times(0)).get(EzyPluginSetup.class); + } + + @Test + public void disallowRequestTest() { + // given + EzyPluginContext pluginContext = mock(EzyPluginContext.class); + ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); + EzyZoneContext zoneContext = mock(EzyZoneContext.class); + EzyServerContext serverContext = mock(EzyServerContext.class); + EzyPluginSetup pluginSetup = mock(EzyPluginSetup.class); + + EzyPlugin plugin = mock(EzyPlugin.class); when(pluginContext.getPlugin()).thenReturn(plugin); EzyPluginSetting pluginSetting = mock(EzyPluginSetting.class); when(plugin.getSetting()).thenReturn(pluginSetting); - - DisAllowRequestEngtry sut = new DisAllowRequestEngtry(); - - // when - when(pluginContext.get(ScheduledExecutorService.class)).thenReturn(executorService); - when(pluginContext.getParent()).thenReturn(zoneContext); - when(zoneContext.getParent()).thenReturn(serverContext); - when(pluginContext.get(EzyPluginSetup.class)).thenReturn(pluginSetup); - - sut.config(pluginContext); - - // then - verify(pluginContext, times(0)).get(EzyPluginSetup.class); - } - - @EzySingleton - public static class Singleton { - } - - @Setter - @EzyConfigurationBefore - public static class MongoConfig implements EzyPackagesToScanAware { - public Set packagesToScan; - } - - private static class InteralPluginEngtry extends EzySimplePluginEntry { - public EzyBeanContext beanContext; - - @Override - protected String[] getScanablePackages() { - return new String[]{"com.tvd12.ezyfoxserver.support.v120.test.entry"}; - } - - @Override - protected void postConfig(EzyPluginContext ctx, EzyBeanContext beanContext) { - this.beanContext = beanContext; - } - } - - private static class NotAllowRequestEngtry extends EzySimplePluginEntry { - @Override - protected boolean allowRequest() { - return false; - } - } - - @EzyDisallowRequest - private static class DisAllowRequestEngtry extends EzySimplePluginEntry { - } + + DisAllowRequestEngtry sut = new DisAllowRequestEngtry(); + + // when + when(pluginContext.get(ScheduledExecutorService.class)).thenReturn(executorService); + when(pluginContext.getParent()).thenReturn(zoneContext); + when(zoneContext.getParent()).thenReturn(serverContext); + when(pluginContext.get(EzyPluginSetup.class)).thenReturn(pluginSetup); + + sut.config(pluginContext); + + // then + verify(pluginContext, times(0)).get(EzyPluginSetup.class); + } + + @EzySingleton + public static class Singleton { + } + + @Setter + @EzyConfigurationBefore + public static class MongoConfig implements EzyPackagesToScanAware { + public Set packagesToScan; + } + + private static class InteralPluginEngtry extends EzySimplePluginEntry { + public EzyBeanContext beanContext; + + @Override + protected String[] getScanablePackages() { + return new String[]{"com.tvd12.ezyfoxserver.support.v120.test.entry"}; + } + + @Override + protected void postConfig(EzyPluginContext ctx, EzyBeanContext beanContext) { + this.beanContext = beanContext; + } + } + + private static class NotAllowRequestEngtry extends EzySimplePluginEntry { + @Override + protected boolean allowRequest() { + return false; + } + } + + @EzyDisallowRequest + private static class DisAllowRequestEngtry extends EzySimplePluginEntry { + } } diff --git a/ezyfox-server-support/src/test/resources/AllTests.tng.xml b/ezyfox-server-support/src/test/resources/AllTests.tng.xml index 1c847066c..2f4442e18 100644 --- a/ezyfox-server-support/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-support/src/test/resources/AllTests.tng.xml @@ -3,17 +3,17 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index ca1d79e4f..056958cbc 100644 --- a/pom.xml +++ b/pom.xml @@ -1,71 +1,71 @@ - 4.0.0 - - com.tvd12 - ezyfox - 1.0.4 - - ezyfox-server - 1.2.3 - pom + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + com.tvd12 + ezyfox + 1.0.4 + + ezyfox-server + 1.2.3 + pom - ezyfox-server - https://youngmonkeys.org/project/ezyfox-sever/ - - EzyFox Server maven project configuration - + ezyfox-server + https://youngmonkeys.org/project/ezyfox-sever/ + + EzyFox Server maven project configuration + - - Young Monkeys - https://youngmonkeys.org/ - + + Young Monkeys + https://youngmonkeys.org/ + - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + - - scm:git:git@github.com:youngmonkeys/ezyfox-server.git - scm:git:git@github.com:youngmonkeys/ezyfox-server.git - https://github.com/youngmonkeys/ezyfox-server - + + scm:git:git@github.com:youngmonkeys/ezyfox-server.git + scm:git:git@github.com:youngmonkeys/ezyfox-server.git + https://github.com/youngmonkeys/ezyfox-server + - - Github - https://github.com/youngmonkeys/ezyfox-server/issues - + + Github + https://github.com/youngmonkeys/ezyfox-server/issues + - - travis - https://travis-ci.org/youngmonkeys/ezyfox-server - + + travis + https://travis-ci.org/youngmonkeys/ezyfox-server + - - - Ta Van Dung - itprono3@gmail.com - Young Monkeys - https://youngmonkeys.org/ - - + + + Ta Van Dung + itprono3@gmail.com + Young Monkeys + https://youngmonkeys.org/ + + - - 2.1.4 - + + 2.1.4 + - - ezyfox-server-core - ezyfox-server-boot - ezyfox-server-nio - ezyfox-server-niorunner - ezyfox-server-support - ezyfox-server-embedded - + + ezyfox-server-core + ezyfox-server-boot + ezyfox-server-nio + ezyfox-server-niorunner + ezyfox-server-support + ezyfox-server-embedded +